Skip to content

readers: refuse duplicate checkpoint keys and overlapping GGUF tensor ranges - #977

Merged
juliankang4 merged 3 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-sa-q7b-reader-ambiguity
Oct 29, 2026
Merged

juliankang4 merged 3 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-sa-q7b-reader-ambiguity

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

중복된 체크포인트 키와 서로 겹치는 GGUF tensor 범위를 로드 시점에 오류로 거부하도록 고쳤습니다.

What and why

The safetensors header and index readers let a repeated JSON key overwrite the earlier one, and the GGUF reader accepted a repeated metadata key, a repeated tensor name, or two tensors whose data ranges overlap. A file with such an ambiguity loaded with whichever entry came last, so the loaded weights depended on declaration order.

The safetensors header and model.safetensors.index.json objects are now read with a duplicate-key check shared by both entry points. The GGUF header parser refuses repeated metadata keys and tensor names, and the strict reader refuses overlapping tensor ranges. Each error names the key or the two tensors involved. Adjacent and separated ranges, and tensor order, load as before. No compute path changes.

Release notes: Fixed: duplicate keys in safetensors headers and indexes, and duplicate keys or overlapping tensor ranges in GGUF files, are refused at load instead of resolving by declaration order.

Code shape

  • No second copy. Logic two models (or two call sites) share has one common owner; I lifted it there instead of
    copying it (AGENTS.md "Common code first", docs/rust-quality.md R14). Where I found an existing copy, I
    named it below.
  • Model code holds only architecture facts. A model's own files carry only what its architecture forces
    (tensor shapes, the attention kind, the quant). A common owner gained no per-model branch, flag or trait method.
  • Dead code is gone. Nothing I made unused is left behind (functions, flags, gate clauses, docs).
  • No silent failure. Undefined input is a named error or panic, never a defined-looking output.
  • Comments state what is true now. No dates, issue numbers or how a bug was found (tools/check-comments.sh).
  • No relaxed gate. No band, tolerance or lint moved to make a check pass; a re-pin carries PIN(YYYY-MM-DD):
    and its reason.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

Duplication found or removed (path:line), or "none": none.

What I ran

Before the fix, on a build with the new tests and the old readers (RTX 5090 machine, CPU run):

cargo test -p bloomery-gguf --lib overlapping_tensor_ranges_are_refused -- --nocapture
cargo test -p bloomery-gguf -p bloomery-safetensors --lib duplicate_ -- --nocapture
overlapping tensor data must be refused in either declaration order
test split_tests::overlapping_tensor_ranges_are_refused ... FAILED
metadata key uniqueness must not depend on declaration order
test split_tests::duplicate_header_keys_are_refused ... FAILED
both declaration orders must refuse the repeated tensor name
test tests::duplicate_header_keys_are_refused ... FAILED
test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured; 12 filtered out

After the fix:

bash tools/gate.sh -p bloomery-gguf --lib -- --nocapture
bash tools/gate.sh -p bloomery-safetensors --lib -- --nocapture
test result: ok. 69 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
test result: ok. 14 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

The new tests cover duplicates in both declaration orders, nested JSON keys, index entries and overlapping ranges, and check that adjacent and separated GGUF ranges still load.

Real files on the RTX 5090 machine, with the release bloomery-serve-qwen38 and prepare built from the tested tree. The GGUF is Qwen3.8-Flash-Next-UD-Q4_K_XL and the checkpoint folder is Qwen3.8-Flash-Next-NVFP4.

BLOOMERY_REF_MODEL="$GGUF" BLOOMERY_DRAFT=off BLOOMERY_BOX_CARD=local bash tools/gpu-gate.sh bloomery-serve-qwen38 --place a --ctx-size 64 --plan
target/release/prepare "$HF" --plan
BLOOMERY_REF_MODEL="$GGUF" BLOOMERY_DRAFT=off BLOOMERY_BOX_CARD=local bash tools/gpu-gate.sh bloomery-serve-qwen38 --place a --ctx-size 64 --host 127.0.0.1 --port 36297
curl -s http://127.0.0.1:36297/completion -d '{"prompt":"The capital of France is","n_predict":1,"temperature":0,"cache_prompt":false}'
gpu-gate.sh: bloomery-serve-qwen38 ran 16 s (exit 0)
READER-PLAN-PASS GGUF .../Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf
prepare: plan qwen4exp: 1369 tensors, 129074335236 bytes; 1901 folder tensors skipped
READER-PLAN-PASS safetensors .../fc694b54fb0174e0913e6adf86691ef85a4ead47
{"schema":"bloomery.event/1","event":"ready","url":"http://127.0.0.1:36297","model":"Qwen3.8 Flash Next","ctx":64,"slots":1,"place":"a"}
READER-LOAD-PASS GGUF {"content": " Paris", ... "tokens_predicted": 1, "tokens_evaluated": 5, ...}

Hardware (if the change is for a machine)

Card Driver
NVIDIA GeForce RTX 5090, 32607 MiB 595.99.02

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 29, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: MUST_FIX: The shared Python GGUF reader accepts duplicate tensor names, making the type check depend on declaration order.

Must fix

1. Refuse duplicate tensor names in the shared Python reader (kind A)

tools/ref/gguf-ranges.py:174 reads repeated names without rejecting them. A clef header declaring token_embd.weight as F32 and then Q8_0 passes through read_header to tools/hf-arch-check.py:625, where Q8_0 overwrites F32 and check_row reports types=ok. Reversing the declarations causes refusal. This is a proven sibling of the duplicate-name defect this PR fixes in Rust.

Fixing the shared parser now avoids separate fixes in its callers. Replace its tensor-info loop with:

        tensors = []
        names = set()
        for _ in range(n_tensors):
            name = string().decode("utf-8", "replace")
            if name in names:
                raise Refusal(65, f"{path}: duplicate tensor name {name!r}")
            names.add(name)
            nd = u32()
            dims = [u64() for _ in range(nd)]
            tensors.append((name, u32(), dims, u64()))

Extend the existing reader self-test with both declaration orders and a unique-name case. Removing this guard must make the duplicate assertions fail.

Checked

  • Diagnostics report 0 dryer pairs and parse_header complexity 22 → 24.
  • In-memory probes through check_row reproduced the declaration-order failure. The proposed guard refused both orders and accepted a unique Q8_0 embedding.
  • Gates: no pins relaxed; the PR supplies FAIL-first output.
  • Escape catalog: no C1–C4 matches.

Notes

Rust tests were not executed during validation.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the last review: the duplicate tensor-name finding is fixed at tools/ref/gguf-ranges.py:176. Both declaration orders are refused.

Verdict: CLEAN: The earlier failure is closed, and no must-fix defect remains in the reviewed interdiff.

Checked

  • Duplicates: 0 new functions, types or constants in the interdiff; dryer reports 0 candidate pairs. The shared header parser remains the owner for its callers.
  • Complexity: crapper reports parse_header at 22 → 24 from two duplicate checks. This function is unchanged in the interdiff.
  • Silent failure: 3 duplicate-refusal paths followed to consumers. Same-file names, split-set names and the architecture type check return named refusals.
  • Tests: 6 new assertions pass in memory. Deleting the header guard above fails 2 assertions. Deleting tools/ref/gguf-ranges.py:234 fails the split assertion. Deleting tools/hf-arch-check.py:626 fails both type-check assertions. Unique names across shards load; equal-type duplicates are refused.
  • Gates: no pins relaxed. The dropped fixture-test commit's changes are retained in the added commit.
  • Escape catalog: no C1–C4 matches in the revised hunks.
  • Performance: the revised code runs in tools and header loading; no inference hot path changes.

Notes

Rust tests and complete tool self-tests were not run. Validation used isolated in-memory probes. GPU evidence is incomplete: the PR lacks the required nvidia-smi line, tested commit hashes and just gate-* output.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit 22c12d7 into midagedev:main Oct 29, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant