@@ -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+
327414def 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