Repository navigation
fix: refuse what the architecture readers cannot read and pin tensor data to each shard - #76
Conversation
|
✅ OpenCodeReview: Review complete: 0 finding(s) across 6 selected item(s). |
There was a problem hiding this comment.
🟡 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)
|
Review round 1, outcomes:
Verification on the updated head: the two new regressions fail on the previous code and pass now; |
506c1a5 to
aeb4e66
Compare
…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>
aeb4e66 to
3262cf0
Compare

What was wrong
The parser accepted some malformed files and then misbehaved when a caller read them:
Mistyped architecture keys panicked the readers.
validateMetadatatype-checked thegeneral.*,tokenizer.ggml.*and a fewclip.*keys, but not the per-architecture (<arch>.*), mostclip.*, or theadapter.*keys. The architecture readers read those through strict accessors that panic on a type mismatch, so a file with, for example,llama.pooling_typestored as auint64parsed successfully and then panickedArchitecture()and both estimators. The CLI's default--jsonpath callsArchitecture()before anything else, so the process died with exit code 2.Empty per-layer arrays hit an unguarded index.
attention.head_countandattention.sliding_windowdeclared as an empty array reachedValuesNumeric(...)[0]in the transformer reader. The neighbouringhead_count_kvbranch already had a length check.The tensor-data offset could lie past the file, and the model size wrapped.
readShardapplied the alignment padding to every shard, including one with no tensors, andparseGGUFFileran its tensor-data consistency check only when the offset was within the file, so an offset past the end skipped the check.ModelSizethen converted a negative difference touint64. 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 indexedDimensions[1]of several projector tensors without checking the rank. The projector estimate also divided byclip.vision.patch_size, which was not range-checked.What changed
validateMetadatanow 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.feed_forward_length,attention.head_count,attention.head_count_kv,expert_used_count) must have exactlyblock_countelements, as llama.cpp'sget_key_or_arrrequires. An emptyattention.sliding_windowarray reads as an absent key.expert_used_countmay be an array; the reader takes the first element as it does for the other per-layer keys.clip.vision.patch_sizemust 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 unusedne[]entries, and every rank-dependent read in the diffuser reader and the projector estimate goes through it.readShardpads only a shard that holds tensors (asgguf.cppdoes), refuses ageneral.alignmentthat is not a power of 2 (asgguf.cppdoes), 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. Thefiles.count == 1gate and theuint64clamp are gone because the difference is never negative.v2tov3so an entry written before these checks is not served.FuzzParseGGUFFilenow 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 fuzzruns it forFUZZTIME(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 withgo/astand 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, andTestReaderKeyExemptionsHoldproves every pin: arefusedkey fails the parse on a mistyped value, aguardedkey 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 directGet, a new reader in another file, or a range over the metadata all fail the test.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
paddingandsplitPaddingsbecome 0,tensorDataStartOffsetandsplitTensorDataStartOffsetsbecome the file size, andmodelSizeandsplitModelSizesbecome 0 instead of a value near 2^64. In the CLI's--jsonoutput,metadata.size,estimate.items.*.ram.umaandestimate.items.*.ram.nonumafollow.general.alignmentthat is not a power of 2, aclip.vision.patch_sizeoutside 1 to 65535 on a vision projector, and a per-layer array whose length differs fromblock_countare refused, as llama.cpp refuses them.v2are not read.Verification
--rawand default--jsonpaths: 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 incmd/gguf-parser;golangci-lint runis clean in both.FuzzParseGGUFFileran 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.Known limits
expert_used_countand oneattention.head_countvalue for every layer where llama.cpp uses per-layer values. This predates the change; no local model declares either as an array.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_lengthdeclared as an array has no length rule; llama.cpp reads it as one scalar and no reader panics on it.validateMetadataorreadShardin another file, a stale exemption, and a half-removed read shielded by a deadIndex-list entry all pass it. Each is a refactoring shape, not a file shape.