okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
538acd098
main
1"""A malformed GGUF header is refused with a ValueError that names the file, never a KeyError, OverflowError 2or struct.error (#1919). Tensor-size support and setup compatibility policy are unchanged. 3Over minimal GGUF v3 files written here (no download, no model, no GPU). 4 5python -m unittest tools.test_gguf_reader_malformed 6""" 7from __future__import annotations 8 9import contextlib 10import io 11import struct 12import sys 13import tempfile 14import unittest 15from unittest import mock 16from pathlib import Path 17 18ROOT = Path (__file__ ).resolve ().parents [1 ] 19sys .path .insert (0 ,str (ROOT / "tools" )) 20sys .path .insert (0 ,str (ROOT )) 21import setup as S # noqa: E402 22from gguf_reader import GGUFFile # noqa: E402 23 24 25class Stop (Exception ): 26"""setup.fail(), caught instead of exiting.""" 27 28 29def gstr (s :bytes )-> bytes : 30return struct .pack ("<Q" ,len (s ))+ s 31 32 33def header (n_tensors :int ,kv :bytes = b"" ,n_kv :int = 0 )-> bytes : 34return struct .pack ("<IIQQ" ,0x46554747 ,3 ,n_tensors ,n_kv )+ kv 35 36 37def tensor (name :bytes ,n :int ,type_id :int ,offset :int )-> bytes : 38return gstr (name )+ struct .pack ("<IQIQ" ,1 ,n ,type_id ,offset ) 39 40 41def pad (b :bytes ,data :int )-> bytes : 42return b + bytes (- len (b )% 32 + data ) 43 44 45class MalformedHeader (unittest .TestCase ): 46def setUp (self ): 47self .tmp = tempfile .TemporaryDirectory () 48self .path = Path (self .tmp .name )/ "m-00001-of-00002.gguf" 49 50def tearDown (self ): 51self .tmp .cleanup () 52 53def refused (self ,raw :bytes )-> str : 54self .path .write_bytes (raw ) 55with self .assertRaises (ValueError )as cm : 56GGUFFile (self .path ) 57self .assertIn (self .path .name ,str (cm .exception )) 58return str (cm .exception ) 59 60def test_unknown_metadata_value_type (self ): 61self .refused (pad (header (0 ,gstr (b"k" )+ struct .pack ("<I" ,99 ),1 ),0 )) 62 63def test_unknown_array_element_type (self ): 64self .refused (pad (header (0 ,gstr (b"k" )+ struct .pack ("<IIQ" ,9 ,99 ,1 ),1 ),0 )) 65 66def test_string_length_past_the_end (self ): 67self .refused (pad (header (0 ,struct .pack ("<Q" ,2 ** 63 ),1 ),0 )) 68 69def test_array_count_past_the_end (self ): 70self .refused (pad (header (0 ,gstr (b"k" )+ struct .pack ("<IIQ" ,9 ,4 ,2 ** 40 ),1 ),0 )) 71 72def test_string_array_count_past_the_end (self ): 73self .refused (pad (header (0 ,gstr (b"k" )+ struct .pack ("<IIQ" ,9 ,8 ,2 ** 62 ),1 ),0 )) 74 75def test_tensor_count_past_the_end (self ): 76self .refused (header (2 ** 40 )) 77 78def test_header_cut_mid_tensor_directory (self ): 79self .refused (header (1 )+ tensor (b"blk.0.w" ,8 ,0 ,0 )[:- 5 ]) 80 81def test_header_cut_inside_the_magic (self ): 82self .refused (b"GG" ) 83 84 85class Alignment (unittest .TestCase ): 86setUp = MalformedHeader .setUp 87tearDown = MalformedHeader .tearDown 88refused = MalformedHeader .refused 89def test_invalid_alignment (self ): 90for alignment in (0 ,- 8 ,3 ): 91with self .subTest (alignment = alignment ): 92kv = gstr (b"general.alignment" )+ struct .pack ("<Ii" ,5 ,alignment ) 93self .assertIn ("alignment" ,self .refused (pad (header (0 ,kv ,1 ),0 ))) 94 95 96class UnknownTensorCompatibility (unittest .TestCase ): 97def test_readable_unknown_tensor_keeps_setup_policy (self ): 98with tempfile .TemporaryDirectory ()as tmp : 99p = Path (tmp )/ "future.gguf" 100raw = pad (header (2 )+ tensor (b"known" ,8 ,0 ,0 )+ tensor (b"future" ,64 ,999 ,32 ),256 ) 101p .write_bytes (raw ) 102g = GGUFFile (p ) 103self .assertIsNone (g .tensors [1 ].expected_bytes ()) 104self .assertTrue (S .whole_shard (p )) 105S .check_shards ([p ]) 106self .assertEqual (p .read_bytes (),raw ) 107 108 109class ReaderCompatibility (unittest .TestCase ): 110setUp = MalformedHeader .setUp 111tearDown = MalformedHeader .tearDown 112refused = MalformedHeader .refused 113 114def test_supported_scalar_and_array_values (self ): 115values = [(0 ,'B' ,255 ), (1 ,'b' ,- 7 ), (2 ,'H' ,65535 ), (3 ,'h' ,- 300 ), 116 (4 ,'I' ,2 ** 31 ), (5 ,'i' ,- 70000 ), (6 ,'f' ,1.25 ), (7 ,'?' ,True ), 117 (10 ,'Q' ,2 ** 63 ), (11 ,'q' ,- 2 ** 40 ), (12 ,'d' ,1.125 )] 118kv ,expected = b'' , {} 119for type_id ,fmt ,value in values : 120for array in (False ,True ): 121key = f' { type_id } _ { array } ' 122data = struct .pack ('<' + fmt ,value ) 123kv += gstr (key .encode ())+ (struct .pack ('<IIQ' ,9 ,type_id ,1 )if array 124else struct .pack ('<I' ,type_id ))+ data 125expected [key ]= [value ]if array else value 126for key ,data ,value in [('text' ,struct .pack ('<I' ,8 )+ gstr ('测试' .encode ()),'测试' ), 127 ('strings' ,struct .pack ('<IIQ' ,9 ,8 ,2 )+ gstr (b'' )+ gstr (b'x' ), ['' ,'x' ]), 128 ('empty' ,struct .pack ('<IIQ' ,9 ,4 ,0 ), [])]: 129kv += gstr (key .encode ())+ data 130expected [key ]= value 131self .path .write_bytes (pad (header (1 ,kv ,len (expected ))+ tensor (b'w' ,8 ,0 ,0 ),32 )) 132g = GGUFFile (self .path ) 133self .assertEqual (g .metadata ,expected ) 134self .assertEqual ((g .tensors [0 ].name ,g .tensors [0 ].shape ,g .tensors [0 ].expected_bytes ()), ('w' , [8 ],32 )) 135S .check_shards ([self .path ]) 136 137def test_metadata_only_file_needs_no_alignment_padding (self ): 138raw = header (0 ,gstr (b'general.name' )+ struct .pack ('<I' ,8 )+ gstr (b't' ),1 ) 139self .path .write_bytes (raw ) 140g = GGUFFile (self .path ) 141self .assertEqual (g .metadata , {'general.name' :'t' }) 142self .assertEqual (g .tensors , []) 143self .assertGreater (g .data_start ,len (raw )) 144S .check_shards ([self .path ]) 145self .assertEqual (self .path .read_bytes (),raw ) 146 147def test_explicit_alignment_keeps_tensor_offsets (self ): 148for alignment in (24 ,64 ): 149with self .subTest (alignment = alignment ): 150kv = gstr (b'general.alignment' )+ struct .pack ('<II' ,4 ,alignment ) 151raw = header (1 ,kv ,1 )+ tensor (b'w' ,8 ,0 ,0 ) 152start = (len (raw )+ alignment - 1 )// alignment * alignment 153self .path .write_bytes (raw + bytes (start - len (raw )+ 32 )) 154g = GGUFFile (self .path ) 155self .assertEqual ((g .alignment ,g .data_start ), (alignment ,start )) 156S .check_shards ([self .path ]) 157 158def test_setup_reports_malformed_file_without_changing_it (self ): 159for raw in (header (0 ,gstr (b'k' )+ struct .pack ('<I' ,99 ),1 ), 160header (0 ,struct .pack ('<Q' ,2 ** 63 )+ bytes (4 ),1 )): 161with self .subTest (raw = raw .hex ()): 162self .path .write_bytes (raw ) 163self .assertFalse (S .whole_shard (self .path )) 164out = io .StringIO () 165with contextlib .redirect_stdout (out ),self .assertRaises (SystemExit ): 166S .check_shards ([self .path ]) 167self .assertIn (self .path .name + ' is not a whole GGUF shard' ,out .getvalue ()) 168self .assertEqual (self .path .read_bytes (),raw ) 169 170def test_unsupported_array_and_impossible_dimension_count_are_named (self ): 171self .refused (header (0 ,gstr (b'k' )+ struct .pack ('<IIQ' ,9 ,9 ,0 ),1 )) 172self .refused (header (1 )+ gstr (b'w' )+ struct .pack ('<I' ,2 ** 32 - 1 )+ bytes (12 )) 173 174 175if __name__ == "__main__" : 176unittest .main ()