okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
97da46cc1
main
1"""quant_formats.py --hf reads each shard's header over HTTP range requests with gguf_reader's bounds checks (#5075): the 2header knows the file's size from the Hugging Face tree, so a complete header parses and a cut one is refused with a 3ValueError that names the file. Over a minimal GGUF v3 header written here (no network, no model). 4 5python -m unittest tools.test_quant_formats_hf 6""" 7from __future__import annotations 8 9import io 10import json 11import re 12import struct 13import sys 14import unittest 15from pathlib import Path 16from unittest import mock 17 18sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 19import quant_formats as Q # noqa: E402 20 21 22def gstr (s :bytes )-> bytes : 23return struct .pack ("<Q" ,len (s ))+ s 24 25 26def shard ()-> bytes : 27"""One Q8_0 [32, 4] tensor `blk.0.ffn_down_exps.weight` (type 8), data at offset 0 after a 32-byte alignment.""" 28head = struct .pack ("<IIQQ" ,0x46554747 ,3 ,1 ,0 )+ gstr (b"blk.0.ffn_down_exps.weight" )+ struct .pack ("<I" ,2 ) 29head += struct .pack ("<QQ" ,32 ,4 )+ struct .pack ("<IQ" ,8 ,0 ) 30head += bytes (- len (head )% 32 ) 31return head + bytes (4 * 34 ) 32 33 34class Response (io .BytesIO ): 35def __enter__ (self ): 36return self 37 38def __exit__ (self ,* a ): 39return False 40 41 42def serve (files :dict [str ,bytes ]): 43def urlopen (req ,timeout = None ): 44url = req if isinstance (req ,str )else req .full_url 45if "/api/models/" in url : 46return Response (json .dumps ([{"type" :"file" ,"path" :p ,"size" :len (b )}for p ,b in files .items ()]).encode ()) 47name = url .rsplit ("/" ,1 )[1 ] 48lo ,hi = map (int ,re .match (r"bytes=([0-9]+)-([0-9]+)" ,req .get_header ("Range" )).groups ()) 49return Response (files [name ][lo :hi + 1 ]) 50return mock .patch .object (Q .urllib .request ,"urlopen" ,urlopen ) 51 52 53class HfHeaders (unittest .TestCase ): 54def test_a_shard_header_is_read_over_range_requests (self ): 55with serve ({"m-00001-of-00001.gguf" :shard ()}): 56heads = Q .hf_headers ("org/repo" ,"rev" ,"dir" ) 57self .assertEqual ([t .name for t in heads [0 ].tensors ], ["blk.0.ffn_down_exps.weight" ]) 58 59def test_a_cut_header_is_refused_with_the_file_name (self ): 60with serve ({"m-00001-of-00001.gguf" :shard ()[:40 ]}): 61with self .assertRaises (ValueError )as cm : 62Q .hf_headers ("org/repo" ,"rev" ,"dir" ) 63self .assertIn ("m-00001-of-00001.gguf" ,str (cm .exception )) 64 65def test_a_huge_name_length_is_refused_not_allocated (self ): 66head = struct .pack ("<IIQQ" ,0x46554747 ,3 ,1 ,0 )+ struct .pack ("<Q" ,2 ** 64 - 16 )+ bytes (32 ) 67with serve ({"m.gguf" :head }): 68with self .assertRaises (ValueError )as cm : 69Q .hf_headers ("org/repo" ,"rev" ,"dir" ) 70self .assertIn ("m.gguf" ,str (cm .exception )) 71 72 73if __name__ == "__main__" : 74unittest .main ()