Skip to content

hf: extract the mapped safetensors reader from hub code - #575

Merged
juliankang4 merged 2 commits into
midagedev:mainfrom
Burntgogi:refactor/issue528-safetensors
Oct 21, 2026
Merged

juliankang4 merged 2 commits into
midagedev:mainfrom
Burntgogi:refactor/issue528-safetensors

Conversation

@Burntgogi

@Burntgogi Burntgogi commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

What

Closes #528. Extract the existing mapped reader into bloomery-safetensors (lib safetensors) and migrate all consumers in HF, decision, model-hf and gpu-gates. No HF re-export or compatibility reader remains.

  • Keep mmap-backed files, borrowed raw tensors, file/header validation, error variants and conversion math unchanged. Public f32_values now checks the complete shape-by-dtype byte count, including overflow, before converting directly constructed Raw spans. The existing f32_values becomes public for HF ModelOpt rather than adding a second conversion or shape allocation.
  • Decision keeps its optional, default-off safetensors feature. It depends on the reader, not HF.
  • GPU-gates takes the reader as an optional direct dependency enabled by hf and clef, not generic GPU features.
  • Move the existing reader tests, sharing the original fixture bytes without copying them. Add the owning bounded gate-safetensors recipe and update path/class mappings and existing docs.
  • Transfer the existing two unsafe blocks and their ratchet budget from HF (2 -> 0) to the reader (2); no new unsafe operations.
  • Keep the existing HF no-gap pin. Add real gate-key regressions for the absent hub edge and present reader edge. No extraction-specific independent lab/fuzz lock changes; the rebase includes main's HIP lab lock repair.

Exercised verification

Review fix f964af2 was rebased onto main 4014464. Freshly rerun: reader debug/release, HF, decision with safetensors, model-hf, warnings-denied clippy, comments and unsafe ratchet. The other entries below retain the earlier extraction evidence.

The new direct-Raw regression failed before the guard and passes afterward: partial F32/BF16/F16 values, too-short/too-long spans and overflow are Format errors; scalar and zero-element spans remain valid. A separate temporary external consumer exercised the public API and observed the three named partial-value refusals plus valid scalar/empty conversion; it was removed.

Linux x86_64, i5-12600K, pinned nightly-2026-08-28, RUSTFLAGS=-C target-cpu=native, isolated target /tmp/bloomery-issue528-target.

Bounded host target Passed Failed Ignored
safetensors lib, debug 12 0 0
safetensors lib, release / new nightly unit 12 0 0
hf lib 78 0 0
decision lib, feature off 61 0 0
decision lib, safetensors on 69 0 0
model-hf lib 21 0 0
model-hf prepare bin 3 0 1
gpu-gates host lib, hf on, no gpu 139 0 3
  • All use the existing tools/gate.sh with --locked. Ignored real-file/oracle gates are not counted as passes.
  • Warnings-denied clippy: new reader, HF, decision and model-hf, all targets with decision's reader feature on: passed.
  • Actual standalone CPU consumer smoke: write and mmap-open real tiny safetensors files; borrowed payload identity and F32 values; two-shard Folder; malformed span and inconsistent index both return named Format refusals. Temporary consumer removed. This is not a model or GPU run.
  • Actual Cargo trees: feature-off decision has neither HF nor reader; feature-on has reader and no HF, including indirect dependencies.
  • Actual why: HF is absent from both decision gate keys; the reader is present in the Clef gate key.
  • New key-boundary regression run against the original main graph fails on the old HF edge and missing reader edge; current recipes self-test passes: 204 gate recipes, 0 failures.
  • recipes.py check: 147 gate rows held to derivation; gate_class.py check: 0 findings; orphan-tests: 3236 tests each owned by a gate/lab recipe.
  • Targeted contributor checks: fmt, arch, comments, levers and loads passed. Unsafe first refused the missing new owner; after transferring the existing budget, contrib-check --tier t0 --only '^check-unsafe$' passed, total1/red0. No ratchet was relaxed.
  • After rebasing onto main's lock repair, full independent HIP lab cargo metadata --locked --offline --format-version 1 passed (without --no-deps). This verifies dependency/lock resolution, not HIP execution.

Explicit limits

No full T0/CI success, Mac runtime, real-model decision CLI, CUDA build, PTX/canon or GPU runtime gate is claimed. Local cargo oxide --version failed because the command is not installed; device-linked crates were not built with plain cargo. Feature metadata checked the GPU-gates dependency off by default and on under hf/clef; that is not GPU typecheck or runtime evidence.

Please run the affected CUDA feature shapes/move proof and owning DSpark/Clef serving/GLM checkpoint gates where their toolchain/assets are available. Local pre-review was unavailable because claude is not installed. GitHub CI/review are separate.

Written with AI assistance.

@github-actions github-actions Bot added documentation Improvements or additions to documentation gpu The card engine: crates/gpu*, crates/app 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 needs-gpu Changes code a card must check, and carries no gate run on a card tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 20, 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 newly public float converter silently accepts truncated tensor bytes.

Must fix

1. Validate Raw before converting its bytes (kind A)

crates/safetensors/src/lib.rs:315 exposes f32_values to callers that can construct Raw directly through its public fields at line 140. Passing Raw { dtype: Dtype::F32, shape: &[1], bytes: &[0, 0, 0] } to f32_values bypasses file validation and returns Ok([]): .as_chunks::<4>().0 drops the partial value. BF16 and F16 do the same with an odd byte count. This violates the no-silent-failure contract.
Validate this boundary before callers depend on successful conversion of malformed tensors.

Insert this guard before Ok(match raw.dtype {:

    let expected = raw.shape.iter().try_fold(raw.dtype.size(), |bytes, &dim| {
        bytes.checked_mul(dim)
    });
    if expected != Some(raw.bytes.len()) {
        return Err(bad(format!(
            "{name}: shape {:?} does not match {} {} bytes",
            raw.shape,
            raw.bytes.len(),
            raw.dtype.name()
        )));
    }

Add a direct Raw regression asserting Error::Format for the example above and partial BF16/F16 values. Removing the guard must make that assertion fail.

Non-blocking

⚠ CUDA move proof is missing: crates/gpu-gates/Cargo.toml:23 changes the reader dependency of CUDA-linked consumers. The PR explicitly omits their CUDA builds and move proof. Attach cargo oxide feature-build results, identical ptx-scan tables or canon-check output, and the affected DSpark/Clef/GLM gate results to close that validation gap.

Checked

Duplicates: 1 newly public function checked; the existing converter is reused and the old reader module is removed. Dryer reported 0 pairs.
Complexity: crapper reports Folder::open at 17; its body moved unchanged, with no added branches.
Silent failure: 5 sites followed; 2 .ok() chains reach named format errors, while 3 conversion arms discard partial values as described in item 1.
Tests: static mutation review shows restoring decision's HF edge or dropping its reader edge makes the new key assertions fail. Existing reader tests miss malformed direct Raw inputs.
Gates: reader assertions moved unchanged; unsafe budgets transferred with dated PINs; no tolerance relaxed.
Escape catalog: no C1–C4 pattern matched the added code.

Notes

Validation was static; no Rust tests or CUDA builds ran during validation.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_clef_serve.rs, crates/gpu-gates/src/bin/shared/dspark_hf.rs and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

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

@Burntgogi

Copy link
Copy Markdown
Contributor Author

Addressed the mandatory Raw boundary request from #575 (review) in f964af2, after rebasing onto main 4014464.

f32_values now checks the complete shape × dtype-size byte count with checked multiplication before conversion. Regression was red before the guard and green afterward (partial F32/BF16/F16, too-short/too-long spans, overflow; valid scalar and zero-element controls). A separate external public-API consumer observed named Format refusals and preserved valid conversions.

Fresh results: reader debug/release 12/12 each; HF 78/78; decision + reader 69/69; model-hf 21/21; warnings-denied clippy for all four host packages, comments, unsafe ratchet and full HIP lab locked/offline metadata passed. Existing extraction matrix and limits remain in the updated PR body.

The requested CUDA feature-shape/PTX/canon/real-gate move proof remains unverified here: cargo oxide is absent and this machine has no NVIDIA seat. No CUDA pass or waiver is claimed. Ready for re-review of the mandatory fix; CUDA evidence still needs the equipped lane.

github-actions[bot]
github-actions Bot previously approved these changes Oct 21, 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.

Since the last review:

Verdict: CLEAN: the new guard closes the malformed-span failure; no must-fix finding remains.

Non-blocking

⚠ CUDA move proof remains missing: crates/gpu-gates/Cargo.toml:23 changes the reader dependency of CUDA-linked consumers. Attach the affected cargo oxide feature-build results, identical ptx-scan tables or canon-check output, and DSpark/Clef/GLM gate results. The PR explicitly reports these checks as unavailable.

Checked

Duplicates: 1 new test checked; it covers direct Raw validation, which existing file-parser tests cannot exercise. Dryer reported 0 pairs. No new duplicate owner requires extraction.
Complexity: crapper flags Folder::open at 17; it is unchanged in this interdiff. f32_values adds one validation branch.
Silent failure: 3 float conversion arms followed; malformed spans and overflow return Error::Format before chunking can discard bytes.
Tests: static mutation review of production line 320 shows that dropping or reversing the guard fails the assertion at line 606. Scalar and empty assertions protect valid boundary inputs.
Gates: no pin, tolerance, test case or lint level was relaxed in the new commit.
Escape catalog: no C1–C4 pattern matched the new commit.

Notes

Reviewed the added interdiff commit; the extraction patch is unchanged. Validation was static; no Rust tests or CUDA builds ran during this review.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_clef_serve.rs, crates/gpu-gates/src/bin/shared/dspark_hf.rs and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

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

Verdict: CLEAN: the import resolutions preserve the reader and tensor-parallel contracts; no new defect was found.

Non-blocking

⚠ CUDA move proof remains missing: crates/gpu-gates/Cargo.toml:23. Attach affected cargo oxide feature-build results, identical ptx-scan tables or canon-check output, and the owning DSpark/Clef/GLM gate results. This verifies the device-linked consumers after the dependency move. The PR reports these checks as unavailable.

Checked

Duplicates: 0 new definitions in the interdiff; dryer reported 0 pairs. The changed imports use the existing reader owner.
Complexity: crapper flags Folder::open at 17; its body is unchanged since the previous review. The interdiff adds no branches.
Silent failure: 0 new sites. The existing Raw guard rejects malformed spans and overflow before conversion.
Tests: the FP8 oracle body and assertions match the base after removing the reader import. Static mutation check: dropping the f32_values guard at line 320 fails the malformed-span assertion at line 606.
Gates: no pins, thresholds or test cases changed in the interdiff.
Escape catalog: no C1–C4 pattern matched.

Notes

Reviewed the changed interdiff hunks; the remaining extraction and validation patches are unchanged. Static comparisons confirmed that GLM's tp_tensors and read_tp match the base, and both consumers directly depend on the reader. No Rust tests, CUDA builds or runtime gates ran during this review.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_clef_serve.rs, crates/gpu-gates/src/bin/shared/dspark_hf.rs and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

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

@juliankang4
juliankang4 merged commit 7f4116a into midagedev:main Oct 21, 2026
6 checks passed
@juliankang4

Copy link
Copy Markdown
Collaborator

@Burntgogi Thanks for the contribution. The review is done, so I'm merging this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation gpu The card engine: crates/gpu*, crates/app 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 needs-gpu Changes code a card must check, and carries no gate run on a card tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

hf: move safetensors into its own crate so decision stops depending on hf

2 participants