Skip to content

fix: refuse what the architecture readers cannot read and pin tensor data to each shard - #76

Merged
thxCode merged 2 commits into
mainfrom
fix/metadata-key-types-and-tensor-offset
Nov 28, 2026
Merged

thxCode merged 2 commits into
mainfrom
fix/metadata-key-types-and-tensor-offset

Conversation

@thxCode

@thxCode thxCode commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

What was wrong

The parser accepted some malformed files and then misbehaved when a caller read them:

  • Mistyped architecture keys panicked the readers. validateMetadata type-checked the general.*, tokenizer.ggml.* and a few clip.* keys, but not the per-architecture (<arch>.*), most clip.*, or the adapter.* keys. The architecture readers read those through strict accessors that panic on a type mismatch, so a file with, for example, llama.pooling_type stored as a uint64 parsed successfully and then panicked Architecture() and both estimators. The CLI's default --json path calls Architecture() before anything else, so the process died with exit code 2.

  • Empty per-layer arrays hit an unguarded index. attention.head_count and attention.sliding_window declared as an empty array reached ValuesNumeric(...)[0] in the transformer reader. The neighbouring head_count_kv branch already had a length check.

  • The tensor-data offset could lie past the file, and the model size wrapped. readShard applied the alignment padding to every shard, including one with no tensors, and parseGGUFFile ran its tensor-data consistency check only when the offset was within the file, so an offset past the end skipped the check. ModelSize then converted a negative difference to uint64. llama.cpp's own vocabulary-only GGUF files (0 tensors, no padding bytes) reported a model size near 2^64. For split files the check did not run at all.

  • Tensor rank reads in the diffuser reader and the projector estimate. The diffuser reader indexed Dimensions[2] of the in-paint feature tensor and the projector estimate indexed Dimensions[1] of several projector tensors without checking the rank. The projector estimate also divided by clip.vision.patch_size, which was not range-checked.

What changed

  • validateMetadata now checks every key the architecture readers consume against the type its accessor reads. The keys live in three tables (_GGUFTransformerKeyTypeSpecs, _GGUFClipKeyTypeSpecs, _GGUFAdapterKeyTypeSpecs) whose names are shared with the readers through package-level constants, so a mistyped key is a parse error, not a panic. Keys are checked in sorted order so the reported fault is stable.
  • A per-layer array (feed_forward_length, attention.head_count, attention.head_count_kv, expert_used_count) must have exactly block_count elements, as llama.cpp's get_key_or_arr requires. An empty attention.sliding_window array reads as an absent key. expert_used_count may be an array; the reader takes the first element as it does for the other per-layer keys.
  • clip.vision.patch_size must be 1 to 65535 on a projector with a vision encoder, as llama.cpp requires, since the estimate divides by it.
  • GGUFTensorInfo.dim(i) returns 1 past a tensor's rank, the value ggml gives unused ne[] entries, and every rank-dependent read in the diffuser reader and the projector estimate goes through it.
  • readShard pads only a shard that holds tensors (as gguf.cpp does), refuses a general.alignment that is not a power of 2 (as gguf.cpp does), refuses a data offset past the end of a shard that holds tensors, and checks each shard's tensors against that shard's own size. The files.count == 1 gate and the uint64 clamp are gone because the difference is never negative.
  • The parse cache moves from v2 to v3 so an entry written before these checks is not served.
  • FuzzParseGGUFFile now parses through the in-memory seam the remote readers use, calls every reader on what the parse accepts, checks that the sizes and the offset stay within the file, and is seeded with the shapes above. make fuzz runs it for FUZZTIME (60s default).

Tests

  • file_validation_test.go: per-key type checks driven from the tables, per-layer array lengths, patch size, rank reads in the diffuser reader and projector estimate, the tensor-data offset rules, and per-shard sizes for a split model.
  • file_architecture_keys_test.go: parses every non-generated source file with go/ast and requires every metadata key a reader looks up to be covered by a table or by an exemption in _GGUFReaderKeyExemptions. The exemption list carries the pin for each entry, and TestReaderKeyExemptionsHold proves every pin: a refused key fails the parse on a mistyped value, a guarded key parses and every reader runs without a panic. A table entry no reader reads fails as over-rejection. Verified by mutation: deleting a table entry, adding a read through a new constant, a literal, a helper, an alias of the metadata, a second map, a direct Get, a new reader in another file, or a range over the metadata all fail the test.
  • Every new test fails on the base commit and passes here.
  • file_decision_test.go's fixture wrote tensor infos without their data and only parsed because of the skipped check; it now writes the data.

Behaviour changes a consumer can notice

  • Files that used to parse and then panic are now refused with an error naming the key or the shard.
  • For a file without tensors, padding and splitPaddings become 0, tensorDataStartOffset and splitTensorDataStartOffsets become the file size, and modelSize and splitModelSizes become 0 instead of a value near 2^64. In the CLI's --json output, metadata.size, estimate.items.*.ram.uma and estimate.items.*.ram.nonuma follow.
  • A general.alignment that is not a power of 2, a clip.vision.patch_size outside 1 to 65535 on a vision projector, and a per-layer array whose length differs from block_count are refused, as llama.cpp refuses them.
  • Cache entries under v2 are not read.

Verification

  • Twelve local models, old and new CLI, --raw and default --json paths: the six that hold tensors (two mmproj projectors, an embedding model, a draft model, two 16 GB chat models) are byte-identical; the six vocabulary-only files differ only in the size fields above. Both projectors are identical through --mmproj.
  • go test -race -cover ./... passes in the root module (coverage 67.0%); go test ./... passes in cmd/gguf-parser; golangci-lint run is clean in both.
  • FuzzParseGGUFFile ran for 90s to 180s at a time (up to 48M executions) with no finding on this change; its seeds fail immediately on the base commit.
  • Four rounds of independent read-only review against frozen diffs; every parser defect reachable from an input file was closed and measured.

Known limits

  • The estimate uses one expert_used_count and one attention.head_count value for every layer where llama.cpp uses per-layer values. This predates the change; no local model declares either as an array.
  • llama.cpp checks each tensor's declared offset against the running total and per-tensor padding (gguf.cpp, the data-section loop). This parser sums tensor bytes once and does not check per-tensor offsets. That is a separate change, since replicating the alignment arithmetic carries a risk of refusing models llama.cpp loads.
  • clip.vision.feed_forward_length declared as an array has no length rule; llama.cpp reads it as one scalar and no reader panics on it.
  • The fuzz seam parses a single shard, so the split-file path runs only under the unit tests.
  • Cache entries under an older version stay on disk until the cache directory is cleared.
  • The source-reading test has limits that no input file reaches: a lookup returned by a function, a method on a wrapper type, a closure parameter, an impostor method named validateMetadata or readShard in another file, a stale exemption, and a half-removed read shielded by a dead Index-list entry all pass it. Each is a refactoring shape, not a file shape.

Copilot AI adaptive review requested due to automatic review settings November 28, 2026 06:57
@gpustack-code-review

gpustack-code-review Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

✅ OpenCodeReview: Review complete: 0 finding(s) across 6 selected item(s).

Comment thread file.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Skip-large-metadata reads understate expert activation memory, and later shards incorrectly inherit the first shard’s alignment, causing valid files to be rejected.

2 open issues
What changed in this PR

This PR hardens GGUF parsing so malformed metadata is rejected before reaching architecture readers and estimators, and tensor-data sizes are checked against each shard.

Changes:

  • Adds metadata type and range validation, per-layer array checks, and safe tensor-dimension reads.
  • Validates shard-local tensor-data bounds, corrects vocabulary-only size accounting, and invalidates older parse caches.
  • Expands regression coverage and adds an in-memory fuzz target with a documented Makefile command.
File Description
Makefile Adds configurable make fuzz target.
file.go Validates metadata and per-shard data bounds; adds safe dimension access.
file_validation_test.go Tests metadata, tensor ranks, shard sizes, and cache invalidation.
file_test.go Expands fuzz seeds and exercises readers after parsing.
file_estimate__llamacpp.go Safely reads lower-rank projector tensor dimensions.
file_decision_test.go Supplies tensor data required by stricter validation.
file_architecture.go Defines metadata type tables and guards array and dimension reads.
file_architecture_keys_test.go Checks reader-key validation coverage and exemptions.
cache.go Advances the parse-cache namespace to exclude older entries.
AGENTS.md Documents fuzzing and regression-input handling.

Review effort: Balanced (adaptive)

Comment thread file.go Resolved
Comment thread file_architecture.go Resolved
@thxCode

thxCode commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator Author

Review round 1, outcomes:

Item Where Outcome
Per-shard tensor-data bounds have no test file.go (thread) Not changed. The tests are in file_validation_test.go (TestParseGGUFFile_TensorDataOffset, TestParseGGUFFile_SplitShards); each fails on the base commit. Details in the thread.
Later shards inherit the first shard's alignment file.go (thread) Fixed. readShard reads general.alignment from each shard's own metadata. Regression TestParseGGUFFile_SplitShards "each shard pads by its own alignment".
Array-valued expert_used_count lost under SkipLargeMetadata() file_architecture.go (thread) Fixed. The key joins the retained per-layer suffix list in ReadArray. Regression TestParseGGUFFile_PerLayerArraySkipLargeMetadata.
FUZZTIME declared next to package Makefile (summary) Fixed. Moved next to the fuzz target.

Verification on the updated head: the two new regressions fail on the previous code and pass now; golangci-lint run is clean in both modules; make generate changes nothing; FuzzParseGGUFFile runs clean; the local models compare as before against the base build (the one tensor-bearing model on disk is byte-identical on both CLI paths, the six vocabulary-only files differ only in the size fields listed in the description).

@thxCode
thxCode force-pushed the fix/metadata-key-types-and-tensor-offset branch from 506c1a5 to aeb4e66 Compare November 28, 2026 09:19
…data to each shard

The parser accepted some files and then panicked or reported a wrapped
size when a caller read them:

- Per-architecture, clip and adapter keys read through strict accessors
  were not type-checked at parse time, so a mistyped key panicked
  Architecture() and the estimators.
- An empty attention.head_count or attention.sliding_window array hit an
  unguarded [0] in the transformer reader.
- The padding was applied to a shard without tensors, and the tensor-data
  consistency check skipped an offset past the end of the file, so the
  model size wrapped to about 2^64. llama.cpp's own vocabulary-only files
  carry no padding and hit this.
- The diffuser reader and the projector estimate indexed a tensor past
  its rank, and the projector estimate divided by a zero patch size.

validateMetadata now checks every key the readers consume against the
type its accessor reads, from tables that share their key names with the
readers, holds a per-layer array to the layer count as llama.cpp's
get_key_or_arr does, and refuses the patch size llama.cpp refuses. A
reader that indexes a tensor past its rank gets ggml's value of 1. An
empty attention.sliding_window array reads as absent.

readShard pads only a shard that holds tensors, as llama.cpp does, refuses
a non-power-of-2 general.alignment, as llama.cpp does, refuses a data
offset past the end of a shard that holds tensors, and checks each
shard's tensors against its own size. The model size no longer converts a
negative difference to uint64. The parse cache moves to v3 so an entry
written before these checks is not served.

A test reads the readers' source and requires every key they look up to
be covered, so a key added to a reader without a table entry fails there
instead of panicking on a mistyped file. The decision-test fixture wrote
tensor infos without their data and only parsed because of the skipped
check; it now writes the data.

Signed-off-by: thxCode <thxcode0824@gmail.com>
The fuzz target stopped at ParseGGUFFile, so it could not see a panic in
Architecture() or the estimators on a file the parse accepted, and its
seeds were four magic bytes. It now parses through the in-memory seam
the remote readers use, calls every reader a caller can reach, and checks
that the sizes and the tensor data offset stay within the file. The seeds
are the shapes that reached a strict accessor, an unguarded index or a
division by zero before the readers were validated. make fuzz runs the
target for FUZZTIME, 60s by default.

Signed-off-by: thxCode <thxcode0824@gmail.com>
@thxCode
thxCode force-pushed the fix/metadata-key-types-and-tensor-offset branch from aeb4e66 to 3262cf0 Compare November 28, 2026 10:15
@thxCode
thxCode merged commit d46ef98 into main Nov 28, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants