Skip to content

feat(models): add Databricks DBRX (dbrx) text model support - #1036

Merged
inureyes merged 1 commit into
mainfrom
feat/issue-835-dbrx-moe
Aug 5, 2026
Merged

inureyes merged 1 commit into
mainfrom
feat/issue-835-dbrx-moe

Conversation

@inureyes

@inureyes inureyes commented Aug 5, 2026

Copy link
Copy Markdown
Member

Closes #835

Ports the DBRX sparse-MoE decoder from mlx-lm. The transformer and top-k routing reuse existing shared infrastructure; what is new is the structural shape of the family.

Premise correction on the "defining quirk"

The issue calls the stacked expert tensors (experts.mlp.w1 / .v1 / .w2) "the defining quirk of the port" and asks for a sanitize that splits them per-expert. The mlx-community conversion already ships them split: keys are transformer.blocks.{i}.ffn.experts.{e}.{w1,v1,w2}.{weight,scales,biases}, because upstream's sanitize runs before quantization. That layout is exactly what the shared switch_layers per-expert loader already consumes, given the right leaf names.

This matters beyond tidiness: splitting a packed quantized tensor is unsound for gather_qmm (the DiffusionGemma #217 class), so implementing the issue as written would have introduced the bug it was trying to avoid.

The real deviations

  • Nested config geometry under attn_config / ffn_config, both of which published checkpoints fill with a full PretrainedConfig dump (top_k, temperature, id2label, ...). The structs declare only the meaningful fields and let serde drop the rest.
  • clip_qkv is Option<f32>, not a defaulted float. Upstream writes it as the JSON integer 8, and an absent value means no clipping; a defaulted 0.0 would clamp every activation to zero and yield a model that loads and emits noise.
  • Uneven QKV split at (d_model, d_model + head_dim * kv_n_heads) = (6144, 7168) for 48 query heads against 8 KV heads of width 128. An even three-way split gives correctly shaped tensors assembled from the wrong channels.
  • norm-attn-norm: norm_1 feeds attention, the residual is added, norm_2 of that residual feeds the FFN, and the FFN output is added back to the un-normalized residual. The tensor the FFN reads and the tensor it adds to are different.
  • LayerNorm without bias at MLX's default 1e-5 (DBRX configs carry no epsilon field), not RMSNorm.
  • Routing: upstream softmaxes over all experts, takes top-k, then divides by the L1 norm of the selected scores. Softmax is monotonic and that composition reduces exactly to a softmax over the top-k logits, which is the shorter route taken here.
  • eos_token_id is null in every published config and lives only in tokenizer_config.json, so the model falls back to <|endoftext|> = 100257.

Validation

Real checkpoint mlx-community/dbrx-instruct-4bit (132B total / 36B active, 70 GB on disk), greedy (temp=0, --no-chat-template) against the mlx-lm 0.31.3 reference:

Prompt Result
"The capital of France is" 24 tokens token-exact
counting one to twenty 36 tokens token-exact, including the free-form continuation "Now, without looking, write down the numbers in"
39-token transformer prompt diverges at an exact tie

At that divergence the reference's own top-two logits are equal to the bit:

1005   ' use'        361.75000
4048   ' learn'      361.75000
top1-top2 gap: 0.000000

DBRX applies no logit softcapping, so at magnitude ~361 bf16 resolution is about 2 units and exact ties are common. That is a tie-break, not a numerical disagreement.

  • 10 unit tests pass
  • cargo clippy --workspace --all-targets -- -D warnings clean
  • cargo fmt --all -- --check clean
  • mlxcel arch reports the family

Reproduction note (not a blocker for this PR)

The mlx-community checkpoint ships a tiktoken tokenizer (tiktoken.py) and no tokenizer.json, which mlxcel's loader cannot read (No tokenizer found ... tried tokenizer.json, tokenizer.model, *.tiktoken, tokenizer.jsonl). Validation used the tokenizer.json from Xenova/dbrx-instruct-tokenizer, first verified to encode the test prompts to ids identical to the reference. Teaching the loader to read tiktoken-style tokenizers is a separate concern from this port and worth its own issue.

Not wired for tensor parallel

The fused Wqkv packs query and KV heads into one tensor, so a generic row split lands inside the Q block rather than between whole heads, and clip_qkv would have to be applied to the rank-local slice before the split. The dispatch arm exists only to keep the table total.

Port the DBRX sparse-MoE decoder from mlx-lm. The transformer and top-k
routing reuse the existing shared infrastructure; what is new is the
structural shape of the family.

Config geometry is nested under `attn_config` / `ffn_config` rather than
flat Llama-style fields, and published checkpoints dump a full
`PretrainedConfig` into both blocks, so the config structs declare only the
fields that matter and let serde drop the generation-time keys sharing the
block. `clip_qkv` is an `Option<f32>` rather than a defaulted float on
purpose: upstream writes it as the JSON integer 8, and an absent value means
"no clipping", whereas a defaulted 0.0 would clamp every activation to zero
and produce a model that loads and emits noise.

Attention is one fused `Wqkv` clamped to [-clip_qkv, +clip_qkv] before an
uneven three-way split at (d_model, d_model + head_dim * kv_n_heads). On
dbrx-instruct that is 48 query heads against 8 KV heads of width 128, so the
offsets are (6144, 7168); an even three-way split would yield correctly
shaped tensors assembled from the wrong channels.

The block is "norm-attn-norm": norm_1 feeds attention, the residual is added,
and norm_2 of that residual feeds the FFN, whose output is added back to the
un-normalized residual. Normalization is LayerNorm without bias at MLX's
default 1e-5, since DBRX configs carry no epsilon field.

Routed experts are named w1 (gate), v1 (up) and w2 (down) under
`transformer.blocks.{i}.ffn.experts.{e}`, which is the shared switch_layers
per-expert layout with different leaf names. Upstream's sanitize splits a
stacked `experts.mlp.*` tensor, but mlx-community conversions run that split
before quantizing, so the loader consumes the already-split per-expert form
and never slices a packed quantized tensor, which would be unsound for
gather_qmm.

Upstream softmaxes over all experts, selects top-k, then divides by the L1
norm of the selected scores. Softmax is monotonic and that composition
reduces exactly to a softmax over the top-k logits, which is the shorter
route taken here.

`eos_token_id` is null in every published config and lives only in
tokenizer_config.json, so the model falls back to the `<|endoftext|>` id
100257. A maskless multi-token prefill routes through `causal_attention` to
satisfy the causal-prefill contract.

Not wired for tensor parallel: the fused Wqkv packs query and KV heads into
one tensor, so a generic row split lands inside the Q block rather than
between whole heads. The dispatch arm exists only to keep the table total.

Validated against mlx-community/dbrx-instruct-4bit (132B total, 36B active,
70 GB on disk), token-exact against the mlx-lm 0.31.3 greedy reference: 24
tokens on a short prompt and 36 tokens on a counting prompt whose free-form
continuation ("Now, without looking, write down the numbers in") matches
verbatim. On a 39-token prefill the two diverge at a position where the
reference's own top-two logits are exactly equal (' use' and ' learn' both
361.75, gap 0.000000); DBRX runs no logit softcapping, so at that magnitude
bf16 resolution is about 2 units and exact ties are common. That is a
tie-break, not a numerical disagreement.

Note for anyone reproducing: the mlx-community checkpoint ships a tiktoken
tokenizer (`tiktoken.py`) and no `tokenizer.json`, which mlxcel's loader
cannot read. Validation used the byte-identical `tokenizer.json` from
Xenova/dbrx-instruct-tokenizer, verified to encode the test prompts to the
same ids as the reference. Teaching the loader to read tiktoken-style
tokenizers is a separate concern from this port.

Tests cover the real config parse including the nested-block clutter, the
integer and null spellings of clip_qkv, the eos fallback, construction from
checkpoint key names, a missing expert being an error rather than a silent
short stack, forward shapes and cache advance, and the two behaviors no shape
assertion can catch: that the clamp changes the attention output and that
norm_2 gates the FFN input.

Refs #835
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata status:done Completed labels Aug 5, 2026
@inureyes
inureyes merged commit 1094dd7 into main Aug 5, 2026
4 checks passed
@inureyes
inureyes deleted the feat/issue-835-dbrx-moe branch August 5, 2026 05:28
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
)

Closes lablup#835

Ports the DBRX sparse-MoE decoder from [mlx-lm](https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/dbrx.py). The transformer and top-k routing reuse existing shared infrastructure; what is new is the structural shape of the family.

## Premise correction on the "defining quirk"

The issue calls the stacked expert tensors (`experts.mlp.w1` / `.v1` / `.w2`) "the defining quirk of the port" and asks for a `sanitize` that splits them per-expert. **The mlx-community conversion already ships them split**: keys are `transformer.blocks.{i}.ffn.experts.{e}.{w1,v1,w2}.{weight,scales,biases}`, because upstream's `sanitize` runs before quantization. That layout is exactly what the shared `switch_layers` per-expert loader already consumes, given the right leaf names.

This matters beyond tidiness: splitting a *packed quantized* tensor is unsound for `gather_qmm` (the DiffusionGemma lablup#217 class), so implementing the issue as written would have introduced the bug it was trying to avoid.

## The real deviations

- **Nested config geometry** under `attn_config` / `ffn_config`, both of which published checkpoints fill with a full `PretrainedConfig` dump (`top_k`, `temperature`, `id2label`, ...). The structs declare only the meaningful fields and let serde drop the rest.
- **`clip_qkv`** is `Option<f32>`, not a defaulted float. Upstream writes it as the JSON integer `8`, and an absent value means *no clipping*; a defaulted `0.0` would clamp every activation to zero and yield a model that loads and emits noise.
- **Uneven QKV split** at `(d_model, d_model + head_dim * kv_n_heads)` = `(6144, 7168)` for 48 query heads against 8 KV heads of width 128. An even three-way split gives correctly shaped tensors assembled from the wrong channels.
- **norm-attn-norm**: `norm_1` feeds attention, the residual is added, `norm_2` of that residual feeds the FFN, and the FFN output is added back to the **un-normalized** residual. The tensor the FFN reads and the tensor it adds to are different.
- **LayerNorm without bias** at MLX's default `1e-5` (DBRX configs carry no epsilon field), not RMSNorm.
- **Routing**: upstream softmaxes over all experts, takes top-k, then divides by the L1 norm of the selected scores. Softmax is monotonic and that composition reduces exactly to a softmax over the top-k logits, which is the shorter route taken here.
- **`eos_token_id` is null** in every published config and lives only in `tokenizer_config.json`, so the model falls back to `<|endoftext|>` = 100257.

## Validation

Real checkpoint `mlx-community/dbrx-instruct-4bit` (132B total / 36B active, 70 GB on disk), greedy (`temp=0`, `--no-chat-template`) against the mlx-lm 0.31.3 reference:

| Prompt | Result |
|---|---|
| "The capital of France is" | **24 tokens token-exact** |
| counting one to twenty | **36 tokens token-exact**, including the free-form continuation "Now, without looking, write down the numbers in" |
| 39-token transformer prompt | diverges at an **exact tie** |

At that divergence the reference's own top-two logits are equal to the bit:

```
1005   ' use'        361.75000
4048   ' learn'      361.75000
top1-top2 gap: 0.000000
```

DBRX applies no logit softcapping, so at magnitude ~361 bf16 resolution is about 2 units and exact ties are common. That is a tie-break, not a numerical disagreement.

- 10 unit tests pass
- `cargo clippy --workspace --all-targets -- -D warnings` clean
- `cargo fmt --all -- --check` clean
- `mlxcel arch` reports the family

### Reproduction note (not a blocker for this PR)

The mlx-community checkpoint ships a tiktoken tokenizer (`tiktoken.py`) and **no `tokenizer.json`**, which mlxcel's loader cannot read (`No tokenizer found ... tried tokenizer.json, tokenizer.model, *.tiktoken, tokenizer.jsonl`). Validation used the `tokenizer.json` from `Xenova/dbrx-instruct-tokenizer`, first verified to encode the test prompts to ids identical to the reference. Teaching the loader to read tiktoken-style tokenizers is a separate concern from this port and worth its own issue.

## Not wired for tensor parallel

The fused `Wqkv` packs query and KV heads into one tensor, so a generic row split lands inside the Q block rather than between whole heads, and `clip_qkv` would have to be applied to the rank-local slice before the split. The dispatch arm exists only to keep the table total.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:models Model architectures, weights, loading, metadata priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(models): add Databricks DBRX (dbrx) text model support

1 participant