Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 31 additions & 11 deletions base-convert/CANONICAL_QUANT_SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,21 @@ per-tensor flexibility for the canonical bit-widths.
## Goals

- One canonical kernel family per bit-width per backend.
- Source format restricted to **fp16 / bf16 / fp32**. Already-quantized
sources are rejected with a clear error — no silent quant-to-quant
re-pack (it's lossy and contradicts the bit budget). Users with a
GGUF Q4_K_M only must re-fetch the bf16 original.
- Quant happens at convert time. Multiple methods supported (AWQ,
GPTQ, SmoothQuant, RTN); converter picks per use case.
- Quantization starts from **fp16 / bf16 / fp32** sources. Applying a
profile to an already-quantized source (GGUF, MLX 4/8-bit) is refused
unless `--allow-quant-from-quant` is given, since it re-packs lossy
weights. Source quantization can instead be kept as it is
(`--kquant-passthrough` for GGUF k-quants and i-quants,
`--mlx-passthrough` for MLX 4-bit).
- Quant happens at convert time. A profile rule picks round-to-nearest
(`"algo": "rtn"`, the default) or AWQ (`"algo": "awq"`, with an
`--awq-profile` sidecar).
- Mixed precision per-tensor (e.g. `mlp.experts: q4`, `mlp.shared_ffn:
q8`, `lm_head: bf16`).
- Multi-platform: Apple Silicon (Metal), CUDA, ROCm. **One bundle per
target backend**; the converter takes `--target=metal|cuda|rocm`.
- Multi-platform: Apple Silicon (Metal), CUDA, ROCm. The converter has no
backend flag (`--target` names the quant scheme); a build for one
backend is a profile chosen for it, and the catalog publishes those
builds as variants.

## Bit-width defaults

Expand Down Expand Up @@ -116,6 +121,19 @@ one backend is not portable to another — re-convert from source.
- Inherit MLX's affine packing exactly, so byte-identical bundles can
be produced from MLX checkpoints (when source is fp16/bf16, not from
pre-quantized MLX weights).
- A *pre-quantized* MLX 4-bit checkpoint at group size 64 is the one
case where quant-from-quant is not lossy: `base_q4` is that same
scheme, so `--target base-q4` transplants the packed codes and the
f16 scale/bias pair verbatim rather than requantizing (disable with
`--no-mlx-passthrough`). This is not merely an optimization.
Re-deriving `scale = (max - min) / 15` from already-quantized values
lands on a *different* grid whenever a group's codes do not span the
full 0..15 range, so dequant → requant is **not** the identity.
Transplanting reproduces MLX's weights bit-for-bit, which is what
makes an MLX-vs-baseRT numerical comparison attributable to engine
math rather than to conversion. Tensors whose rows get permuted on
the way through (rotary q/k), stacked or split virtual tensors, and
any `--profile` run keep the f32 path.
- Power-of-2 widths (q2/q4/q8): concatenated little-endian, lane `i`
at bit `i*bits` in a uint32. Pack factor = `32/bits`.
- q3 / q5: bit-spread across 3 / 5 bytes per 8 lanes.
Expand Down Expand Up @@ -171,7 +189,7 @@ backwards-compat with current `base_q4` bundles):

## Quant profile JSON

Profiles live in `tools/base-convert/profiles/`. Reusable + diffable.
Profiles live in `profiles/` beside this file. Reusable + diffable.
The converter consumes one via `--profile <path>`; the resulting
bundle records the profile name in `quant_profile` for audit.

Expand Down Expand Up @@ -214,8 +232,10 @@ dense models.
biases are stored as bf16. Norms are stored at f16. The `*-f16scale.json`
profiles (`default-q4-f16scale.json`, `default-q8-f16scale.json`) select
f16 scales instead.
- The source checkpoint must be fp16/bf16/fp32. Re-quantizing an
already-quantized checkpoint (e.g. a GGUF Q4_K) is not a supported target.
- A profile applies to fp16/bf16/fp32 checkpoints. Re-quantizing an
already-quantized checkpoint (e.g. a GGUF Q4_K) needs
`--allow-quant-from-quant`; keeping its blocks as they are needs
`--kquant-passthrough`.

## Validation criterion

Expand Down
16 changes: 8 additions & 8 deletions base-convert/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion base-convert/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ members = [
]

[workspace.package]
version = "0.5.1"
version = "0.5.2"
edition = "2021"
license = "Apache-2.0"
repository = "https://github.com/basecompute/baseRT"
Expand Down
93 changes: 72 additions & 21 deletions base-convert/FORMAT.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,41 @@ The header schema is arch-open. Supported categories at v1:
weights go under the `mmproj` sub-bundle. Tower config is
`mmproj.config`. Projection head weights live in the main bundle under
canonical names (`multi_modal_projector.*`).
- **Speculator** (speculative decoding drafters): a drafter that
conditions on the model's hidden states goes under the `speculator`
sub-bundle — the checkpoint's own Multi-Token-Prediction head
(Qwen3.5/3.6/3.8 `mtp.*`, arch `<arch>-mtp`), or a converted EAGLE /
DFlash drafter. Same blob, own tensor list, so a runtime that does not
speculate skips it. An MTP head's decoder layer is canonicalized exactly
like a main layer and prefixed (`mtp.layers.0.self_attn.q_proj.weight`,
`mtp.layers.0.ffn_gate_exps.weight`), its own tensors keep their names
(`mtp.fc.weight`, `mtp.pre_fc_norm_embedding.weight`,
`mtp.pre_fc_norm_hidden.weight`, `mtp.norm.weight`); norm shifts are
baked like the main layers'. Speculator tensors stay f16 regardless of the
quant target. `speculator.config` is open-namespace: `kind` ("mtp"),
`num_layers`, `moe`, `shared_embeddings`, `shared_lm_head`, `fc_inputs`.
The header raises `HAS_SPECULATOR`.
- **Block-drafter sidecars** (DFlash / DSpark): a drafter that ships as
its own checkpoint converts to its own small bundle, arch `dflash` /
`dspark` (recognised by `architectures`, not `model_type`, which is the
qwen3 backbone's). Its tensors are main tensors of the sidecar: the
qwen3 decoder under `layers.N.*` (canonicalized like a target's layers),
`fc.{i}.weight` (the fused `fc` split by input column, one `[dim, dim]`
block per `target_layer_ids` entry), `hidden_norm.weight`,
`final_norm.weight` (from `norm.weight`), and — DSpark — its own
`embed_tokens.weight` / `lm_head.weight`, `markov.w1/w2.weight`,
`confidence.proj.*`; a DFlash sidecar has no embedding or head and the
runtime resolves both from the target's bundle. Every tensor is f16
whatever the quant target. The header config carries the drafter's own
geometry in the usual HF keys plus `speculator_kind`, `block_size`,
`mask_token_id`, `logits_start`, `target_layer_ids`, `fc_scale` (1/256,
folded into every `fc.{i}` — hidden_norm is scale-invariant and the raw
fc output overflows f16 on the target's massive activations),
`num_target_layers`
and, when present, `markov_rank`, `confidence_head`, DFlash 2's
`conv_kernel_size` / `conv_group_size` / `selector_rank` /
`selector_top_k`. A sliding-window schedule is recorded as the runtime's
`sliding_window` + `sliding_window_pattern` period.

Adding a new architecture = adding a `base-arch/<name>.rs` mapping from
source tensor names to canonical names. **No `format_version` bump**
Expand Down Expand Up @@ -216,7 +251,7 @@ answer structural questions with a single bit-test.
| 2 | HAS_SSM |
| 3 | HAS_HYBRID |
| 4 | HAS_LORA |
| 5 | HAS_SPECULATOR |
| 5 | HAS_SPECULATOR | (the bundle carries a `speculator` sub-bundle)
| 6 | HAS_COMPUTE_GRAPH |
| 7 | HAS_KV_WARMUP |
| 8 | HAS_TRACE_REF |
Expand Down Expand Up @@ -249,6 +284,19 @@ Supported kinds:
- `ssm`, `ssm_moe` — SSM (Mamba, RWKV) with optional MoE FFN
- `attention_moe`, `dense_moe` — attention + MoE FFN
- `dense_mlp` — classic transformer block
- `moe_ffn` — FFN-only MoE block with no attention/SSM mixer
(Nemotron-H MoE interleaves pure-Mamba, pure-attention and
pure-MoE-FFN blocks; each block has exactly one of the three)

Hybrid checkpoints additionally mirror the schedule as a flat
`config.layer_types` string array (one entry per layer). Vocabularies in
use: `"linear_attention" | "full_attention"` (Qwen3.5/3.6 Gated
DeltaNet) and `"mamba" | "attention" | "moe" | "mlp"` (Nemotron-H).
Nemotron-H configs also carry the Mamba-2 mixer geometry
(`ssm_state_size`, `ssm_conv_kernel`, `ssm_num_groups`,
`ssm_inner_size`, `ssm_num_heads`) and DeepSeek-style router fields
(`expert_gating`: 0 = softmax / 1 = sigmoid, `expert_weights_scale`,
plus the per-layer `mlp.router.e_score_correction_bias` tensor).

Per-layer precision overrides (`force_fp32_attn`, `force_fp32_ssm`,
`no_quantize`) let the converter mark specific layers as untouchable
Expand All @@ -261,8 +309,8 @@ weights.
A LoRA adapter is shipped as a stand-alone `.base` file, NOT as an
extension slot on a base bundle. The runtime opens it with the same
`WeightProvider` it uses for the base model, then installs it via
`baseRT_lora_load(model, path)`. `tools/lora_convert.py` produces the
file from a PEFT (HuggingFace) source.
`baseRT_lora_load(model, path)`. `basert convert-lora <peft-dir> --base
<model.base>` produces the file from a PEFT (HuggingFace) source.

### Header shape

Expand Down Expand Up @@ -354,17 +402,16 @@ ranks disagree.

### Per-arch fusion topology

`tools/lora_convert.py` derives the fusion choice from the PEFT
`adapter_config.json`'s `base_model_name_or_path`:

| Base model family | QKV | gate+up |
|----------------------------------------------|--------------|--------------|
| Llama / Gemma 3 / Qwen3 / Mistral / BERT | fused (3·r) | fused (2·r) |
| Gemma 4 | separate | separate |

Adding a new arch is a one-line entry in `ARCH_TOPOLOGY`. The
runtime side needs no changes — `dispatch_gemm`'s tensor_name +
shape together disambiguate.
Quantized decode and prefill run QKV and gate+up as fused GEMMs (named
for the q and gate projections); mixed-dtype configs run one GEMM per
projection. The two never run together, so `basert convert-lora` emits
both: stacked block-diagonal pairs under the fused names and
per-projection pairs under the split names. The per-projection widths
come from `--base`, which also checks that the adapter and the model
agree on the hidden size. It covers the Llama-shaped families (llama,
mistral, phi3) and refuses other architectures. The runtime side needs
no changes — `dispatch_gemm`'s tensor_name + shape together
disambiguate.

## Extension slots

Expand All @@ -389,9 +436,9 @@ Known kinds (all optional):
- `0x0003 KvWarmup` — pre-filled KV cache tokens for common system
prompts
- `0x0004 TraceReference` — 16-token fixed input + expected fp32
logits. `baserT --validate` runs the forward pass at load and fails
loud on RMS-error regression — catches silent quantization bugs per
file, forever
logits, for a validating loader to compare a forward pass against at
load. Reserved: the converter writes none and the engine does not read
it yet
- `0x0005 RopeTables` — precomputed cos/sin. Runtime skips RoPE compute
- `0x0006 CalibrationData` — per-tensor AWQ activation stats, JSON
- `0x00FF Custom` — vendor-defined
Expand All @@ -404,8 +451,7 @@ doesn't know how to process are a hard failure.
## Integrity

- **Per-tensor xxh64** in each `TensorEntry.checksum_xxh64`. Computed at
write, lazy-verified at read. Strict mode (`baserT --validate`)
eagerly verifies all tensors before dispatch.
write; `basert inspect --verify-checksums` checks every tensor.
- **Per-slot xxh64** in each extension slot header. Verified when the
slot is parsed.
- **ed25519 signature** over canonical-JSON header + sha256 of weights
Expand All @@ -422,7 +468,7 @@ ed25519 catches that because the attacker lacks the signing key.
{
"schema": 1,
"arch": "qwen3", // model arch; drives tensor-name convention
"quant_scheme": "base_q4", // one of: base_q4, base_q8, bf16, mxfp4, nvfp4
"quant_scheme": "base_q4", // base_q2 … base_q8 | bf16 | f16 | mxfp4 | nvfp4 | passthrough_gguf
"min_hw": "apple_m1", // minimum hardware generation
"created": "2026-04-24T12:00:00Z",
"baserT_version": "0.9.0",
Expand Down Expand Up @@ -452,7 +498,7 @@ ed25519 catches that because the attacker lacks the signing key.
"tensors": [
{
"name": "model.layers.0.self_attn.qkv_proj.weight", // q/k/v fused at convert-time
"dtype": "base_q4", // base_q4 | base_q8 | bf16 | f16 | f32 | mxfp4 | nvfp4
"dtype": "base_q4", // base_q2 … base_q8 | bf16 | f16 | f32 | mxfp4 | nvfp4
"shape": [2560, 2048], // [fused_out, in]
"offset": 0, // byte offset within weights_blob
"length": 655360, // byte length of packed data
Expand All @@ -472,6 +518,11 @@ ed25519 catches that because the attacker lacks the signing key.
"arch": "gemma4_vision",
"tensors": [ ... ] // same shape as top-level tensors
},
"speculator": { // optional: speculative-decoding drafter
"arch": "qwen35-mtp",
"config": { "kind": "mtp", "num_layers": 1, "moe": false, ... },
"tensors": [ ... ] // same shape as top-level tensors; f16
},
"calibration": { // optional: AWQ audit trail
"mode": "full", // full | lite | none
"calib_tokens": 512,
Expand Down
17 changes: 9 additions & 8 deletions base-convert/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ See [FORMAT.md](FORMAT.md) for the on-disk layout.
| Crate | Role |
|-----------------|--------------------------------------------------------|
| `base-format` | `.base` file reader/writer, header schema |
| `base-quant` | Packing routines: `base_q4`, `base_q8`, `mxfp4`, `nvfp4` |
| `base-quant` | Packing routines: `base_q2` … `base_q8`, `mxfp4`, `nvfp4`; quant profiles |
| `base-awq` | Full AWQ calibration (clip + per-layer alpha search) |
| `base-readers` | Input readers: GGUF, MLX-safetensors, HF-safetensors |
| `base-arch` | Per-architecture tensor-name normalization |
Expand All @@ -28,7 +28,8 @@ cargo build --release -p base-convert # produces the `basert` binary
## Model hub: `pull` / `list`

`basert pull` fetches a model into a per-user cache
(`$BASERT_MODELS_DIR`, default `~/.cache/baseRT/models`) laid out as
(`$BASERT_MODELS_DIR`, default `~/Library/Caches/baseRT/models` on macOS and
`~/.cache/baseRT/models` on Linux) laid out as
`<org>/<model>/<variant>/model.base`. The runtime reads the same
directory.

Expand Down Expand Up @@ -76,7 +77,7 @@ through pre-converted catalog artifacts.
Run a model with the BaseRT runtime:

```
basert serve <model> [--model <model2> …] # OpenAI-compatible server (--model repeats for multi-model)
basert serve <model> [--model <model2> …] # HTTP server: runs Superfluid, installed on first use
basert chat <model> # interactive chat
basert complete <model> --prompt <text> # one-shot completion
basert bench <model> # throughput benchmark
Expand All @@ -85,11 +86,11 @@ basert bench <model> # throughput benchmark
## Converter subcommands

```
basert convert --source <path> --target base-q4 --output <path>
basert inspect <path> # dump header + tensor inventory
basert keygen <key-prefix> # ed25519 keypair (writes .key, .pub)
basert sign <bundle> <secret-key> # signs an unsigned .base in-place
basert verify <bundle> <public-key> # exits non-zero on tampered file
basert convert <path> --target base-q4 -o <out.base>
basert inspect <path> [--verify-checksums] # dump header + tensor inventory
basert keygen --out <dir> [--name <name>] # ed25519 keypair (<name>.secret, <name>.pub)
basert sign <bundle> --key <secret> -o <out> # writes a signed copy
basert verify <bundle> --pubkey <pub> # exits non-zero on a tampered or wrongly signed file; 0 on an unsigned one
```

Probe tooling for HF checkpoints (per-tensor quant search; everything is
Expand Down
5 changes: 3 additions & 2 deletions base-convert/crates/base-awq/src/wikitext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
//! On-disk: a plain UTF-8 text file with one wikitext line per text
//! line (matches the standard distribution at
//! `wikitext-103-raw/wiki.train.raw` from the HF Datasets mirror).
//! No Python deps; the user downloads the file once and points the
//! converter at it via `--calib-file <path>`.
//! No Python deps; the user downloads the file once. The converter does
//! not read it: AWQ takes the activation sidecar (`--awq-profile`) that a
//! calibration run over this text records.
//!
//! This module deliberately doesn't tokenize — that's the runtime's
//! job at calibration time, since it must use the model's own
Expand Down
Loading
Loading