Repository navigation
feat(models): add GPT-BigCode (gpt_bigcode) text model support - #926
Conversation
Adds GPT-BigCode, the architecture behind the BigCode StarCoder and SantaCoder code models, as a fully integrated text model: config parse, loader, decoder graph, detection, registration, `LoadedModel` dispatch, docs and unit tests. It is a GPT-2 derivative, so it builds on the block skeleton landed in #924 rather than restating it. Multi-Query Attention is the defining feature. With `multi_query: true` exactly one KV head is shared by every query head, so the fused `c_attn` projection produces `n_embd + 2 * kv_dim` features rather than `3 * n_embd` and is split at `[n_embd, n_embd + kv_dim]`, which is not an even three-way split. On `bigcode/gpt_bigcode-santacoder` that is 2048 + 2 * 128 = 2304 for 16 query heads of width 128 over a single KV head. This maps onto the existing GQA attention path with `n_kv_heads = 1`; MLX broadcasts the shared KV head across the query heads exactly as it does for the GQA families, so no new attention code is involved. `multi_query: false` degenerates to plain multi-head attention and is covered too. The issue body's claim that `c_attn` / `c_proj` are stored in the Conv1D layout like GPT-2 is wrong, and following it would have silently corrupted every projection. HuggingFace `GPTBigCode` builds its projections with `nn.Linear`, not the `Conv1D` that GPT-2 uses, so the weights are already `[out, in]`, which is the layout `mlxcel_core::layers::Linear` wants. Verified against the checkpoint: `transformer.h.0.attn.c_attn.weight` is `[2304, 2048]` and `mlp.c_fc.weight` is `[8192, 2048]`, both `[out, in]`, where the GPT-2 equivalent is `[768, 2304]` = `[in, out]`. Upstream `gpt_bigcode.py` correspondingly has no `sanitize` method at all. There is therefore no transpose here, and `load_linear` rejects a weight that arrives in the transposed orientation by name, with an error explaining why GPT-BigCode is not Conv1D, so the claim cannot be reintroduced silently later. Two further deltas versus GPT-2: the MLP width comes from `n_inner` (8192 on santacoder) with `4 * n_embd` as the documented fallback for an absent or null field, and there is no `h.N.attn.bias` causal-mask buffer to strip because HuggingFace registers this family's mask with `persistent=False`. The santacoder export carries 292 tensors, none matching that shape, so the GPT-2 strip pass is deliberately not copied. The key prefix is `transformer.` only: both HuggingFace and upstream mlx-lm nest the decoder under a `transformer` submodule and upstream ships no `sanitize` that could rename it, so GPT-2's multi-prefix probe is not copied either. The untrusted-config hardening that #924's security pass arrived at is built in from the start rather than retrofitted. `ModelArgs::validate` rejects `n_head == 0`, an indivisible head split, and out-of-range `n_embd` / `n_layer` / `n_positions` / `vocab_size` / `n_inner` at load, before `n_layer` sizes the `Vec::with_capacity` in `from_weights` and before any derived `as i32` cast can truncate. Every gather is bounded by the real tensor shape rather than a config field: both the `wpe` and the `wte` table are checked against `n_positions` and `vocab_size` at load, because MLX wraps a negative gather index but does not range-check a positive one, so a config that overstates a table turns an ordinary prompt into an out-of-bounds read whose result reaches the logits. Every projection, bias and norm is checked against the shape the config implies in every layer, not just layer 0, since an MLX C++ exception crossing the cxx bridge is an uncatchable `std::terminate` rather than a load error. There is no unbounded probe loop over `0..n_layer` on the load path. `src/models/gpt2.rs` gains three shared helpers instead of having them duplicated: `dim_eq`, `layer_norm_from_weights` (now taking the model width and epsilon directly, and validating the norm shape), and `validate_position_table` generalized to `validate_embedding_table` so it covers the token table as well as the position table. All three carry the `// Used by:` comment the project convention asks for. GPT-2 behavior is unchanged apart from the added norm-shape rejection. Validated with `cargo check --release --lib --tests`, `cargo clippy --release --lib --tests` (no new findings), `cargo fmt --all -- --check`, and the unit suites for `models::gpt_bigcode` (20 tests), `models::gpt2` (25), `detection_tests` (23) and `models::metadata_tests` (4). Real-checkpoint generation against `bigcode/gpt_bigcode-santacoder` is pending. Closes #834
|
Real-checkpoint validation on Apple M1 Ultra (Metal + Accelerate, release build). GPT-BigCode is token-exact against the mlx-lm reference.
No GPT-2 regression from the shared-helper refactor. This PR lifts On the GELU question. The implementation matches upstream mlx-lm, which applies the erf-based |
Implementation Review SummaryIntentAdd GPT-BigCode ( Findings AddressedNone. No CRITICAL or HIGH finding was identified, so no code was changed on this branch. Verified Rather Than Accepted
Remaining Items
Suggestions Reviewed and Declined
Verification
|
`load_linear` returned early for any projection carrying a `.scales` tensor, so a packed weight reached the graph with neither its output width nor its bias shape checked. That carve-out is wrong for this family specifically, because `Attention::forward` slices the fused `c_attn` output at offsets derived from `config.json` (`[n_embd, n_embd + kv_dim]`) rather than from the tensor. A packed `c_attn` wider than the config claims leaves all three slices in bounds, so Q is correct while K and V are read from arbitrary interior channels: the model loads, decodes and emits fluent-looking output from a projection nothing validated. The reachable case is a quantized conversion whose config omits `multi_query` (it defaults to true, giving `n_embd + 2 * head_dim`) while the packed weight is the `3 * n_embd` multi-head width. A packed weight narrower than the config claims takes the other branch: MLX's `slice` clamps the stop index instead of erroring, and the following `reshape` then throws an `std::invalid_argument` that crosses the cxx bridge as an uncatchable `std::terminate`, so the process aborts with no diagnostic instead of returning a load error naming the tensor. Affine and block-float packing both compress the input axis only, so a quantized weight is still `[out_features, packed_in]`. The input width stays unchecked and is left to `UnifiedLinear` to reconcile, but the row count is untouched by packing and is now checked on both paths, as is the 1-D `.bias`. No legitimate export is rejected: `mx.quantize` on an `[out, in]` weight always yields `[out, in * bits / 32]`. Validated with `cargo fmt --all -- --check`, `cargo clippy --release --lib --tests --features metal,accelerate` (no new findings), and `cargo test --release --lib --features metal,accelerate` for `models::gpt_bigcode` (20 passed), `models::gpt2` (25 passed) and `detection_tests` (23 passed). Refs #834
Security and performance reviewScope: changed files, with the config surface and the MQA arithmetic traced end to end. No CRITICAL or HIGH findings. One MEDIUM fixed in 165f819, three reported below. Verified clean
MEDIUM (fixed in 165f819)A quantized projection reached the graph with its output width unchecked. Failure scenario: a 4-bit conversion whose Affine and block-float packing both compress the input axis only, so a quantized weight is still MEDIUM (reported, not fixed: the fix belongs in shared estimation code)GPT-BigCode is invisible to the architecture-aware KV estimator, so the server's default Failure scenario: serving a StarCoder-class checkpoint with the default flags, a burst of long-context completion requests grows the paged pool with no admission or eviction ceiling until the OS reclaims the process, instead of being block-budgeted as it would be for a Llama or Qwen3 model. The pre-load The condition is inherited: GPT-2 (merged in #924) writes the same key names and is in the same state on A quantized embedding table's dequantized width is still unchecked. LOW
Verification
|
Two doc-comment inaccuracies surfaced while finalizing the GPT-BigCode port. `src/models/gpt2.rs` described `mlxcel_core::utils::gelu_approx` as the tanh approximation, contradicting the correct erf-based description this port's own `src/models/gpt_bigcode.rs` module docs already carry for the same shared helper; confirmed against the implementation in `src/lib/mlxcel-core/cpp/mlx_cxx_bridge.cpp`, which computes the erf form. GPT-2's checkpoint activation is named `gelu_new` (tanh, matching upstream mlx-lm's `nn.gelu_approx`), but this tree deliberately evaluates the erf form instead; patching the mlx-lm reference to tanh and regenerating produced the identical 60 greedy token ids, so the substitution is confirmed harmless here. `src/distributed/tensor_parallel/inference.rs` claimed the GPT-BigCode arch string is rejected by "the planner's supported-architecture validation" before any TP load is attempted. That refusal does not happen where the comment says: `generate_shard_plan` has no `gpt_bigcode` arm and falls into its `_ =>` fallback, still producing a generic transformer plan. The actual refusal is in `validate_supported_runtime`, whose `runtime_kind_for` match has no arm for `ModelType::GptBigCode`, returns `None`, and is turned into an unsupported-architecture error. The outcome (TP is refused) was already correct; only the described mechanism was wrong. Also updated the `docs/supported-models.md` GPT-BigCode entry, written before the quantized-projection security fix (previous commit), to describe the new load-time check: a packed `c_attn` now has its output row count validated against the config-derived width on the same path as an unquantized checkpoint. No Korean counterpart of this file exists in the tree, so no translation was added. Verified the security fix has a regression test that actually depends on it: reverting only the `src/models/gpt_bigcode.rs` half of that fix while keeping its paired test in `src/models/gpt_bigcode_tests.rs` makes `a_quantized_projection_skips_the_packed_input_width_but_not_the_output_width` the sole failure in the `models::gpt_bigcode` suite. Validated with `cargo fmt --all -- --check`, `cargo clippy --release --lib --tests --features metal,accelerate` (no new findings beyond the two pre-existing warnings in `src/multimodal/host_preprocessor*.rs`), and `cargo test --release --lib --features metal,accelerate` for `models::gpt_bigcode` (20 passed), `models::gpt2` (25 passed), `detection_tests` (23 passed), `models::metadata_tests` (4 passed), and `distributed::tensor_parallel` (338 passed, 4 ignored). Refs #834
## Summary Adds GPT-NeoX (`gpt_neox`), the EleutherAI decoder behind the Pythia suite and the NeoX-derived checkpoints, as a fully integrated text model: config parse, loader, decoder graph, detection, registration, `LoadedModel` dispatch, docs and unit tests. It shares `LayerNorm` with bias and a fused QKV projection with the GPT-2 lineage landed in #924 and #926, so the shared helpers there are reused rather than duplicated, but the three things that define the family are its own. ## The trap: interleaved per-head QKV `query_key_value.weight` is `[6144, 2048]` on `EleutherAI/pythia-1b`, plain `nn.Linear` orientation, no transpose. But the split is **not** a three-way split of the output axis. Upstream reshapes to `(..., num_heads, 3 * head_dim)` and splits *that*, so the projection output is head-major: `[q_i | k_i | v_i]` per head, each of the 8 heads contributing 768 contiguous channels for `head_dim` 256. A flat `split(qkv, 3, axis=-1)`, which is exactly what `src/models/gpt2.rs` and `src/models/gpt_bigcode.rs` do to their own fused projections, produces Q, K and V of byte-identical shape assembled from the wrong channels. Nothing throws, the cached KV shape is unchanged, the logits shape is unchanged, and the model generates fluent English out of a scrambled attention. No shape assertion anywhere can catch it. The split is therefore factored into `split_interleaved_qkv` so the layout can be pinned by channel value rather than only observed through a whole forward pass, and it is covered three ways: - `interleaved_qkv_split_pins_the_head_major_layout` feeds a 24-channel projection whose values are their own channel indices and asserts Q is `[0,1,2,3, 12,13,14,15]`, K is `[4,5,6,7, 16,17,18,19]`, V is `[8,9,10,11, 20,21,22,23]`. - `a_flat_three_way_split_would_take_different_channels` asserts the same tensors differ from the literal flat-split runs `0..7` / `8..15` / `16..23`. - `attention_forward_returns_the_interleaved_v_block` is an end-to-end pin that does not touch the helper: with a single token, attention softmaxes over exactly one key, so with a zeroed `query_key_value` weight, a counting bias and an identity `dense`, the block output *is* the V channels. It must be `[8,9,10,11, 20,21,22,23]`, and is asserted not to be the flat split's `[16..23]`. **Verified by mutation, not just by passing.** `split_interleaved_qkv` was temporarily replaced with the naive flat form and the suite re-run: exactly those three tests failed and all 26 others passed, including the full prefill-then-decode, both residual tests, and every layout and loading test. `attention_forward_returns_the_interleaved_v_block` reported `[16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0]`, the flat split's V, confirming the test observes the exact failure mode it was written for. The mutation was then reverted and the suite re-run green. ## What changed - `src/models/gpt_neox.rs` (new): `ModelArgs`, `GptNeoxLayout`, `strip_registered_buffers`, `load_linear`, `split_interleaved_qkv`, the decoder graph and the `LanguageModel` impl. - **Partial RoPE.** Only `int(head_dim * rotary_pct)` channels of each head rotate and the rest pass through untouched (64 of 256 for Pythia's `rotary_pct` 0.25), expressed with the `dims` argument of `fast_rope` with `traditional = false`, following the `partial_rotary_factor` precedent in `src/models/phi.rs`. `partial_rope_leaves_the_unrotated_channels_untouched` asserts the tail channels are bit-unchanged at a non-zero offset and that a partial rotation differs from rotating the whole head. - **Both residual layouts.** `use_parallel_residual: true` (every Pythia checkpoint) feeds attention and the MLP the *same* pre-norm input and sums both into the residual; `false` chains them so `post_attention_layernorm` reads the post-attention residual. Both produce identically shaped output from identical weights, so running the wrong one is a silent quality regression rather than a crash. The two tests recompute each form from the block's own sub-modules, which pins the wiring rather than the arithmetic, and a third asserts the two layouts do not produce the same logits. - **Three registered buffers dropped at load.** `attention.bias` (a `[1, 1, 2048, 2048]` causal mask whose name collides with the projection-bias namespace exactly as GPT-2's `h.N.attn.bias` does), `attention.masked_bias` and `attention.rotary_emb.inv_freq`. Removed in a single `retain` pass over the weight map, not a probe of `<prefix>.<i>.attention.bias` for every `i` in `0..num_hidden_layers`: `num_hidden_layers` is attacker-controlled and unchecked at that point on the `load()` path, and the probing form has no early exit. That is the same replacement the previous chain PR had to make after review. A test asserts the real `query_key_value.bias`, `dense.bias` and `input_layernorm.bias` all survive the pass. - **Two key layouts.** The raw HuggingFace export (`gpt_neox.layers.N`, top-level `embed_out`) and the layout upstream mlx-lm's `sanitize` produces (`model.h.N`, `model.embed_out`). The candidate list is fixed at two entries probed by the embedding key alone, with no shape-derived branch, because unlike GPT-2 both layouts store every projection in the same `nn.Linear` `[out, in]` orientation and there is nothing to transpose. `both_layouts_build_the_same_model` asserts they produce identical logits. Only the raw layout is checkpoint-validated; the second is derived directly from upstream's `sanitize`, which is the only thing that can produce an MLX conversion of this family. - **Untrusted-config hardening built in from the start**, following what the security passes on #924 and #926 arrived at rather than waiting to be told again. `ModelArgs::validate` rejects `num_attention_heads == 0` *before* any divisibility check (`0.is_multiple_of(0)` is true, so the divisibility check alone lets a zero-zero config reach `head_dim()`), an indivisible head split, and out-of-range `hidden_size` / `num_hidden_layers` / `max_position_embeddings` / `vocab_size` / `intermediate_size`, all before `num_hidden_layers` sizes the `Vec::with_capacity` in `from_weights` and before any derived `as i32` cast can truncate to a negative number. - **`rotary_pct` is the first float this lineage lets a config author control**, so it gets its own validation. `mlx::core::fast::rope` does check `dims`: at the pinned MLX commit `mlx/fast.cpp` throws on a non-positive `dims`, on an odd `dims`, and on a `dims` larger than the input's last axis. None of that is recoverable here, because `fast_rope` crosses the cxx bridge as `UniquePtr<MlxArray>` rather than a `Result`, so the C++ `std::invalid_argument` becomes an uncatchable `std::terminate` (SIGABRT), and it fires at the first forward pass rather than at load. Every value MLX would throw on is therefore rejected in Rust, at load: zero, negative, odd, greater-than-`head_dim`, NaN and both infinities (the `as i32` cast saturates, turning NaN into 0 and infinity into `i32::MAX`, but the non-finite case is rejected explicitly so the message names the real problem). `rotary_emb_base` is rejected when non-positive or non-finite, since RoPE takes its logarithm and a zero or negative base makes every rotated channel NaN without anything throwing. `config_validation_rejects_out_of_range_rope_parameters` covers all of these plus both accepted boundaries (the floor is two rotary dimensions, not one, since one is odd), and `every_accepted_rotary_pct_survives_a_real_rope_call` sweeps `rotary_pct` at both head widths and puts every accepted value through a real `fast_rope` call, so the guard drifting away from MLX's contract aborts the test binary rather than production. - **`layer_norm_eps` and the `quantization` block are validated at load too**, closing the same failure shape for two more config-controlled floats that `validate_rope` did not cover. `layer_norm_eps` is the third float this family lets a config author control; `fast::layer_norm` never looks at it (`x * rsqrt(mean(x^2) + eps)`), so a non-finite, negative or zero value makes every hidden state NaN without anything throwing, and the checkpoint loads cleanly and then generates uniform garbage instead of failing to load. `quantization.group_size` and `quantization.bits` reach `quantized_matmul` and `dequantize` unreconciled (`reconcile_quantization_layout` treats a non-positive pair as insufficient shape info and passes it through unchanged), and MLX's own `packed_in * 32 / bits` check divides by zero at `bits == 0` and collapses to zero above 32, throwing the same uncatchable `std::terminate` the `rotary_pct` guard exists to prevent; the bound is a range (`1..=32` for `bits`, positive for `group_size`) rather than an allowlist, since mlxcel deliberately re-derives an effective bit width from the tensor shapes when the declared one disagrees, and an allowlist would reject the mixed-precision exports that behavior serves. `config_validation_rejects_a_layer_norm_eps_that_would_nan_every_hidden_state` and `config_validation_rejects_a_quantization_block_that_would_abort_an_mlx_kernel` cover both guards, including the values that must stay accepted. - **Every gather and slice bound by the real tensor shape.** The `embed_in` table is checked against `vocab_size` at load, because MLX wraps a negative gather index but does not range-check a positive one, so a config that overstates the table turns an ordinary prompt into an out-of-bounds read whose result reaches the logits. Every projection, bias and norm is checked against the config-implied shape in *every* layer, not just layer 0. - **The quantized branch does not skip the shape contract.** Packing compresses the input axis only, so the row count is untouched and is checked on the quantized path exactly as on the float path, along with the 1-D bias; only the packed input width is left to `UnifiedLinear`. That check is load-bearing here specifically because `Attention::forward` reshapes the fused projection to `[batch, seq, num_heads, 3 * head_dim]` using config-derived widths, so a packed `query_key_value` of a different real width makes the reshape throw, and an MLX C++ exception crossing the cxx bridge is an uncatchable `std::terminate` rather than a load error. This is the same carve-out #926 had to close after review, closed here before it was opened. - **Which GELU, stated explicitly.** `mlxcel_core::utils::gelu_approx` is the erf-based *exact* GELU in this tree despite its name (the tanh form was deliberately replaced in `mlx_cxx_bridge.cpp` because `power(x, 3)` produced NaN for negative bf16 inputs). That matches Pythia's declared `hidden_act` of `"gelu"`, which HuggingFace resolves to the exact erf GELU, and differs from the tanh approximation upstream mlx-lm applies by under 5e-4 per element (MLX's own documented bound over `[-6, 6]`). The reasoning is written out at the call site. A config declaring a non-GELU `hidden_act` is reported via `eprintln!` rather than rejected, since the activation cannot corrupt memory and `tracing::warn!` is a no-op on the CLI path this is reachable from. - **No grouped-query attention.** Upstream's `num_key_value_heads` is vestigial: its `__post_init__` defaults it to `num_attention_heads` but `Attention` never reads it, and HuggingFace `GPTNeoXAttention` has no such concept. The fused projection is `3 * hidden_size` wide and reshaped to `(num_heads, 3 * head_dim)`, so Q, K and V always carry the same head count; the field is deliberately absent from this config struct and the forward test asserts the cached KV head count is `num_attention_heads`. - `src/models/gpt2.rs`: the shared `validate_embedding_table` gains a `width_field` parameter so its rejection message names the config field the reader will actually find in their `config.json` (`hidden_size` here, `n_embd` in the GPT-2 lineage). The three shared helpers' `// Used by:` comments are updated. GPT-2 and GPT-BigCode behavior is otherwise unchanged; `src/models/gpt_bigcode.rs` is touched only for the two updated call sites. - `src/models/mod.rs`: module declaration, `GptNeoxModel` re-export, and `ModelType::GptNeoX` in all four places that must agree (the enum, `ALL_MODEL_TYPES`, the `metadata()` display table, and the `all_variants!` exhaustiveness list). `src/models/detection.rs`: `"gpt_neox" => Ok(ModelType::GptNeoX)`, plus a detection test asserting it does not fall through to either GPT-2-lineage arm. `src/model_metadata.rs`: standard config-backed registration. `src/loaded_model.rs`: variant and `delegate_language_model!` arm. `src/distributed/tensor_parallel/inference.rs`: `"gpt_neox"` fallback architecture string, keeping the dispatch table total; TP is refused by `validate_supported_runtime`, whose `runtime_kind_for` match has no arm for this variant. Sharding would need its own rules regardless, since a row split at any offset a generic plan would pick cuts through the middle of a head's Q, K and V rather than between whole heads. - `src/models/gpt_neox_tests.rs` (32 tests) and `docs/supported-models.md`. - **Finalization pass.** Two `format!` error strings in `validate_norm_eps` and `validate_quantization` had literal multi-space gaps left over from wrapping the prose without converting it to the backslash-continued style the rest of the file uses; rewritten with no behavior change. The `docs/supported-models.md` entry now also names the `layer_norm_eps` and `quantization` rejections above. Both fix commits were verified by reverting each in isolation: without the odd-`dims` rejection, `config_validation_rejects_out_of_range_rope_parameters` fails cleanly and `every_accepted_rotary_pct_survives_a_real_rope_call` then feeds an odd `dims` to a real `fast_rope` call and aborts the whole test binary with SIGABRT (`[rope] dims must be even but got 1.`), rather than failing cleanly; without the `layer_norm_eps` / `quantization` guards, the two tests named above fail cleanly (no MLX call is reached, so no abort). All three pass again with the fixes restored. ## Test plan - [x] `cargo fmt --all -- --check` - [x] `cargo check --release --lib --tests --features metal,accelerate` - [x] `cargo clippy --release --lib --tests --features metal,accelerate` (no new findings; the two warnings in `src/multimodal/host_preprocessor*.rs` are pre-existing on `main` and untouched here) - [x] `cargo test --release --lib --features metal,accelerate models::gpt_neox` (32 passed) - [x] `cargo test --release --lib --features metal,accelerate models::gpt2` (25 passed, unchanged by the `validate_embedding_table` signature change) - [x] `cargo test --release --lib --features metal,accelerate models::gpt_bigcode` (20 passed, likewise) - [x] `cargo test --release --lib --features metal,accelerate detection_tests` (24 passed) - [x] `cargo test --release --lib --features metal,accelerate models::metadata_tests` (4 passed: the registration and `ALL_MODEL_TYPES` exhaustiveness gates) - [x] `cargo test --release --lib --features metal,accelerate distributed::tensor_parallel` (338 passed, 4 ignored) - [x] `python3 scripts/ci/check_cross_repo_refs.py` - [x] Mutation check on the interleaved split, described in full above: the naive flat form fails exactly the three value-level tests and passes the other 26. - Unit coverage beyond the split: the real pythia-1b config field set and the bare-config defaults; scalar, list and empty-list token-id fields with the bos fallback; partial-RoPE dimensioning including `int()` truncation and the full-rotation case; `intermediate_size` versus the `4 * hidden_size` fallback including explicit `null`; the non-GELU activation predicate; eight hostile integer scalars plus `max_position_embeddings` and the `4 * hidden_size` overflow boundary; nine out-of-range RoPE parameters plus both accepted boundaries; detection of both key layouts, their rejection path, and their producing identical logits; the registered-buffer strip including that the real biases survive and that a second pass removes nothing; the model building identically with and without the buffers present; every projection loading with its stored `[out, in]` shape unchanged; rejection of a transposed weight, a rank-3 weight, a mis-sized bias, a missing projection, a later layer that disagrees with the config, an `embed_in` table shorter than `vocab_size` claims, a table or either norm of the wrong width, and an untied config with no `embed_out`; a quantized projection that skips only the packed input-width check while its output row count (wider and narrower) and its bias are still rejected by name; both residual layouts recomputed from their own sub-modules and asserted non-interchangeable; and prefill-then-decode under both residual settings asserting the logits shape, the advancing cache offset and the cached KV head count. - Not run here: the release build and the token-exact real-checkpoint validation against `models/pythia-1b`, which the maintainer is running separately. Closes #836
…p#926) ## Summary Adds GPT-BigCode (`gpt_bigcode`), the architecture behind the BigCode StarCoder and SantaCoder code models, as a fully integrated text model: config parse, loader, decoder graph, detection, registration, `LoadedModel` dispatch, docs and unit tests. It is a GPT-2 derivative, so it builds on the block skeleton landed in lablup#924 rather than restating it. ## Correction to the issue body The issue says `c_attn` / `c_proj` are "stored in the Conv1D layout like GPT-2". **That is wrong, and following it would have silently corrupted every projection.** HuggingFace `GPTBigCode` builds its projections with `nn.Linear`, not the `Conv1D` that GPT-2 uses, so the weights are already `[out, in]`, which is the layout `mlxcel_core::layers::Linear` wants. Shapes read directly from the `bigcode/gpt_bigcode-santacoder` SafeTensors header: ``` transformer.h.0.attn.c_attn.weight F16 [2304, 2048] = [out, in] transformer.h.0.attn.c_proj.weight F16 [2048, 2048] transformer.h.0.mlp.c_fc.weight F16 [8192, 2048] = [out, in] transformer.h.0.mlp.c_proj.weight F16 [2048, 8192] ``` Compare GPT-2, whose `c_attn.weight` is `[768, 2304]` = `[in, out]` and does need the transpose. Upstream `gpt_bigcode.py` correspondingly has no `sanitize` method at all. There is therefore no transpose in this port, and `load_linear` rejects a weight that arrives in the transposed orientation by name with an error that explains why GPT-BigCode is not Conv1D, so the claim cannot be reintroduced silently later. `a_conv1d_oriented_weight_is_rejected_and_named` pins that behavior. ## What changed - `src/models/gpt_bigcode.rs` (new): `ModelArgs` for the GPT-2-style config field names plus `multi_query` and `n_inner`, the decoder graph, `detect_prefix`, `load_linear`, and the `LanguageModel` impl. - **Multi-Query Attention**, the defining feature. With `multi_query: true` exactly one KV head is shared by every query head, so the fused `c_attn` projection produces `n_embd + 2 * kv_dim` features rather than `3 * n_embd` and is split at `[n_embd, n_embd + kv_dim]`, which is *not* an even three-way split. On santacoder that is 2048 + 2 * 128 = 2304 for 16 query heads of width 128 over a single KV head. This maps onto the existing GQA attention path with `n_kv_heads = 1`; MLX broadcasts the shared KV head across the query heads exactly as it does for the GQA families, so no new attention code is involved. `ModelArgs::qkv_split_offsets` exposes the split as a pure function so the uneven offsets are unit-tested without a checkpoint, and the tiny forward tests assert the cached KV head count directly (1 under MQA, `n_head` when `multi_query` is false). - **MLP width from `n_inner`** (8192 on santacoder), not a hardcoded `4 * n_embd`. An absent or `null` `n_inner` falls back to `4 * n_embd`, matching HuggingFace. - **No causal-mask buffer to strip.** HuggingFace registers GPT-BigCode's mask with `persistent=False`, so unlike GPT-2 no `h.N.attn.bias` tensor reaches the checkpoint; the santacoder export carries 292 tensors, none matching that shape. GPT-2's `strip_causal_mask_buffers` pass is deliberately not copied. - **Single key prefix.** Both HuggingFace and upstream mlx-lm nest the decoder under a `transformer` submodule, and upstream ships no `sanitize` that could rename it, so GPT-2's multi-prefix probe is not copied either; `detect_prefix` accepts `transformer.` and rejects anything else with a message naming the key it looked for. - **Untrusted-config hardening built in from the start**, following what lablup#924's security pass arrived at. `ModelArgs::validate` rejects `n_head == 0`, an indivisible head split, and out-of-range `n_embd` / `n_layer` / `n_positions` / `vocab_size` / `n_inner` at load, before `n_layer` sizes the `Vec::with_capacity` in `from_weights` and before any derived `as i32` cast can truncate. Every gather is bounded by the real tensor shape rather than a config field: both the `wpe` and the `wte` table are checked against `n_positions` and `vocab_size` at load, because MLX wraps a negative gather index but does not range-check a positive one, so a config that overstates a table turns an ordinary prompt into an out-of-bounds read whose result reaches the logits. Every projection, bias and norm is checked against the shape the config implies in *every* layer, not just layer 0, since an MLX C++ exception crossing the cxx bridge is an uncatchable `std::terminate` rather than a load error. There is no unbounded probe loop over `0..n_layer` on the load path. - **Output head.** Every published checkpoint ties the head to `wte` and ships no `lm_head` tensor, which is why `tie_word_embeddings` defaults to true. An untied config must actually carry the tensor; silently falling back to the tied path would produce logits from the wrong matrix. GPT-BigCode has no family-wide `<|endoftext|>` id (santacoder uses 49152, StarCoder uses 0), so `eos_token_ids` falls back from `eos_token_id` to `bos_token_id` and then to empty rather than guessing an id that could truncate at an ordinary token. - `src/models/gpt2.rs`: three helpers are made shared rather than duplicated, each carrying the `// Used by:` comment the project convention asks for. `dim_eq` and `layer_norm_from_weights` become `pub(crate)`, with the latter now taking the model width and epsilon directly and validating the norm shape; `validate_position_table` is generalized to `validate_embedding_table` so it covers the token table as well as the position table. GPT-2 behavior is unchanged apart from the added norm-shape rejection. - `src/models/mod.rs`: module declaration, `GptBigCodeModel` re-export, and `ModelType::GptBigCode` in all four places that must agree (the enum, `ALL_MODEL_TYPES`, the `metadata()` display table, and the `all_variants!` exhaustiveness list). - `src/models/detection.rs`: `"gpt_bigcode" => Ok(ModelType::GptBigCode)`, plus a detection test asserting it does not fall through to the `gpt2` arm. - `src/model_metadata.rs`: standard config-backed registration, so both the directory route and the owned-weights route go through the shared registry. `src/loaded_model.rs`: variant and `delegate_language_model!` arm. `src/distributed/tensor_parallel/inference.rs`: `"gpt_bigcode"` fallback architecture string; the fused `c_attn` key names have no shard rules and the multi-query KV block cannot be split across ranks anyway. `generate_shard_plan` has no `gpt_bigcode` arm and still produces a generic transformer plan through its fallback, but `validate_supported_runtime`'s `runtime_kind_for` match has no arm for `ModelType::GptBigCode` either, so TP is refused with an unsupported-architecture error before any load is attempted; the entry here exists to keep the dispatch table total. - `src/models/gpt_bigcode_tests.rs` (new, 20 tests) and `docs/supported-models.md`. ## Follow-up fix: quantized projection output width (`165f8199c`) `load_linear` returned early for any projection carrying a `.scales` key, so a packed weight reached the graph with neither its output width nor its bias shape checked. That carve-out is wrong for this family specifically, because `Attention::forward` slices the fused `c_attn` output at offsets derived from `config.json` (`[n_embd, n_embd + kv_dim]`), not from the tensor itself. A packed `c_attn` wider than the config claims leaves every slice in bounds, so the model loads and decodes fluent-looking output while K and V are silently read from arbitrary interior channels; the reachable case is a quantized conversion whose `config.json` omits `multi_query` (which then defaults to `true`) against a weight packed for full multi-head attention. A packed weight narrower than the config claims takes the other branch instead, where MLX's `slice` clamps the stop index and the following `reshape` then throws, crossing the cxx bridge as an uncatchable `std::terminate`. Quantization packs the input axis only, so the row count is untouched by packing and is now checked on the quantized path the same way it already was on the float path, along with the 1-D bias; the packed input width stays unchecked, since no float layout applies to it and `UnifiedLinear` reconciles that half of the contract itself. `a_quantized_projection_skips_the_packed_input_width_but_not_the_output_width` (renamed and extended from the earlier, now-inaccurate `load_linear_delegates_a_quantized_projection_unchecked`) covers a wider packed weight, a narrower one, and a mis-sized packed bias. ## Finalization polish Corrected two doc comments this chain had left inconsistent: `src/models/gpt2.rs` described the shared `mlxcel_core::utils::gelu_approx` helper as the tanh approximation, which contradicts both the C++ implementation in `mlx_cxx_bridge.cpp` (erf-based) and this port's own, correct description of the same helper in `src/models/gpt_bigcode.rs`; and the `src/distributed/tensor_parallel/inference.rs` comment for `ModelType::GptBigCode` named the wrong mechanism for the TP refusal (corrected wording is in the `What changed` bullet above). Also extended the `docs/supported-models.md` GPT-BigCode entry, written before `165f8199c` landed, to describe the quantized output-width check that commit added. ## Test plan - [x] `cargo fmt --all -- --check` - [x] `cargo check --release --lib --tests --features metal,accelerate` - [x] `cargo clippy --release --lib --tests --features metal,accelerate` (no new findings; the two warnings in `src/multimodal/host_preprocessor*.rs` are pre-existing on `main` and untouched here) - [x] `cargo test --release --lib --features metal,accelerate models::gpt_bigcode` (20 passed) - [x] `cargo test --release --lib --features metal,accelerate models::gpt2` (25 passed, unchanged by the shared-helper refactor) - [x] `cargo test --release --lib --features metal,accelerate detection_tests` (23 passed) - [x] `cargo test --release --lib --features metal,accelerate models::metadata_tests` (4 passed: the registration and `ALL_MODEL_TYPES` exhaustiveness gates) - [x] `cargo test --release --lib --features metal,accelerate distributed::tensor_parallel` (338 passed, 4 ignored; unaffected by the comment-only inference.rs change) - [x] `python3 scripts/ci/check_cross_repo_refs.py` - [x] Reverted only the `src/models/gpt_bigcode.rs` half of `165f8199c` while keeping its paired test, confirming `a_quantized_projection_skips_the_packed_input_width_but_not_the_output_width` is the sole failure in the `models::gpt_bigcode` suite, then restored the fix. - Unit coverage: the real santacoder config field set and the bare-config defaults; scalar, list and empty-list token-id fields with the bos fallback; config-magnitude validation against nine hostile scalar cases; the MQA head count, `kv_dim`, `c_attn` output width and the uneven split offsets, asserted to differ from both `3 * n_embd` and the even thirds; the `multi_query: false` degeneration; `n_inner` versus the `4 * n_embd` fallback including explicit `null`; prefix detection and its rejection path; every projection loading with the stored `[out, in]` shape unchanged; rejection of a Conv1D-oriented weight, a rank-3 weight, a mis-sized bias, a missing projection, a later layer that disagrees with the config, a `wpe` or `wte` table shorter than the config claims, a table or norm of the wrong width, and an untied config with no `lm_head`; a quantized projection that skips only the packed input-width check while its output row count (both wider and narrower than the config implies) and its bias are still validated and rejected by name; and two tiny end-to-end prefill-then-decode runs asserting the logits shape, the advancing cache offset and the cached KV head count under both `multi_query` settings. - Not run here: the release build and real-checkpoint generation against `models/gpt_bigcode-santacoder`, which the maintainer is running separately. Closes lablup#834
## Summary Adds GPT-NeoX (`gpt_neox`), the EleutherAI decoder behind the Pythia suite and the NeoX-derived checkpoints, as a fully integrated text model: config parse, loader, decoder graph, detection, registration, `LoadedModel` dispatch, docs and unit tests. It shares `LayerNorm` with bias and a fused QKV projection with the GPT-2 lineage landed in lablup#924 and lablup#926, so the shared helpers there are reused rather than duplicated, but the three things that define the family are its own. ## The trap: interleaved per-head QKV `query_key_value.weight` is `[6144, 2048]` on `EleutherAI/pythia-1b`, plain `nn.Linear` orientation, no transpose. But the split is **not** a three-way split of the output axis. Upstream reshapes to `(..., num_heads, 3 * head_dim)` and splits *that*, so the projection output is head-major: `[q_i | k_i | v_i]` per head, each of the 8 heads contributing 768 contiguous channels for `head_dim` 256. A flat `split(qkv, 3, axis=-1)`, which is exactly what `src/models/gpt2.rs` and `src/models/gpt_bigcode.rs` do to their own fused projections, produces Q, K and V of byte-identical shape assembled from the wrong channels. Nothing throws, the cached KV shape is unchanged, the logits shape is unchanged, and the model generates fluent English out of a scrambled attention. No shape assertion anywhere can catch it. The split is therefore factored into `split_interleaved_qkv` so the layout can be pinned by channel value rather than only observed through a whole forward pass, and it is covered three ways: - `interleaved_qkv_split_pins_the_head_major_layout` feeds a 24-channel projection whose values are their own channel indices and asserts Q is `[0,1,2,3, 12,13,14,15]`, K is `[4,5,6,7, 16,17,18,19]`, V is `[8,9,10,11, 20,21,22,23]`. - `a_flat_three_way_split_would_take_different_channels` asserts the same tensors differ from the literal flat-split runs `0..7` / `8..15` / `16..23`. - `attention_forward_returns_the_interleaved_v_block` is an end-to-end pin that does not touch the helper: with a single token, attention softmaxes over exactly one key, so with a zeroed `query_key_value` weight, a counting bias and an identity `dense`, the block output *is* the V channels. It must be `[8,9,10,11, 20,21,22,23]`, and is asserted not to be the flat split's `[16..23]`. **Verified by mutation, not just by passing.** `split_interleaved_qkv` was temporarily replaced with the naive flat form and the suite re-run: exactly those three tests failed and all 26 others passed, including the full prefill-then-decode, both residual tests, and every layout and loading test. `attention_forward_returns_the_interleaved_v_block` reported `[16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0]`, the flat split's V, confirming the test observes the exact failure mode it was written for. The mutation was then reverted and the suite re-run green. ## What changed - `src/models/gpt_neox.rs` (new): `ModelArgs`, `GptNeoxLayout`, `strip_registered_buffers`, `load_linear`, `split_interleaved_qkv`, the decoder graph and the `LanguageModel` impl. - **Partial RoPE.** Only `int(head_dim * rotary_pct)` channels of each head rotate and the rest pass through untouched (64 of 256 for Pythia's `rotary_pct` 0.25), expressed with the `dims` argument of `fast_rope` with `traditional = false`, following the `partial_rotary_factor` precedent in `src/models/phi.rs`. `partial_rope_leaves_the_unrotated_channels_untouched` asserts the tail channels are bit-unchanged at a non-zero offset and that a partial rotation differs from rotating the whole head. - **Both residual layouts.** `use_parallel_residual: true` (every Pythia checkpoint) feeds attention and the MLP the *same* pre-norm input and sums both into the residual; `false` chains them so `post_attention_layernorm` reads the post-attention residual. Both produce identically shaped output from identical weights, so running the wrong one is a silent quality regression rather than a crash. The two tests recompute each form from the block's own sub-modules, which pins the wiring rather than the arithmetic, and a third asserts the two layouts do not produce the same logits. - **Three registered buffers dropped at load.** `attention.bias` (a `[1, 1, 2048, 2048]` causal mask whose name collides with the projection-bias namespace exactly as GPT-2's `h.N.attn.bias` does), `attention.masked_bias` and `attention.rotary_emb.inv_freq`. Removed in a single `retain` pass over the weight map, not a probe of `<prefix>.<i>.attention.bias` for every `i` in `0..num_hidden_layers`: `num_hidden_layers` is attacker-controlled and unchecked at that point on the `load()` path, and the probing form has no early exit. That is the same replacement the previous chain PR had to make after review. A test asserts the real `query_key_value.bias`, `dense.bias` and `input_layernorm.bias` all survive the pass. - **Two key layouts.** The raw HuggingFace export (`gpt_neox.layers.N`, top-level `embed_out`) and the layout upstream mlx-lm's `sanitize` produces (`model.h.N`, `model.embed_out`). The candidate list is fixed at two entries probed by the embedding key alone, with no shape-derived branch, because unlike GPT-2 both layouts store every projection in the same `nn.Linear` `[out, in]` orientation and there is nothing to transpose. `both_layouts_build_the_same_model` asserts they produce identical logits. Only the raw layout is checkpoint-validated; the second is derived directly from upstream's `sanitize`, which is the only thing that can produce an MLX conversion of this family. - **Untrusted-config hardening built in from the start**, following what the security passes on lablup#924 and lablup#926 arrived at rather than waiting to be told again. `ModelArgs::validate` rejects `num_attention_heads == 0` *before* any divisibility check (`0.is_multiple_of(0)` is true, so the divisibility check alone lets a zero-zero config reach `head_dim()`), an indivisible head split, and out-of-range `hidden_size` / `num_hidden_layers` / `max_position_embeddings` / `vocab_size` / `intermediate_size`, all before `num_hidden_layers` sizes the `Vec::with_capacity` in `from_weights` and before any derived `as i32` cast can truncate to a negative number. - **`rotary_pct` is the first float this lineage lets a config author control**, so it gets its own validation. `mlx::core::fast::rope` does check `dims`: at the pinned MLX commit `mlx/fast.cpp` throws on a non-positive `dims`, on an odd `dims`, and on a `dims` larger than the input's last axis. None of that is recoverable here, because `fast_rope` crosses the cxx bridge as `UniquePtr<MlxArray>` rather than a `Result`, so the C++ `std::invalid_argument` becomes an uncatchable `std::terminate` (SIGABRT), and it fires at the first forward pass rather than at load. Every value MLX would throw on is therefore rejected in Rust, at load: zero, negative, odd, greater-than-`head_dim`, NaN and both infinities (the `as i32` cast saturates, turning NaN into 0 and infinity into `i32::MAX`, but the non-finite case is rejected explicitly so the message names the real problem). `rotary_emb_base` is rejected when non-positive or non-finite, since RoPE takes its logarithm and a zero or negative base makes every rotated channel NaN without anything throwing. `config_validation_rejects_out_of_range_rope_parameters` covers all of these plus both accepted boundaries (the floor is two rotary dimensions, not one, since one is odd), and `every_accepted_rotary_pct_survives_a_real_rope_call` sweeps `rotary_pct` at both head widths and puts every accepted value through a real `fast_rope` call, so the guard drifting away from MLX's contract aborts the test binary rather than production. - **`layer_norm_eps` and the `quantization` block are validated at load too**, closing the same failure shape for two more config-controlled floats that `validate_rope` did not cover. `layer_norm_eps` is the third float this family lets a config author control; `fast::layer_norm` never looks at it (`x * rsqrt(mean(x^2) + eps)`), so a non-finite, negative or zero value makes every hidden state NaN without anything throwing, and the checkpoint loads cleanly and then generates uniform garbage instead of failing to load. `quantization.group_size` and `quantization.bits` reach `quantized_matmul` and `dequantize` unreconciled (`reconcile_quantization_layout` treats a non-positive pair as insufficient shape info and passes it through unchanged), and MLX's own `packed_in * 32 / bits` check divides by zero at `bits == 0` and collapses to zero above 32, throwing the same uncatchable `std::terminate` the `rotary_pct` guard exists to prevent; the bound is a range (`1..=32` for `bits`, positive for `group_size`) rather than an allowlist, since mlxcel deliberately re-derives an effective bit width from the tensor shapes when the declared one disagrees, and an allowlist would reject the mixed-precision exports that behavior serves. `config_validation_rejects_a_layer_norm_eps_that_would_nan_every_hidden_state` and `config_validation_rejects_a_quantization_block_that_would_abort_an_mlx_kernel` cover both guards, including the values that must stay accepted. - **Every gather and slice bound by the real tensor shape.** The `embed_in` table is checked against `vocab_size` at load, because MLX wraps a negative gather index but does not range-check a positive one, so a config that overstates the table turns an ordinary prompt into an out-of-bounds read whose result reaches the logits. Every projection, bias and norm is checked against the config-implied shape in *every* layer, not just layer 0. - **The quantized branch does not skip the shape contract.** Packing compresses the input axis only, so the row count is untouched and is checked on the quantized path exactly as on the float path, along with the 1-D bias; only the packed input width is left to `UnifiedLinear`. That check is load-bearing here specifically because `Attention::forward` reshapes the fused projection to `[batch, seq, num_heads, 3 * head_dim]` using config-derived widths, so a packed `query_key_value` of a different real width makes the reshape throw, and an MLX C++ exception crossing the cxx bridge is an uncatchable `std::terminate` rather than a load error. This is the same carve-out lablup#926 had to close after review, closed here before it was opened. - **Which GELU, stated explicitly.** `mlxcel_core::utils::gelu_approx` is the erf-based *exact* GELU in this tree despite its name (the tanh form was deliberately replaced in `mlx_cxx_bridge.cpp` because `power(x, 3)` produced NaN for negative bf16 inputs). That matches Pythia's declared `hidden_act` of `"gelu"`, which HuggingFace resolves to the exact erf GELU, and differs from the tanh approximation upstream mlx-lm applies by under 5e-4 per element (MLX's own documented bound over `[-6, 6]`). The reasoning is written out at the call site. A config declaring a non-GELU `hidden_act` is reported via `eprintln!` rather than rejected, since the activation cannot corrupt memory and `tracing::warn!` is a no-op on the CLI path this is reachable from. - **No grouped-query attention.** Upstream's `num_key_value_heads` is vestigial: its `__post_init__` defaults it to `num_attention_heads` but `Attention` never reads it, and HuggingFace `GPTNeoXAttention` has no such concept. The fused projection is `3 * hidden_size` wide and reshaped to `(num_heads, 3 * head_dim)`, so Q, K and V always carry the same head count; the field is deliberately absent from this config struct and the forward test asserts the cached KV head count is `num_attention_heads`. - `src/models/gpt2.rs`: the shared `validate_embedding_table` gains a `width_field` parameter so its rejection message names the config field the reader will actually find in their `config.json` (`hidden_size` here, `n_embd` in the GPT-2 lineage). The three shared helpers' `// Used by:` comments are updated. GPT-2 and GPT-BigCode behavior is otherwise unchanged; `src/models/gpt_bigcode.rs` is touched only for the two updated call sites. - `src/models/mod.rs`: module declaration, `GptNeoxModel` re-export, and `ModelType::GptNeoX` in all four places that must agree (the enum, `ALL_MODEL_TYPES`, the `metadata()` display table, and the `all_variants!` exhaustiveness list). `src/models/detection.rs`: `"gpt_neox" => Ok(ModelType::GptNeoX)`, plus a detection test asserting it does not fall through to either GPT-2-lineage arm. `src/model_metadata.rs`: standard config-backed registration. `src/loaded_model.rs`: variant and `delegate_language_model!` arm. `src/distributed/tensor_parallel/inference.rs`: `"gpt_neox"` fallback architecture string, keeping the dispatch table total; TP is refused by `validate_supported_runtime`, whose `runtime_kind_for` match has no arm for this variant. Sharding would need its own rules regardless, since a row split at any offset a generic plan would pick cuts through the middle of a head's Q, K and V rather than between whole heads. - `src/models/gpt_neox_tests.rs` (32 tests) and `docs/supported-models.md`. - **Finalization pass.** Two `format!` error strings in `validate_norm_eps` and `validate_quantization` had literal multi-space gaps left over from wrapping the prose without converting it to the backslash-continued style the rest of the file uses; rewritten with no behavior change. The `docs/supported-models.md` entry now also names the `layer_norm_eps` and `quantization` rejections above. Both fix commits were verified by reverting each in isolation: without the odd-`dims` rejection, `config_validation_rejects_out_of_range_rope_parameters` fails cleanly and `every_accepted_rotary_pct_survives_a_real_rope_call` then feeds an odd `dims` to a real `fast_rope` call and aborts the whole test binary with SIGABRT (`[rope] dims must be even but got 1.`), rather than failing cleanly; without the `layer_norm_eps` / `quantization` guards, the two tests named above fail cleanly (no MLX call is reached, so no abort). All three pass again with the fixes restored. ## Test plan - [x] `cargo fmt --all -- --check` - [x] `cargo check --release --lib --tests --features metal,accelerate` - [x] `cargo clippy --release --lib --tests --features metal,accelerate` (no new findings; the two warnings in `src/multimodal/host_preprocessor*.rs` are pre-existing on `main` and untouched here) - [x] `cargo test --release --lib --features metal,accelerate models::gpt_neox` (32 passed) - [x] `cargo test --release --lib --features metal,accelerate models::gpt2` (25 passed, unchanged by the `validate_embedding_table` signature change) - [x] `cargo test --release --lib --features metal,accelerate models::gpt_bigcode` (20 passed, likewise) - [x] `cargo test --release --lib --features metal,accelerate detection_tests` (24 passed) - [x] `cargo test --release --lib --features metal,accelerate models::metadata_tests` (4 passed: the registration and `ALL_MODEL_TYPES` exhaustiveness gates) - [x] `cargo test --release --lib --features metal,accelerate distributed::tensor_parallel` (338 passed, 4 ignored) - [x] `python3 scripts/ci/check_cross_repo_refs.py` - [x] Mutation check on the interleaved split, described in full above: the naive flat form fails exactly the three value-level tests and passes the other 26. - Unit coverage beyond the split: the real pythia-1b config field set and the bare-config defaults; scalar, list and empty-list token-id fields with the bos fallback; partial-RoPE dimensioning including `int()` truncation and the full-rotation case; `intermediate_size` versus the `4 * hidden_size` fallback including explicit `null`; the non-GELU activation predicate; eight hostile integer scalars plus `max_position_embeddings` and the `4 * hidden_size` overflow boundary; nine out-of-range RoPE parameters plus both accepted boundaries; detection of both key layouts, their rejection path, and their producing identical logits; the registered-buffer strip including that the real biases survive and that a second pass removes nothing; the model building identically with and without the buffers present; every projection loading with its stored `[out, in]` shape unchanged; rejection of a transposed weight, a rank-3 weight, a mis-sized bias, a missing projection, a later layer that disagrees with the config, an `embed_in` table shorter than `vocab_size` claims, a table or either norm of the wrong width, and an untied config with no `embed_out`; a quantized projection that skips only the packed input-width check while its output row count (wider and narrower) and its bias are still rejected by name; both residual layouts recomputed from their own sub-modules and asserted non-interchangeable; and prefill-then-decode under both residual settings asserting the logits shape, the advancing cache offset and the cached KV head count. - Not run here: the release build and the token-exact real-checkpoint validation against `models/pythia-1b`, which the maintainer is running separately. Closes lablup#836
Summary
Adds GPT-BigCode (
gpt_bigcode), the architecture behind the BigCode StarCoder and SantaCoder code models, as a fully integrated text model: config parse, loader, decoder graph, detection, registration,LoadedModeldispatch, docs and unit tests. It is a GPT-2 derivative, so it builds on the block skeleton landed in #924 rather than restating it.Correction to the issue body
The issue says
c_attn/c_projare "stored in the Conv1D layout like GPT-2". That is wrong, and following it would have silently corrupted every projection. HuggingFaceGPTBigCodebuilds its projections withnn.Linear, not theConv1Dthat GPT-2 uses, so the weights are already[out, in], which is the layoutmlxcel_core::layers::Linearwants. Shapes read directly from thebigcode/gpt_bigcode-santacoderSafeTensors header:Compare GPT-2, whose
c_attn.weightis[768, 2304]=[in, out]and does need the transpose. Upstreamgpt_bigcode.pycorrespondingly has nosanitizemethod at all. There is therefore no transpose in this port, andload_linearrejects a weight that arrives in the transposed orientation by name with an error that explains why GPT-BigCode is not Conv1D, so the claim cannot be reintroduced silently later.a_conv1d_oriented_weight_is_rejected_and_namedpins that behavior.What changed
src/models/gpt_bigcode.rs(new):ModelArgsfor the GPT-2-style config field names plusmulti_queryandn_inner, the decoder graph,detect_prefix,load_linear, and theLanguageModelimpl.multi_query: trueexactly one KV head is shared by every query head, so the fusedc_attnprojection producesn_embd + 2 * kv_dimfeatures rather than3 * n_embdand is split at[n_embd, n_embd + kv_dim], which is not an even three-way split. On santacoder that is 2048 + 2 * 128 = 2304 for 16 query heads of width 128 over a single KV head. This maps onto the existing GQA attention path withn_kv_heads = 1; MLX broadcasts the shared KV head across the query heads exactly as it does for the GQA families, so no new attention code is involved.ModelArgs::qkv_split_offsetsexposes the split as a pure function so the uneven offsets are unit-tested without a checkpoint, and the tiny forward tests assert the cached KV head count directly (1 under MQA,n_headwhenmulti_queryis false).n_inner(8192 on santacoder), not a hardcoded4 * n_embd. An absent ornulln_innerfalls back to4 * n_embd, matching HuggingFace.persistent=False, so unlike GPT-2 noh.N.attn.biastensor reaches the checkpoint; the santacoder export carries 292 tensors, none matching that shape. GPT-2'sstrip_causal_mask_bufferspass is deliberately not copied.transformersubmodule, and upstream ships nosanitizethat could rename it, so GPT-2's multi-prefix probe is not copied either;detect_prefixacceptstransformer.and rejects anything else with a message naming the key it looked for.ModelArgs::validaterejectsn_head == 0, an indivisible head split, and out-of-rangen_embd/n_layer/n_positions/vocab_size/n_innerat load, beforen_layersizes theVec::with_capacityinfrom_weightsand before any derivedas i32cast can truncate. Every gather is bounded by the real tensor shape rather than a config field: both thewpeand thewtetable are checked againstn_positionsandvocab_sizeat load, because MLX wraps a negative gather index but does not range-check a positive one, so a config that overstates a table turns an ordinary prompt into an out-of-bounds read whose result reaches the logits. Every projection, bias and norm is checked against the shape the config implies in every layer, not just layer 0, since an MLX C++ exception crossing the cxx bridge is an uncatchablestd::terminaterather than a load error. There is no unbounded probe loop over0..n_layeron the load path.wteand ships nolm_headtensor, which is whytie_word_embeddingsdefaults to true. An untied config must actually carry the tensor; silently falling back to the tied path would produce logits from the wrong matrix. GPT-BigCode has no family-wide<|endoftext|>id (santacoder uses 49152, StarCoder uses 0), soeos_token_idsfalls back fromeos_token_idtobos_token_idand then to empty rather than guessing an id that could truncate at an ordinary token.src/models/gpt2.rs: three helpers are made shared rather than duplicated, each carrying the// Used by:comment the project convention asks for.dim_eqandlayer_norm_from_weightsbecomepub(crate), with the latter now taking the model width and epsilon directly and validating the norm shape;validate_position_tableis generalized tovalidate_embedding_tableso it covers the token table as well as the position table. GPT-2 behavior is unchanged apart from the added norm-shape rejection.src/models/mod.rs: module declaration,GptBigCodeModelre-export, andModelType::GptBigCodein all four places that must agree (the enum,ALL_MODEL_TYPES, themetadata()display table, and theall_variants!exhaustiveness list).src/models/detection.rs:"gpt_bigcode" => Ok(ModelType::GptBigCode), plus a detection test asserting it does not fall through to thegpt2arm.src/model_metadata.rs: standard config-backed registration, so both the directory route and the owned-weights route go through the shared registry.src/loaded_model.rs: variant anddelegate_language_model!arm.src/distributed/tensor_parallel/inference.rs:"gpt_bigcode"fallback architecture string; the fusedc_attnkey names have no shard rules and the multi-query KV block cannot be split across ranks anyway.generate_shard_planhas nogpt_bigcodearm and still produces a generic transformer plan through its fallback, butvalidate_supported_runtime'sruntime_kind_formatch has no arm forModelType::GptBigCodeeither, so TP is refused with an unsupported-architecture error before any load is attempted; the entry here exists to keep the dispatch table total.src/models/gpt_bigcode_tests.rs(new, 20 tests) anddocs/supported-models.md.Follow-up fix: quantized projection output width (
165f8199c)load_linearreturned early for any projection carrying a.scaleskey, so a packed weight reached the graph with neither its output width nor its bias shape checked. That carve-out is wrong for this family specifically, becauseAttention::forwardslices the fusedc_attnoutput at offsets derived fromconfig.json([n_embd, n_embd + kv_dim]), not from the tensor itself. A packedc_attnwider than the config claims leaves every slice in bounds, so the model loads and decodes fluent-looking output while K and V are silently read from arbitrary interior channels; the reachable case is a quantized conversion whoseconfig.jsonomitsmulti_query(which then defaults totrue) against a weight packed for full multi-head attention. A packed weight narrower than the config claims takes the other branch instead, where MLX'ssliceclamps the stop index and the followingreshapethen throws, crossing the cxx bridge as an uncatchablestd::terminate.Quantization packs the input axis only, so the row count is untouched by packing and is now checked on the quantized path the same way it already was on the float path, along with the 1-D bias; the packed input width stays unchecked, since no float layout applies to it and
UnifiedLinearreconciles that half of the contract itself.a_quantized_projection_skips_the_packed_input_width_but_not_the_output_width(renamed and extended from the earlier, now-inaccurateload_linear_delegates_a_quantized_projection_unchecked) covers a wider packed weight, a narrower one, and a mis-sized packed bias.Finalization polish
Corrected two doc comments this chain had left inconsistent:
src/models/gpt2.rsdescribed the sharedmlxcel_core::utils::gelu_approxhelper as the tanh approximation, which contradicts both the C++ implementation inmlx_cxx_bridge.cpp(erf-based) and this port's own, correct description of the same helper insrc/models/gpt_bigcode.rs; and thesrc/distributed/tensor_parallel/inference.rscomment forModelType::GptBigCodenamed the wrong mechanism for the TP refusal (corrected wording is in theWhat changedbullet above). Also extended thedocs/supported-models.mdGPT-BigCode entry, written before165f8199clanded, to describe the quantized output-width check that commit added.Test plan
cargo fmt --all -- --checkcargo check --release --lib --tests --features metal,acceleratecargo clippy --release --lib --tests --features metal,accelerate(no new findings; the two warnings insrc/multimodal/host_preprocessor*.rsare pre-existing onmainand untouched here)cargo test --release --lib --features metal,accelerate models::gpt_bigcode(20 passed)cargo test --release --lib --features metal,accelerate models::gpt2(25 passed, unchanged by the shared-helper refactor)cargo test --release --lib --features metal,accelerate detection_tests(23 passed)cargo test --release --lib --features metal,accelerate models::metadata_tests(4 passed: the registration andALL_MODEL_TYPESexhaustiveness gates)cargo test --release --lib --features metal,accelerate distributed::tensor_parallel(338 passed, 4 ignored; unaffected by the comment-only inference.rs change)python3 scripts/ci/check_cross_repo_refs.pysrc/models/gpt_bigcode.rshalf of165f8199cwhile keeping its paired test, confirminga_quantized_projection_skips_the_packed_input_width_but_not_the_output_widthis the sole failure in themodels::gpt_bigcodesuite, then restored the fix.kv_dim,c_attnoutput width and the uneven split offsets, asserted to differ from both3 * n_embdand the even thirds; themulti_query: falsedegeneration;n_innerversus the4 * n_embdfallback including explicitnull; prefix detection and its rejection path; every projection loading with the stored[out, in]shape unchanged; rejection of a Conv1D-oriented weight, a rank-3 weight, a mis-sized bias, a missing projection, a later layer that disagrees with the config, awpeorwtetable shorter than the config claims, a table or norm of the wrong width, and an untied config with nolm_head; a quantized projection that skips only the packed input-width check while its output row count (both wider and narrower than the config implies) and its bias are still validated and rejected by name; and two tiny end-to-end prefill-then-decode runs asserting the logits shape, the advancing cache offset and the cached KV head count under bothmulti_querysettings.models/gpt_bigcode-santacoder, which the maintainer is running separately.Closes #834