Skip to content

feat(models): add GPT-BigCode (gpt_bigcode) text model support - #926

Merged
inureyes merged 3 commits into
mainfrom
feature/issue-834-gpt-bigcode-support
Jul 26, 2026
Merged

inureyes merged 3 commits into
mainfrom
feature/issue-834-gpt-bigcode-support

Conversation

@inureyes

@inureyes inureyes commented Jul 26, 2026 •

Copy link
Copy Markdown
Member

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 #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 feat(models): add GPT-2 (gpt2) text model support #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

  • cargo fmt --all -- --check
  • cargo check --release --lib --tests --features metal,accelerate
  • 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)
  • 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 and ALL_MODEL_TYPES exhaustiveness 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.py
  • 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 #834

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
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:low Low priority area:models Model architectures, weights, loading, metadata labels Jul 26, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Real-checkpoint validation on Apple M1 Ultra (Metal + Accelerate, release build).

GPT-BigCode is token-exact against the mlx-lm reference. mlxcel generate -m models/gpt_bigcode-santacoder -p "def fibonacci(n):" -n 60 --no-chat-template reproduces the reference continuation exactly (correct recursive Fibonacci plus the trailing print(fibonacci(10))), at 48.9 tok/s. This exercises the MQA path end to end: one shared kv head across all 16 query heads, with the fused c_attn split at [dim, dim + kv_dim] rather than a 3-way even split.

mlxcel arch reports GPT-BigCode (StarCoder / SantaCoder, multi-query attention).

No GPT-2 regression from the shared-helper refactor. This PR lifts dim_eq, layer_norm_from_weights, and the generalized validate_embedding_table out of the merged src/models/gpt2.rs, so I re-ran the GPT-2 gate: generation from models/gpt2 is byte-identical to the output on merged main before the refactor.

On the GELU question. The implementation matches upstream mlx-lm, which applies the erf-based nn.gelu even though this config declares gelu_pytorch_tanh. I checked whether that distinction is observable here by monkey-patching the mlx-lm reference to use nn.gelu_approx (the tanh form) and regenerating: both variants emit the identical 60 token ids. So the sub-1e-3 activation difference flips no argmax on this checkpoint, and matching upstream is not masking a defect. Worth keeping in mind only if a future GPT-BigCode checkpoint shows divergence from HuggingFace output.

@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Add GPT-BigCode (gpt_bigcode, StarCoder / SantaCoder) as a fully integrated text model, reusing the GPT-2 block skeleton from #924 and mapping Multi-Query Attention onto the existing GQA path with n_kv_heads = 1.

Findings Addressed

None. No CRITICAL or HIGH finding was identified, so no code was changed on this branch.

Verified Rather Than Accepted

  • Shared-helper generalization is not a weakening. validate_position_table to validate_embedding_table (src/models/gpt2.rs:834) is logic-identical to the merged form; only n_positions / n_embd became parameters. GPT-2's call site (gpt2.rs:777) passes the original values, src/models/gpt2_tests.rs is untouched by this PR, and both regression tests still assert on the original substrings (n_positions, n_embd). 25 GPT-2 tests pass unchanged.
  • The Conv1D rejection cannot fire on a legitimate checkpoint. load_linear (src/models/gpt_bigcode.rs:406) reaches the rejection only when is_expected is false. For a square projection [in, out] and [out, in] are the same predicate, so is_expected is true and the branch is unreachable. The transposed hint is text on an already-failing path.
  • MQA split matches upstream exactly. mlx_lm/models/gpt_bigcode.py splits at [dim, dim + kv_dim] giving Q, then K, then V. gpt_bigcode.rs:465-467 produces the same three ranges in the same order; K and V are not swapped. cache.update_and_fetch(k, v) argument order is correct.
  • No mask buffer to strip, confirmed against the checkpoint. The models/gpt_bigcode-santacoder SafeTensors header carries 292 tensors, zero keys ending .attn.bias, and zero tensors of rank greater than 2. c_attn.weight is [2304, 2048], wte is [49280, 2048], wpe is [2048, 2048], no lm_head.weight, all keys transformer.-prefixed. Every claim in the PR body holds.
  • EOS fallback has no falsy-value bug. eos_token_ids (gpt_bigcode.rs:336) selects on !ids.is_empty(), not on the id value, so StarCoder's eos_token_id: 0 yields [0] correctly. The empty-list outcome is reachable only for a config declaring neither eos_token_id nor bos_token_id; -n -1 still resolves through context_window_from_config, which reads n_positions, so generation remains bounded. Declining to invent a family-wide id is the right call here.
  • Config-trust hardening is real. validate() runs before Vec::with_capacity on both routes (load and from_weights), n_head <= n_embd <= 65536 is implied by the divisibility check so every as i32 cast is in range, there is no probe loop over 0..n_layer, and both wte and wpe are bounded against real tensor rows. The wte check is new relative to GPT-2.
  • Registration surfaces are complete. ModelType, ALL_MODEL_TYPES, metadata(), all_variants!, detection.rs, model_metadata.rs, loaded_model.rs, distributed/tensor_parallel/inference.rs and docs/supported-models.md all carry the variant. display_name() and family() derive from metadata(), and family Specialized is already in FAMILY_ORDER. Paged decode, TurboQuant symmetric KV and the hybrid-SSM prompt-cache deny list are all opt-in or deny-by-default, so no entry is required. Tensor parallel is refused for tp_size > 1 via runtime_kind_for's _ => None.

Remaining Items

  • (MEDIUM) src/execution/kv_arch.rs:244 and :163, src/execution/memory_estimate.rs:510 and :721, src/execution/quant_advisor.rs:61 alias num_hidden_layers / n_layers / num_layers and hidden_size / d_model / dim, but never the OpenAI-era n_layer / n_embd / n_inner. mlxcel inspect therefore reports KV cache 0 bytes and activation 0 bytes for this family, --recommend-kv-cache prints nothing, and mlxcel serve logs a KV-geometry-unavailable warning because --kv-cache-budget defaults to auto. Inert today (the family does not opt into paged decode) and shared verbatim with gpt2 from feat(models): add GPT-2 (gpt2) text model support #924, so it is a follow-up rather than a blocker. Trap for whoever fixes it: kv_arch.rs:150 has no branch for the boolean multi_query flag, only ChatGLM's multi_query_group_num, so adding the aliases alone would produce a 16x KV over-estimate for SantaCoder.
  • (MEDIUM) src/models/gpt_bigcode.rs:396 short-circuits a quantized projection past the float shape contract, so a malformed quantized c_attn would reach slice_last_dim and abort through the cxx bridge rather than returning a load error. Deliberate, documented, unit-tested, and identical to gpt2.rs:323. No public quantized gpt_bigcode checkpoint exists.
  • (LOW) src/distributed/tensor_parallel/inference.rs:221-224 states that "the planner's supported-architecture validation rejects this string". generate_shard_plan actually accepts it through the _ => generic-transformer fallback at plan_generator.rs:157. The real refusal is runtime_kind_for's _ => None at llama_runtime.rs:2225, surfaced by validate_supported_runtime. The outcome is correct, only the mechanism is misdescribed. Copied from the GPT-2 comment.
  • (LOW) src/models/gpt2.rs:29-30 claims gelu_approx is the tanh approximation. It is erf-based (mlx_cxx_bridge.cpp:2653, "Use erf-based exact GELU instead of the original tanh approximation"). gpt_bigcode.rs:549-552 states this correctly, so two sibling files now contradict each other. Pre-existing from feat(models): add GPT-2 (gpt2) text model support #924.
  • (LOW) intermediate_size() maps n_inner: 0 to the 4 * n_embd fallback instead of rejecting it. HuggingFace would yield 0. Harmless: the c_fc shape check then fails loudly against the real tensor.

Suggestions Reviewed and Declined

  • Adding a per-file mlx-lm derivation notice: declined. Zero of the 157 files under src/models/ carry one, including gpt2.rs. The convention there is //! Reference: <GitHub URL>, and NOTICE lines 28-48 already carry the mlx-lm MIT attribution for "mlxcel's model architectures". The per-file convention is applied to src/lib/mlxcel-core/src/cache/turbo/ and src/audio/qwen3_omni_moe/, which is what the guideline's example targets.
  • Requiring an exact wte row count for tied heads: declined. It would reject legitimate checkpoints that pad the embedding table for alignment while declaring the true vocab_size, and slicing the tied logits would diverge from upstream mlx-lm, whose Model.__call__ applies wte.as_linear over every row unsliced. That would break the token-exactness gate this PR was validated against.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass

cargo check --release --lib --tests --features metal,accelerate clean (only the two pre-existing host_preprocessor warnings). cargo test --release --lib --features metal,accelerate models::gpt 46 passed, 0 failed. cargo fmt --all -- --check clean. scripts/ci/check_cross_repo_refs.py clean.

`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
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

Scope: 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

  • Untrusted-config hardening is complete for this family's own surface. Every scalar that sizes an allocation, indexes a table, divides, or feeds an as i32 cast is bounded in ModelArgs::validate before it is used: the zero check on n_head precedes the divisibility check (0.is_multiple_of(0) is true, so the order matters), and n_embd being a nonzero multiple of n_head transitively bounds n_head <= n_embd <= 65536. That makes every derived quantity fit i32 with room to spare: kv_dim <= 65536 and c_attn_out_features() = n_embd + 2 * kv_dim <= 196608, so the MQA arithmetic cannot overflow or truncate. n_inner is checked through intermediate_size(), which is the value that actually sizes the MLP projections. There is no unbounded probe loop on the load path, and Vec::with_capacity(n_layer) is capped at 1024.
  • The CRITICAL from feat(models): add GPT-2 (gpt2) text model support #924 is correctly carried over and extended. n_positions is only stored on the model after validate_embedding_table has proved n_positions <= wpe.weight rows, so the clamp bound in position_ids is bounded by the real tensor, not by a config field. The same check is newly applied to wte against vocab_size.
  • Shared helpers were not weakened. validate_embedding_table is validate_position_table with the row bound and the field name parameterized; the rejection condition (claimed_rows > rows), the zero-row guard and the quantized-width carve-out are unchanged. layer_norm_from_weights is strictly stronger than before: it now rejects a norm weight or bias that is not 1-D of width n_embd, which previously reached MLX. dim_eq is unchanged. Nothing here loosens the merged GPT-2 path.
  • MQA maps onto the existing GQA path with no materialization. n_kv_heads = 1 reaches mlx::core::fast::scaled_dot_product_attention unchanged; MLX broadcasts the shared KV head internally and there is no repeat_kv anywhere on the route, so K and V are stored and read once rather than 16 times. KVCache holds one head per layer, which is the whole point of the architecture.
  • Per-decode-step position-id cost is negligible and identical to GPT-2's. A one-element Vec<i32> and a 4-byte host-to-device array per step, with no forced evaluation. The cache offset is read once before the layer loop, so update_and_fetch advancing it mid-loop cannot corrupt the lookup.
  • Split offsets, n_kv_heads, scale, the erf GELU, the tied head and the top-level lm_head key all match https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/gpt_bigcode.py line for line.

MEDIUM (fixed in 165f819)

A quantized projection reached the graph with its output width unchecked. src/models/gpt_bigcode.rs load_linear returned early for any prefix carrying a .scales tensor, skipping both the shape contract and the bias check. That carve-out is inherited from GPT-2, but it is more dangerous here because Attention::forward slices the fused c_attn output at offsets derived from config.json rather than from the tensor.

Failure scenario: a 4-bit conversion whose config.json omits multi_query (it defaults to true, so the loader computes 2048 + 2 * 128 = 2304) while the packed c_attn is the multi-head 3 * 2048 = 6144 width. All three slices stay in bounds, so Q is correct while K and V are read from arbitrary interior channels of the projection. The model loads, decodes and emits fluent-looking output with no error anywhere, which is exactly the outcome load_linear exists to prevent for the transposed float case. The mirror case (packed weight narrower than the config claims) takes the other branch: MLX's slice clamps the stop index rather than erroring, and the following reshape 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; the row count and the 1-D .bias are now checked on both paths. No legitimate export is rejected, since mx.quantize on an [out, in] weight always yields [out, in * bits / 32]. Covered by the extended a_quantized_projection_skips_the_packed_input_width_but_not_the_output_width.

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 --kv-cache-budget auto leaves the paged KV pool unbounded. src/execution/kv_arch.rs:244 requires num_hidden_layers / n_layers / num_layers, and attn_dims at kv_arch.rs:163 requires hidden_size / d_model / dim / model_dim. GPT-BigCode writes n_layer and n_embd, so classify returns None, estimate_kv_arch yields nothing, kv_cache_bytes_per_token returns 0, paged_block_bytes returns None, and resolve_paged_block_budget returns None. src/server/model_worker.rs:729 then logs "the model's KV geometry is unavailable; leaving the paged pool unbounded".

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 mlxcel inspect estimate also reports KV as 0 bytes.

The condition is inherited: GPT-2 (merged in #924) writes the same key names and is in the same state on main, which is why this is a follow-up rather than a change inside a model-port PR. Anyone fixing it should land all three pieces together, because the first two alone introduce a new error: adding n_layer and n_embd to the key lists is correct for GPT-2 (plain MHA, num_kv_heads correctly defaults to n_head), but for GPT-BigCode attn_dims has no multi_query handling, so num_kv_heads would default to n_head and over-reserve MQA KV by n_head times: 16x on santacoder, 48x on StarCoder. An over-reservation of that size is the opposite outage, admitting roughly 1/48 of the sequences the model can actually hold.

A quantized embedding table's dequantized width is still unchecked. validate_embedding_table skips the cols == n_embd comparison when the table is quantized, because the packed width is a function of the bit depth rather than the model width. A quantized wte or wpe whose real width is not n_embd therefore reaches ln_1.forward and the residual add with a mismatched last axis, which is the std::terminate path again rather than a load error. Closing this needs the dequantized in_features from UnifiedEmbedding rather than anything derivable from the row count, and the helper is shared with GPT-2, so it is left as a follow-up.

LOW

intermediate_size() treats n_inner: 0 as absent and falls back to 4 * n_embd, where HuggingFace would take the 0 literally. The consequence is only that validate's intermediate == 0 branch is unreachable (n_embd >= 1 is already established, so the fallback is at least 4). No security or correctness impact on any real config; noting it so the dead branch is not mistaken for live coverage.

Verification

cargo fmt --all -- --check, cargo clippy --release --lib --tests --features metal,accelerate (only the two pre-existing src/multimodal/host_preprocessor*.rs warnings, unchanged from main), and cargo test --release --lib --features metal,accelerate for models::gpt_bigcode (20 passed), models::gpt2 (25 passed, confirming the shared-helper refactor plus the new norm-shape rejection leaves GPT-2 unchanged) and detection_tests (23 passed).

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
@inureyes inureyes added status:done Completed and removed status:review Under review labels Jul 26, 2026
@inureyes
inureyes merged commit 4ed5e3b into main Jul 26, 2026
4 checks passed
@inureyes
inureyes deleted the feature/issue-834-gpt-bigcode-support branch July 26, 2026 19:16
inureyes added a commit that referenced this pull request Jul 26, 2026
## 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
@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
…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
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
## 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
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:low Low 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 GPT-BigCode (gpt_bigcode) text model support

1 participant