Repository navigation
fix(test): skip partial Muse Glimmer checkpoints instead of panicking - #1173
Conversation
`pinned_post_tower_weight_roots_and_shapes_match_published_contract` skipped gracefully only when `model.safetensors.index.json` was absent. With the index present but anything else it reads missing or corrupt, the shape an interrupted `hf download` or `mlxcel download` leaves behind, it unwrapped its way to an opaque panic: `config.json`, the index body, and every referenced safetensors shard were read with `unwrap`. An availability pre-check now parses the index once and shares it with the assertion body, confirming that `config.json` and each shard named for a pinned weight root is present and readable before anything is asserted. `safetensors_shape` returns a `Result`, so a truncated or unparseable shard header also skips rather than panicking, and it bounds the declared header length against the file size before allocating. Every skip message names the offending path. The skip stays deliberately narrow. Only availability and readability may skip: an absent file, an unreadable file, JSON that does not parse, a truncated header. Contract violations still fail, so a `weight_map` missing a pinned root, a config `validate()` rejects, and a shard whose recorded shape disagrees with the config all reach the unchanged `assert_eq!` calls. Two `should_panic` tests over synthetic checkpoints prove that boundary holds, and six more assert the pre-check names the specific missing file. Adds opt-in `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1`, read under the crate-wide env lock, which turns skips into failures so a corrupted checkpoint cannot quietly disable the contract check forever on the machine that owns it. The pinned block moves to `muse_glimmer_fusion_pinned_tests.rs`, attached as a second test module, because it reads files off disk rather than exercising fusion math and the synthetic coverage would otherwise push the original file well past 500 lines. Validated on a machine holding the real pinned checkpoint: `cargo test --lib vision::encoders::muse_glimmer_fusion` passes 19/19, and passes again under `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1`, which proves the contract path executed rather than skipping. Running the test binary from a directory without `models/` skips with the named reason, and fails under the env var. Nothing under `models/` was moved or modified; all partial checkpoints are synthesized in `tempfile::tempdir()`. Refs #1161
Implementation Review SummaryIntent
Correctness boundary auditEvery path in
FindingsMEDIUM: a LOW: the mid-loop skip can mask a later contract violation ( LOW: the header-length bound is file-relative only ( LOW: LOW: the empty- LOW: body inaccuracies that become the squash commit body. The PR body says "eleven new tests"; there are 13 new (14 in the file, 19 in the module overall). Both the PR body and the commit body justify the file split by a "500-line limit" that is not this repo's convention: the repo's own INFO: only one of the two pinned guards is hardened. Env lockNo deadlock is possible. ScopeProportionate, with room to trim. Of the 499 lines, roughly half is the pinned test and helper that merely moved, and the synthetic coverage is what the issue explicitly asked for. The doc comments are longer than the surrounding code's norm and could lose about 30 lines without losing meaning, but they document the correctness boundary, which is the substance of the issue. Not worth churn. Verification
No changes were made by this review; all findings are reported for the author to accept or decline. |
The availability pre-check deserialized config.json straight into MuseGlimmerConfig, so a config that is valid JSON but does not fit the schema was reported as an availability problem and skipped. Schema drift in the pinned config, or a different model dropped into the pinned directory, is exactly the divergence this contract test exists to catch, so it has to fail. The pre-check now parses config.json as plain JSON only, which still skips the truncated config an interrupted download leaves behind, and PinnedCheckpoint carries the raw Value. Deserializing into MuseGlimmerConfig moved next to validate() in the assertion body, where a mismatch panics. Also tightens two tests so they cannot pass for the wrong reason: the wrong-shape case now expects the assert_eq! custom-message prefix rather than a bare key name that three different panics emit, and the absent weight_map case gains the should_panic companion its missing-weight-root sibling already had. Adds both halves of the schema-mismatch boundary, the pre-check passing it through and the assertion failing on it.
safetensors_shape bounded the declared header length against the file size alone before allocating. That is loose enough to matter on the pinned checkpoint: its shards are 50 GB and 9.6 GB, so a corrupt eight-byte prefix can declare a header of several gigabytes and still sit under the file length, at which point vec![0u8; header_len] plus read_exact either aborts the test process on allocation failure or pulls gigabytes of tensor payload into memory. An abort is a worse outcome than the opaque unwrap this PR set out to remove, since it carries no reason at all. Adds an absolute 256 MiB ceiling checked before the file-relative bound, matching the guard read_safetensors_header_bytes in mlxcel-core already applies to the same prefix. The real pinned shard records an 11,720-byte header, so the margin is about four orders of magnitude and no genuine checkpoint can be rejected by it. Covered by safetensors_shape_refuses_a_header_over_the_allocation_ceiling, which declares u64::MAX in a tiny temp file so the test allocates nothing large either. Verified with cargo test --lib vision::encoders::muse_glimmer_fusion (23 passed), the same run under MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 against the real checkpoint (23 passed, so the ceiling does not turn the contract check into a skip), cargo clippy --lib --tests -- -D warnings, and cargo fmt --check. Refs #1161
Security and performance reviewReviewed at Fixed: unbounded header allocation against a multi-gigabyte shard (MEDIUM)
Verified clean
Observation, not blocking
Verification
|
Bilingual report covering the pinned Muse Glimmer skip guard: the availability versus contract boundary and how it is enforced structurally, the two defects found in review (a schema-mismatched config that skipped instead of failing, and a header allocation bounded only by file size), and how each acceptance criterion was proven using the new env gate against the real checkpoint.
The paragraph said a partially materialized checkpoint made the availability pre-check panic. There was no availability pre-check before #1173; that PR created it, and the panic came from unwrapping the reads directly. Restates what actually changed: unwraps became a pre-check that skips with a named reason while contract violations stay failures.
The paragraph claimed there was no availability pre-check before PR #1173. There was one, just a narrower one: PR #1157 (`92d6d4c8`) replaced the vision-side test's `assert!(index_path.exists(), ...)` with a silent skip and added the same index-absent skip to `pinned_weight_index_classifies_each_source_weight_once`. Issue #1161 records this as well, both in its third acceptance criterion and in its note that #1157 "added the index-absent guard". As written the paragraph implied every partially materialized state was loud before #1173, which overstates what that PR gave up and therefore what the gate buys back. An absent index already skipped quietly under #1157. Restates the sequence accurately: #1157 made the index-absent case quiet, #1173 made the index-present-but-incomplete case quiet by replacing the unwraps past that guard, and `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1` restores the loudness for both. Documentation only; no code, test, or gate behavior changes.
Bilingual report covering the shared pinned-checkpoint gate: why the gate had to move into test_support rather than be copied, why the loading-side panic on a classification error stays a panic, and why documenting when to enable the variable was half the deliverable given it was set nowhere in the tree. Records the two-step correction the pre-#1173 paragraph needed, since the #1157 and #1173 sequence is easy to state wrongly.
…REQUIRE_PINNED_CHECKPOINTS (#1180) ## Summary Extends the pinned-checkpoint gate PR #1173 introduced to the loading-side sibling test, shares the gate logic between both call sites instead of duplicating it, and documents the variable including when and how to actually turn it on, per the scope the issue's comment added. ## What changed `src/test_support/pinned_checkpoint.rs` (new) holds a single `skip_or_fail_pinned_checkpoint(test_name, reason)` helper, declared from `src/test_support/mod.rs` alongside the existing `env_lock` module; it reads `MLXCEL_REQUIRE_PINNED_CHECKPOINTS` under `crate::test_support::env_lock::env_lock()`, drops the guard before asserting, and treats only the exact value `1` as enabling. `src/vision/encoders/muse_glimmer_fusion_pinned_tests.rs` drops its private copy of the gate and calls the shared helper at both of its call sites, passing its own test name so the skip message is byte-identical to before and the failure message still names that test. `src/loading/vlm_muse_glimmer_tests.rs` routes `pinned_weight_index_classifies_each_source_weight_once`'s previously unconditional skip through the same shared helper, so it now fails rather than skips when the gate is on and the pinned index is absent; the existing `panic!` on `read_muse_weight_inventory_from_index` returning `Err` is untouched, since that is a genuine contract violation rather than an availability problem. `docs/environment-variables.md` adds a row for `MLXCEL_REQUIRE_PINNED_CHECKPOINTS` to the existing "Test and CI variables" table, whose `Variable | Purpose` shape carries the value and default semantics inline, stating that only the exact string `1` enables it, plus prose covering that it is test-only, that it belongs on a machine that owns the pinned checkpoint, a single-run invocation example and a persistent-export suggestion, and its role in turning an ambiguous `ok` into positive evidence that the checkpoint was actually read (how acceptance criterion 2 of #1161 was proven). ## Test plan - [x] `cargo check --lib --tests` - [x] `cargo clippy --lib --tests -- -D warnings` - [x] `cargo test --lib vision::encoders::muse_glimmer_fusion` (23 passed, real pinned checkpoint present) - [x] `cargo test --lib loading::vlm::muse_glimmer::` (14 passed, real pinned checkpoint present) - [x] Compiled test binary run from a temp directory with no `models/`, variable unset: both pinned guards skip, each still naming itself - [x] Compiled test binary run from a temp directory with no `models/`, `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1`: both pinned guards fail, each still naming itself, exit 101 Closes #1177
#1181) ## Summary The file-size and module-split thresholds existed only in the agent-facing `.claude/skills/mlxcel-code-structure/SKILL.md`, with no contributor-facing document referencing them, which is how PR #1173's commit body ended up citing a nonexistent "500-line limit." This PR adds a "File Size and Module Structure" section to `docs/code-guidelines.md` as the single authoritative home for those numbers, and widens the places that describe that document so the guidance is reachable by the normal contributor path. ## Option chosen Option 1 from the issue: the thresholds live in `docs/code-guidelines.md`, and the section states as a rule that anything else citing them, agent-facing tooling under `.claude/skills/` included, should link there rather than restate them. This is preferable because the thresholds are project convention that any human contributor needs, not agent-specific configuration; a document only agents read is the wrong home for a rule contributors are expected to follow. The tradeoff is that the skill file's structural rules are now split across two documents for a reader working through it top to bottom, but the pointer names exactly what moved and where, so that cost is small next to having one number that cannot drift. The rule is written prescriptively rather than as a claim about what any particular consumer currently contains, because no such claim is verifiable from this repository. ## Correction to the brief The brief this implementation started from asserted that `.claude/skills/` is tracked in this repository and instructed treating the skill-file edit as a real committed change. That is incorrect: `.gitignore` line 28 is `/.claude/`, committed at `HEAD`, and `git ls-files .claude/` returns zero files, so the entire `.claude/` directory is untracked here and ships no content with the repository. What was missing was therefore not de-duplication within this repository but a discoverable, contributor-facing home for the numbers, which this PR adds. ## What changed - `docs/code-guidelines.md`: new "File Size and Module Structure" section before "Shared Function Comments", carrying the size table (under 800 fine as a single file, 800 to 1,200 acceptable with a helpers file, 1,200+ extract `<name>_helpers.rs`, 1,500+ consider a directory module, 2,000+ with no helpers file as the anti-pattern), the reason-based exception for `nemotron_h.rs`, `llama4.rs` as an illustration of the 1,200+ row, an explicit note that several files sit well past the thresholds and should be read as debt rather than as precedent, the inline-test-versus-sibling-`_tests.rs` threshold (roughly 100 lines to move, 200 at the latest) with the wiring both forms of which this repository already uses, and the `<name>_helpers.rs` / `<name>_tests.rs` naming convention. - `CONTRIBUTING.md`: widened the intro paragraph and the "Quick links" row describing `docs/code-guidelines.md`, which called it narrowly the shared-function rules, and added a "Code standards" bullet linking straight to the new section. - `docs/README.md`: widened entry 19, which described `code-guidelines.md` as covering only the `// Used by:` convention and the JIT kernel rule, so the docs index names the thresholds too. Every line count quoted in the new section was measured against this branch rather than carried over, because the source this section was assembled from had gone stale: it recorded `nemotron_h.rs` at 2,342 lines (actually 2,914) and `llama4.rs` at 1,499 (actually 1,862), and its "complete model in one file" example, `qwen2.rs`, is a 31-line re-export shim over `llama3`, so `dbrx.rs` (606 lines, a full model through `impl LanguageModel`) replaced it. The section also tells readers the figures are approximate and to check the file rather than trust a number quoted anywhere, that section included. What was deliberately left in the skill file rather than carried into `docs/`: the module-versus-directory trigger, trait-placement rules, the model-registration checklist, subsystem dependency-direction rules, error-handling and config-deserialization patterns, and the rest of the anti-patterns table. That material is about how to structure new code while implementing a model, not something a contributor looks up as a size or split threshold. Out of scope, per the issue: the `0adb53c5` commit body on `main` is not rewritten, the PR #1173 technical report already records the discrepancy correctly, and the thresholds themselves are unchanged, only relocated and surfaced. ## Test plan - [x] Documentation-only change; no code or test files touched, so there is nothing for `cargo test` to exercise. - [x] Every file path and line count cited in the new section verified against this branch with `wc -l`, including that `nemotron_h.rs` has no sibling `_helpers.rs` and `llama4.rs` does. - [x] Confirmed `gemma3n_helpers.rs`, `llama4_helpers.rs` and `qwen3_next_helpers.rs` are the only `*_helpers.rs` files under `src/models/`. - [x] Confirmed `dbrx.rs` is a complete model (`Attention`, `SparseMoeBlock`, `DecoderLayer`, `DbrxModel`, `impl LanguageModel`) rather than a re-export shim. - [x] Confirmed the outlier claim: `gemma4.rs` 6,680 lines and `qwen3_5.rs` 3,451 lines both with no helpers file, `gemma3n.rs` 5,594 lines, and nine files under `src/models/` over 2,000 lines. - [x] Confirmed the `CONTRIBUTING.md` anchor `#file-size-and-module-structure` matches the `## File Size and Module Structure` heading, with no duplicate heading that would shift the slug. - [x] Confirmed the described sibling-test wiring matches this repository: both `#[cfg(test)] mod <name>_tests;` and the `#[path = "..."]` form are in use. Closes #1178
…lablup#1173) ## Summary `pinned_post_tower_weight_roots_and_shapes_match_published_contract` skipped gracefully only when `model.safetensors.index.json` was absent. With the index present but anything else it reads missing or corrupt, the shape an interrupted `hf download` or `mlxcel download` leaves behind, it unwrapped its way to an opaque panic instead of skipping with a reason. This adds an availability pre-check that names the offending file, while leaving every contract assertion able to fail exactly as before. ## Implementation choice The issue offered two options; this is the hybrid the brief recommended. Option 1 alone (a pure existence pre-check) cannot detect a shard that exists but whose header was truncated mid-download, and option 2 alone (converting each unwrap into a skip) reads the index twice, which the issue explicitly asked to avoid. The hybrid gets both: `load_pinned_checkpoint` parses the index once and hands the parsed `weight_map` to the assertion body, and `safetensors_shape` returns a `Result` so header corruption is covered too. ## How the correctness boundary is kept The skip is deliberately narrow, and the split is enforced by construction rather than by convention. - Only **availability and readability** may skip: an absent file, an unreadable file, JSON that does not parse, a truncated or unparseable safetensors header. `load_pinned_checkpoint` returns `Err` for exactly these, and `read_checkpoint_file` distinguishes "not present" from "could not be read" so the message names the path either way. - **Contract violations still fail.** The `assert_eq!` calls are untouched and are not wrapped in any skip path. `load_pinned_checkpoint` is structured so it cannot swallow one: a `weight_map` that is absent or non-object yields an empty map (which drives the weight-root assertion to fail, not to skip), and a pinned key absent from an otherwise well-formed `weight_map` is skipped over by the shard loop with a comment saying why, so the weight-root assertion is what reports it. - Inside `safetensors_shape`, a header that parses but does not describe the key as a shaped tensor panics rather than returning `Err`, following the issue's "if unsure whether it is missing or wrong, it is wrong" rule. - The contract assertions moved into `assert_post_tower_contract`, which takes an already-validated `PinnedCheckpoint` and contains no skip path at all. That split is what makes the two `should_panic` tests below possible. ## What changed - `src/vision/encoders/muse_glimmer_fusion_pinned_tests.rs` (new): the pinned-checkpoint contract check, the `load_pinned_checkpoint` availability pre-check, a `Result`-returning `safetensors_shape`, and synthetic partial-checkpoint coverage. `safetensors_shape` also bounds the declared header length against the file size before allocating, so a corrupt length cannot turn into a multi-gigabyte allocation. - `src/vision/encoders/muse_glimmer_fusion_tests.rs`: the pinned block and its now-unused imports removed, leaving 196 lines of fusion-math tests. - `src/vision/encoders/muse_glimmer_fusion.rs`: attaches `pinned_tests` as a second `#[cfg(test)]` module, the same pattern `src/vision/mod.rs` already uses. The split keeps both files under the 500-line limit; folding the synthetic coverage into the original file would have pushed it well past that. Test-only change. No production loading path is touched, and `src/loading/vlm_muse_glimmer_tests.rs` is untouched as the issue required. ## Synthetic-checkpoint tests The real pinned checkpoint is either complete or absent, so the partial cases cannot be exercised against it, and nothing under `models/` may be moved or truncated to fake one. All eleven new tests build throwaway checkpoints in `tempfile::tempdir()` (already a dev-dependency, no new dependency added). Pre-check names the specific missing or unreadable file: `pinned_precheck_names_an_absent_index`, `pinned_precheck_names_a_missing_config`, `pinned_precheck_names_a_missing_shard` (index present naming a shard that does not exist), `pinned_precheck_names_an_unparseable_index`, `pinned_precheck_names_an_unparseable_config`, and `pinned_precheck_accepts_a_complete_synthetic_checkpoint` as the negative control. Pre-check refuses to swallow contract violations: `pinned_precheck_leaves_a_missing_weight_root_to_the_contract_assertion` and `pinned_precheck_leaves_an_absent_weight_map_to_the_contract_assertion` both assert the pre-check returns `Ok`, so the violation reaches the assertion. Contract violations still fail, proven executably rather than by reading the diff: `contract_assertion_still_fails_on_a_missing_weight_root` and `contract_assertion_still_fails_on_a_wrong_recorded_shape` are `#[should_panic]` tests over complete-but-wrong synthetic checkpoints. The second fails with `assertion left == right failed: model.vision_adapter.fc1.weight / left: [1, 1] / right: [4096, 6144]`, which is the shape assertion firing, not a skip. Header handling: `safetensors_shape_reads_a_well_formed_header`, `safetensors_shape_reports_a_truncated_header`, `safetensors_shape_reports_an_unparseable_header`. ## Optional env var `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1` is implemented. It is read inside `skip_or_fail_pinned_checkpoint` under `crate::test_support::env_lock::env_lock()`, held for the duration of the read, because this crate is edition 2024 and `src/server/muse_glimmer_startup_guard_tests.rs` mutates the process environment with `unsafe set_var` under that same lock; an unlocked read is the same class of race being fixed elsewhere in this chain. Only the exact value `1` enables it. It also turned out to be the cleanest way to prove acceptance criterion 2 on this machine: with skips disabled, the pinned test passing is positive evidence that it read the real checkpoint rather than silently skipping. ## Test plan - [x] `cargo test --lib vision::encoders::muse_glimmer_fusion` on a machine holding the real pinned checkpoint: `19 passed; 0 failed`. - [x] `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 cargo test --lib vision::encoders::muse_glimmer_fusion`: `19 passed; 0 failed`. Since any skip is a hard failure under this variable, this confirms the full pinned checkpoint still validates the weight-root and shape contract for real (criterion 2). - [x] Test binary run from a directory containing no `models/`: skips with `Skipping pinned_post_tower_weight_roots_and_shapes_match_published_contract: models/mlx/muse-glimmer-30b/model.safetensors.index.json is not present` (criterion 3, behavior unchanged). - [x] Same run with `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1`: fails with `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 but the pinned Muse Glimmer checkpoint is not usable: ... is not present` (criterion 4). - [x] `cargo clippy --lib --tests -- -D warnings`: clean. - [x] `cargo check --lib --tests`: clean. - [x] `cargo fmt --check` on all three changed files: clean. - [x] Nothing under `models/` or `/home/inureyes/models` was moved, renamed, deleted, truncated, or written to; both 50 GB and 9.6 GB shards verified present afterwards. Closes lablup#1161
…REQUIRE_PINNED_CHECKPOINTS (lablup#1180) ## Summary Extends the pinned-checkpoint gate PR lablup#1173 introduced to the loading-side sibling test, shares the gate logic between both call sites instead of duplicating it, and documents the variable including when and how to actually turn it on, per the scope the issue's comment added. ## What changed `src/test_support/pinned_checkpoint.rs` (new) holds a single `skip_or_fail_pinned_checkpoint(test_name, reason)` helper, declared from `src/test_support/mod.rs` alongside the existing `env_lock` module; it reads `MLXCEL_REQUIRE_PINNED_CHECKPOINTS` under `crate::test_support::env_lock::env_lock()`, drops the guard before asserting, and treats only the exact value `1` as enabling. `src/vision/encoders/muse_glimmer_fusion_pinned_tests.rs` drops its private copy of the gate and calls the shared helper at both of its call sites, passing its own test name so the skip message is byte-identical to before and the failure message still names that test. `src/loading/vlm_muse_glimmer_tests.rs` routes `pinned_weight_index_classifies_each_source_weight_once`'s previously unconditional skip through the same shared helper, so it now fails rather than skips when the gate is on and the pinned index is absent; the existing `panic!` on `read_muse_weight_inventory_from_index` returning `Err` is untouched, since that is a genuine contract violation rather than an availability problem. `docs/environment-variables.md` adds a row for `MLXCEL_REQUIRE_PINNED_CHECKPOINTS` to the existing "Test and CI variables" table, whose `Variable | Purpose` shape carries the value and default semantics inline, stating that only the exact string `1` enables it, plus prose covering that it is test-only, that it belongs on a machine that owns the pinned checkpoint, a single-run invocation example and a persistent-export suggestion, and its role in turning an ambiguous `ok` into positive evidence that the checkpoint was actually read (how acceptance criterion 2 of lablup#1161 was proven). ## Test plan - [x] `cargo check --lib --tests` - [x] `cargo clippy --lib --tests -- -D warnings` - [x] `cargo test --lib vision::encoders::muse_glimmer_fusion` (23 passed, real pinned checkpoint present) - [x] `cargo test --lib loading::vlm::muse_glimmer::` (14 passed, real pinned checkpoint present) - [x] Compiled test binary run from a temp directory with no `models/`, variable unset: both pinned guards skip, each still naming itself - [x] Compiled test binary run from a temp directory with no `models/`, `MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1`: both pinned guards fail, each still naming itself, exit 101 Closes lablup#1177
lablup#1181) ## Summary The file-size and module-split thresholds existed only in the agent-facing `.claude/skills/mlxcel-code-structure/SKILL.md`, with no contributor-facing document referencing them, which is how PR lablup#1173's commit body ended up citing a nonexistent "500-line limit." This PR adds a "File Size and Module Structure" section to `docs/code-guidelines.md` as the single authoritative home for those numbers, and widens the places that describe that document so the guidance is reachable by the normal contributor path. ## Option chosen Option 1 from the issue: the thresholds live in `docs/code-guidelines.md`, and the section states as a rule that anything else citing them, agent-facing tooling under `.claude/skills/` included, should link there rather than restate them. This is preferable because the thresholds are project convention that any human contributor needs, not agent-specific configuration; a document only agents read is the wrong home for a rule contributors are expected to follow. The tradeoff is that the skill file's structural rules are now split across two documents for a reader working through it top to bottom, but the pointer names exactly what moved and where, so that cost is small next to having one number that cannot drift. The rule is written prescriptively rather than as a claim about what any particular consumer currently contains, because no such claim is verifiable from this repository. ## Correction to the brief The brief this implementation started from asserted that `.claude/skills/` is tracked in this repository and instructed treating the skill-file edit as a real committed change. That is incorrect: `.gitignore` line 28 is `/.claude/`, committed at `HEAD`, and `git ls-files .claude/` returns zero files, so the entire `.claude/` directory is untracked here and ships no content with the repository. What was missing was therefore not de-duplication within this repository but a discoverable, contributor-facing home for the numbers, which this PR adds. ## What changed - `docs/code-guidelines.md`: new "File Size and Module Structure" section before "Shared Function Comments", carrying the size table (under 800 fine as a single file, 800 to 1,200 acceptable with a helpers file, 1,200+ extract `<name>_helpers.rs`, 1,500+ consider a directory module, 2,000+ with no helpers file as the anti-pattern), the reason-based exception for `nemotron_h.rs`, `llama4.rs` as an illustration of the 1,200+ row, an explicit note that several files sit well past the thresholds and should be read as debt rather than as precedent, the inline-test-versus-sibling-`_tests.rs` threshold (roughly 100 lines to move, 200 at the latest) with the wiring both forms of which this repository already uses, and the `<name>_helpers.rs` / `<name>_tests.rs` naming convention. - `CONTRIBUTING.md`: widened the intro paragraph and the "Quick links" row describing `docs/code-guidelines.md`, which called it narrowly the shared-function rules, and added a "Code standards" bullet linking straight to the new section. - `docs/README.md`: widened entry 19, which described `code-guidelines.md` as covering only the `// Used by:` convention and the JIT kernel rule, so the docs index names the thresholds too. Every line count quoted in the new section was measured against this branch rather than carried over, because the source this section was assembled from had gone stale: it recorded `nemotron_h.rs` at 2,342 lines (actually 2,914) and `llama4.rs` at 1,499 (actually 1,862), and its "complete model in one file" example, `qwen2.rs`, is a 31-line re-export shim over `llama3`, so `dbrx.rs` (606 lines, a full model through `impl LanguageModel`) replaced it. The section also tells readers the figures are approximate and to check the file rather than trust a number quoted anywhere, that section included. What was deliberately left in the skill file rather than carried into `docs/`: the module-versus-directory trigger, trait-placement rules, the model-registration checklist, subsystem dependency-direction rules, error-handling and config-deserialization patterns, and the rest of the anti-patterns table. That material is about how to structure new code while implementing a model, not something a contributor looks up as a size or split threshold. Out of scope, per the issue: the `0adb53c5` commit body on `main` is not rewritten, the PR lablup#1173 technical report already records the discrepancy correctly, and the thresholds themselves are unchanged, only relocated and surfaced. ## Test plan - [x] Documentation-only change; no code or test files touched, so there is nothing for `cargo test` to exercise. - [x] Every file path and line count cited in the new section verified against this branch with `wc -l`, including that `nemotron_h.rs` has no sibling `_helpers.rs` and `llama4.rs` does. - [x] Confirmed `gemma3n_helpers.rs`, `llama4_helpers.rs` and `qwen3_next_helpers.rs` are the only `*_helpers.rs` files under `src/models/`. - [x] Confirmed `dbrx.rs` is a complete model (`Attention`, `SparseMoeBlock`, `DecoderLayer`, `DbrxModel`, `impl LanguageModel`) rather than a re-export shim. - [x] Confirmed the outlier claim: `gemma4.rs` 6,680 lines and `qwen3_5.rs` 3,451 lines both with no helpers file, `gemma3n.rs` 5,594 lines, and nine files under `src/models/` over 2,000 lines. - [x] Confirmed the `CONTRIBUTING.md` anchor `#file-size-and-module-structure` matches the `## File Size and Module Structure` heading, with no duplicate heading that would shift the slug. - [x] Confirmed the described sibling-test wiring matches this repository: both `#[cfg(test)] mod <name>_tests;` and the `#[path = "..."]` form are in use. Closes lablup#1178
Summary
pinned_post_tower_weight_roots_and_shapes_match_published_contractskipped gracefully only whenmodel.safetensors.index.jsonwas absent. With the index present but anything else it reads missing or corrupt, the shape an interruptedhf downloadormlxcel downloadleaves behind, it unwrapped its way to an opaque panic instead of skipping with a reason. This adds an availability pre-check that names the offending file, while leaving every contract assertion able to fail exactly as before.Implementation choice
The issue offered two options; this is the hybrid the brief recommended. Option 1 alone (a pure existence pre-check) cannot detect a shard that exists but whose header was truncated mid-download, and option 2 alone (converting each unwrap into a skip) reads the index twice, which the issue explicitly asked to avoid. The hybrid gets both:
load_pinned_checkpointparses the index once and hands the parsedweight_mapto the assertion body, andsafetensors_shapereturns aResultso header corruption is covered too.How the correctness boundary is kept
The skip is deliberately narrow, and the split is enforced by construction rather than by convention.
load_pinned_checkpointreturnsErrfor exactly these, andread_checkpoint_filedistinguishes "not present" from "could not be read" so the message names the path either way.assert_eq!calls are untouched and are not wrapped in any skip path.load_pinned_checkpointis structured so it cannot swallow one: aweight_mapthat is absent or non-object yields an empty map (which drives the weight-root assertion to fail, not to skip), and a pinned key absent from an otherwise well-formedweight_mapis skipped over by the shard loop with a comment saying why, so the weight-root assertion is what reports it.config.jsonis parsed as plain JSON only in the pre-check, so a truncated config still skips, while deserializing intoMuseGlimmerConfighappens next tovalidate()in the assertion body, where a schema mismatch panics. A config that parses but does not fit the schema means the pinned directory holds a wrong or drifted model, which is a contract violation rather than an availability problem. This was corrected in review; the first commit deserialized in the pre-check and therefore skipped on schema drift.safetensors_shape, a header that parses but does not describe the key as a shaped tensor panics rather than returningErr, following the issue's "if unsure whether it is missing or wrong, it is wrong" rule.assert_post_tower_contract, which takes an already-validatedPinnedCheckpoint. It holds one skip branch only, for a shard header that cannot be read, which is scoped to availability by construction because those are the only conditions under whichsafetensors_shapereturnsErr. That split is what makes the fourshould_panictests below possible.What changed
src/vision/encoders/muse_glimmer_fusion_pinned_tests.rs(new, 603 lines): the pinned-checkpoint contract check, theload_pinned_checkpointavailability pre-check, aResult-returningsafetensors_shape, and synthetic partial-checkpoint coverage.safetensors_shapebounds the declared header length twice before allocating: against an absoluteMAX_SAFETENSORS_HEADER_BYTESceiling of 256 MiB, mirroring the guard the production reader already applies insrc/lib/mlxcel-core/src/weights.rs:196, and against the file's own size. The absolute ceiling was added in review: the file-relative bound alone permits a declared header as large as the whole file, and the pinned shards are 50 GB and 9.6 GB, so a corrupt eight-byte prefix could have reached an uncatchable allocation abort.src/vision/encoders/muse_glimmer_fusion_tests.rs: the pinned block and its now-unused imports removed, leaving 196 lines of fusion-math tests.src/vision/encoders/muse_glimmer_fusion.rs: attachespinned_testsas a second#[cfg(test)]module, the same patternsrc/vision/mod.rsalready uses. The split separates disk-reading contract checks from fusion math and follows the established#[cfg(test)] #[path]sibling-module convention. Both files sit under the repository's actual 800-line single-file guideline (.claude/skills/mlxcel-code-structure/SKILL.md), at 196 and 603 lines.Test-only change. No production loading path is touched, and
src/loading/vlm_muse_glimmer_tests.rsis untouched as the issue required.Synthetic-checkpoint tests
The real pinned checkpoint is either complete or absent, so the partial cases cannot be exercised against it, and nothing under
models/may be moved or truncated to fake one. All seventeen new tests build throwaway checkpoints intempfile::tempdir()(already a dev-dependency, no new dependency added). The pinned module now holds 18 tests in total, the eighteenth being the pre-existing contract check that moved here.Pre-check names the specific missing or unreadable file:
pinned_precheck_names_an_absent_index,pinned_precheck_names_a_missing_config,pinned_precheck_names_a_missing_shard(index present naming a shard that does not exist),pinned_precheck_names_an_unparseable_index,pinned_precheck_names_an_unparseable_config, andpinned_precheck_accepts_a_complete_synthetic_checkpointas the negative control.Pre-check refuses to swallow contract violations:
pinned_precheck_leaves_a_missing_weight_root_to_the_contract_assertion,pinned_precheck_leaves_an_absent_weight_map_to_the_contract_assertion, andpinned_precheck_leaves_a_schema_mismatched_config_to_the_contract_assertioneach assert the pre-check returnsOk, so the violation reaches the assertion.Contract violations still fail, proven executably rather than by reading the diff. Four
#[should_panic]tests runassert_post_tower_contractover complete-but-wrong synthetic checkpoints:contract_assertion_still_fails_on_a_missing_weight_root,contract_assertion_still_fails_on_an_absent_weight_map,contract_assertion_still_fails_on_a_schema_mismatched_config, andcontract_assertion_still_fails_on_a_wrong_recorded_shape. The last one expects thefailed:prefix thatassert_eq!emits before its custom message, so it can only pass on the shape assertion itself; a bare key name would also match the weight-root assertion and the "must name a shard" panic, letting it pass for the wrong reason.Header handling:
safetensors_shape_reads_a_well_formed_header,safetensors_shape_reports_a_truncated_header,safetensors_shape_reports_an_unparseable_header, andsafetensors_shape_refuses_a_header_over_the_allocation_ceiling, which declaresu64::MAXin a tiny temp file so the test itself allocates nothing large.Optional env var
MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1is implemented. It is read insideskip_or_fail_pinned_checkpointundercrate::test_support::env_lock::env_lock(), held for the duration of the read and dropped before the assertion, because this crate is edition 2024 andsrc/server/muse_glimmer_startup_guard_tests.rsmutates the process environment withunsafe set_varunder that same lock; an unlocked read is the same class of race being fixed elsewhere in this chain. Only the exact value1enables it.It also turned out to be the cleanest way to prove acceptance criterion 2 on this machine: with skips disabled, the pinned test passing is positive evidence that it read the real checkpoint rather than silently skipping.
Follow-up #1177 tracks extending this gate to the loading-side sibling guard, which does not yet honor it, and documenting the variable in
docs/environment-variables.md.Test plan
Results below are for the merged branch tip, all four commits.
cargo test --lib vision::encoders::muse_glimmer_fusionon a machine holding the real pinned checkpoint:23 passed; 0 failed(18 in the pinned module, 5 fusion-math).MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 cargo test --lib vision::encoders::muse_glimmer_fusion:23 passed; 0 failed. Since any skip is a hard failure under this variable, this confirms the full pinned checkpoint still validates the weight-root and shape contract for real (criterion 2).models/: skips withSkipping pinned_post_tower_weight_roots_and_shapes_match_published_contract: models/mlx/muse-glimmer-30b/model.safetensors.index.json is not present(criterion 3, behavior unchanged).MLXCEL_REQUIRE_PINNED_CHECKPOINTS=1: fails withMLXCEL_REQUIRE_PINNED_CHECKPOINTS=1 but the pinned Muse Glimmer checkpoint is not usable: ... is not present(criterion 4).cargo clippy --lib --tests -- -D warnings: clean.cargo check --lib --tests: clean.cargo fmt --check: clean.models/or/home/inureyes/modelswas moved, renamed, deleted, truncated, or written to; both 50 GB and 9.6 GB shards verified present afterwards with their original timestamps.Closes #1161