Skip to content

Commit 563f178

Browse files
justinchubyCopilot
andcommitted
Address review: document mixed-quant residual, strengthen bounded-memory test
Independent review (PR #581) raised two minor findings: - Mixed-quant continuation-shard swap: continuation shards carry no identity metadata, so a same-model IQ1_S/IQ1_M swap evades metadata-only validation. Document the residual precisely on _IDENTITY_KEYS / _validate_identity / GgufShardSet and add a regression test proving the manifest guard (expected_sizes/expected_sha256, produced by preflight) fails closed on a swapped continuation shard — the byte-exact guard the task requires when manifest data exists. - Bounded-memory test used F32 tensors, which get_tensor returns as memmap views that tracemalloc cannot see (vacuous assertion). Switch the fixture to native Q8_0 blocks so each get_tensor dequantizes into a real float32 heap array; the peak-vs-single-tensor bound is now meaningful. Co-authored-by: Copilot <[email protected]>
1 parent 77aa673 commit 563f178

2 files changed

Lines changed: 128 additions & 9 deletions

File tree

‎src/mobius/integrations/gguf/_shard_set.py‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,17 @@
7777
# them. A divergence means the shards came from different exports (mixed
7878
# revision) or different quantization presets (mixed quant), which would build
7979
# a corrupt model if silently stitched together.
80+
#
81+
# NOTE ON THE RESIDUAL MIXED-QUANT GAP: in real llama.cpp/Unsloth split sets
82+
# these keys are carried ONLY by the primary shard (``split.no == 0``);
83+
# continuation shards store just ``split.*`` plus tensor data. Identity
84+
# validation therefore cannot, on metadata alone, distinguish a continuation
85+
# shard of ``…-IQ1_S`` from the same-index continuation shard of ``…-IQ1_M``
86+
# of the same model (identical tensor names, identical ``split.tensors.count``,
87+
# per-shard-consistent offsets). The byte-exact guard for that case is the
88+
# download manifest: pass ``expected_sha256`` / ``expected_sizes`` (both are
89+
# produced by :mod:`._preflight`), which are verified per shard in
90+
# :func:`_build_shard_infos` and fail closed on any mismatch.
8091
_IDENTITY_KEYS = (
8192
"general.architecture",
8293
"general.name",
@@ -280,7 +291,11 @@ class GgufShardSet:
280291
set is expensive; the preflight path opts in.
281292
expected_sha256: Optional ``{filename: sha256}`` from a download manifest
282293
(e.g. Hugging Face LFS metadata). When present each listed shard is
283-
verified and a mismatch fails closed.
294+
verified and a mismatch fails closed. This is the ONLY byte-exact
295+
guard against a same-model mixed-quant continuation-shard swap
296+
(``IQ1_S`` primary + ``IQ1_M`` continuation), whose continuation
297+
shards carry no identity metadata to compare — supply it (from
298+
:mod:`._preflight`) whenever manifest data is available.
284299
expected_sizes: Optional ``{filename: size_bytes}`` verified the same way.
285300
"""
286301

@@ -573,7 +588,15 @@ def _validate_shard_set(infos: list[ShardInfo], shards: list[GGUFModel]) -> None
573588

574589

575590
def _validate_identity(infos: list[ShardInfo], shards: list[GGUFModel]) -> None:
576-
"""Every shard that declares an identity key must agree with the others."""
591+
"""Every shard that declares an identity key must agree with the others.
592+
593+
This catches the common mixed-revision / mixed-quant cases (a shard whose
594+
primary declares a different architecture, name, quantization version, or
595+
tokenizer/template). It CANNOT catch a same-model ``IQ1_S`` vs ``IQ1_M``
596+
continuation-shard swap, because continuation shards carry no identity
597+
keys; supply a manifest (``expected_sha256`` / ``expected_sizes``) for that
598+
case. See the note on :data:`_IDENTITY_KEYS`.
599+
"""
577600
for key in _IDENTITY_KEYS:
578601
seen: dict[Any, str] = {}
579602
for info, shard in zip(infos, shards):

‎src/mobius/integrations/gguf/_shard_set_test.py‎

Lines changed: 103 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,52 @@ def test_checksum_mismatch_rejected(tmp_path):
274274
open_gguf_model(shards[0], verify_checksums=True, expected_sha256=bad)
275275

276276

277+
def test_manifest_rejects_swapped_continuation_shard(tmp_path):
278+
"""A same-model mixed-quant continuation-shard swap is caught by the manifest.
279+
280+
Continuation shards carry no identity metadata, so without a manifest the
281+
swap passes structural validation (the documented residual gap in
282+
``_IDENTITY_KEYS``). Supplying ``expected_sizes`` / ``expected_sha256`` (as
283+
:mod:`._preflight` produces from HF LFS metadata) fails closed — this is the
284+
byte-exact guard the task requires "when manifest data exists".
285+
"""
286+
# A trusted set and a differently-quantized variant of the "same" model
287+
# whose continuation shards differ in byte length and content.
288+
good = _write_sharded_gguf(
289+
tmp_path / "good", stem="tiny", split_max_tensors=3, cols=16, seed=1
290+
)
291+
other = _write_sharded_gguf(
292+
tmp_path / "other", stem="tiny", split_max_tensors=3, cols=24, seed=2
293+
)
294+
295+
manifest = open_gguf_model(good[0], verify_checksums=True).manifest
296+
expected_sizes = {s.path.name: s.size_bytes for s in manifest.shards}
297+
expected_sha256 = {s.path.name: s.sha256 for s in manifest.shards}
298+
299+
# Assemble a working set: trusted primary + a continuation shard swapped in
300+
# from the other (mixed-quant) export.
301+
work = tmp_path / "work"
302+
work.mkdir()
303+
for p in good:
304+
(work / p.name).write_bytes(p.read_bytes())
305+
victim = other[1] # continuation shard, same filename, different bytes/size
306+
(work / victim.name).write_bytes(victim.read_bytes())
307+
work_shards = sorted(work.glob("tiny-*.gguf"))
308+
309+
# Documented residual: metadata alone cannot detect the swap, so this must
310+
# NOT raise (continuation shards carry no identity keys to compare).
311+
open_gguf_model(work_shards[0])
312+
313+
# With the manifest it fails closed (the size guard fires before hashing).
314+
with pytest.raises(GgufShardError, match=r"(?i)size|sha|checksum"):
315+
open_gguf_model(
316+
work_shards[0],
317+
verify_checksums=True,
318+
expected_sha256=expected_sha256,
319+
expected_sizes=expected_sizes,
320+
)
321+
322+
277323
# --------------------------------------------------------------------------- #
278324
# Manifest / determinism
279325
# --------------------------------------------------------------------------- #
@@ -324,25 +370,75 @@ def test_offsets_within_file_and_aligned(tmp_path):
324370
# --------------------------------------------------------------------------- #
325371

326372

373+
def _write_q8_sharded_gguf(
374+
directory: Path,
375+
*,
376+
stem: str = "q8",
377+
num_layers: int = 3,
378+
split_max_tensors: int = 3,
379+
rows: int = 512,
380+
cols: int = 512,
381+
) -> list[Path]:
382+
"""Write a split set whose tensors are native ``Q8_0`` blocks.
383+
384+
Unlike F32 tensors (which ``get_tensor`` returns as a memmap-backed *view*),
385+
a quantized tensor is dequantized into a fresh float32 heap array, so
386+
``tracemalloc`` actually observes the per-tensor payload and the
387+
bounded-memory assertion is meaningful. ``cols`` must be a multiple of the
388+
32-element ``Q8_0`` block; each block is 34 bytes (fp16 scale + 32 int8).
389+
"""
390+
from gguf import GGMLQuantizationType, GGUFWriter
391+
392+
assert cols % 32 == 0, "Q8_0 requires the last dim to be a multiple of 32"
393+
directory.mkdir(parents=True, exist_ok=True)
394+
block_bytes = cols // 32 * 34
395+
writer = GGUFWriter(str(directory / stem), "llama", split_max_tensors=split_max_tensors)
396+
writer.add_context_length(128)
397+
writer.add_embedding_length(cols)
398+
writer.add_block_count(num_layers)
399+
writer.add_head_count(4)
400+
writer.add_head_count_kv(2)
401+
writer.add_vocab_size(32)
402+
403+
rng = np.random.default_rng(3)
404+
for name in _tensor_names(num_layers):
405+
raw = rng.integers(0, 256, size=(rows, block_bytes), dtype=np.uint8)
406+
writer.add_tensor(name, raw, raw_dtype=GGMLQuantizationType.Q8_0)
407+
writer.write_header_to_file()
408+
writer.write_kv_data_to_file()
409+
writer.write_tensors_to_file()
410+
writer.close()
411+
return sorted(directory.glob(f"{stem}-*.gguf"))
412+
413+
327414
def test_bounded_memory_random_access(tmp_path):
328-
# Larger tensors so the payload dominates over Python object overhead.
329-
shards = _write_sharded_gguf(tmp_path, split_max_tensors=3, rows=512, cols=512)
415+
# Native Q8_0 blocks so each get_tensor() dequantizes into a real float32
416+
# heap array (a memmap *view* would hide the payload from tracemalloc and
417+
# make this assertion vacuous).
418+
rows = cols = 512
419+
shards = _write_q8_sharded_gguf(tmp_path, split_max_tensors=3, rows=rows, cols=cols)
330420
model = open_gguf_model(shards[0])
331-
one_tensor_bytes = 512 * 512 * 4
421+
assert model.num_tensors == len(_tensor_names(3))
422+
one_tensor_bytes = rows * cols * 4 # dequantized float32 payload
332423

333424
tracemalloc.start()
334425
try:
335426
base = tracemalloc.get_traced_memory()[0]
336-
for name in model.tensor_names:
337-
block = model.get_tensor(name)
338-
del block
427+
# Random Q8_0 bytes can encode non-finite fp16 scales; we only measure
428+
# memory here, so ignore the resulting numpy dequant warnings.
429+
with np.errstate(invalid="ignore", over="ignore"):
430+
for name in model.tensor_names:
431+
block = model.get_tensor(name)
432+
# Force materialisation of the dequantized payload.
433+
assert block.nbytes == one_tensor_bytes
434+
del block
339435
peak = tracemalloc.get_traced_memory()[1]
340436
finally:
341437
tracemalloc.stop()
342438

343439
# Peak stays within a small multiple of a single tensor — we never
344440
# materialise the whole (multi-tensor) checkpoint at once.
345-
assert peak - base < 6 * one_tensor_bytes
441+
assert peak - base < 3 * one_tensor_bytes
346442

347443

348444
# --------------------------------------------------------------------------- #

0 commit comments

Comments
 (0)