okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
538acd098
main
1"""Tests for tools/nvfp4_local_pack.py: the CSF scale decode, the MXFP8 dequantization, the PLE rows.""" 2import json 3import pathlib 4import struct 5import sys 6 7import numpy as np 8import unittest 9 10try : 11import pytest 12except ImportError :# not in requirements.txt: python -m unittest skips this module instead of failing to import it (#3325) 13raise unittest .SkipTest ("pytest is not installed" ) 14 15sys .path .insert (0 ,str (pathlib .Path (__file__ ).resolve ().parent )) 16import nvfp4_local_pack as P # noqa: E402 17 18 19def _scales (rows ,cols ,seed ,outliers = 0.01 ): 20rng = np .random .default_rng (seed ) 21base = rng .integers (60 ,100 ,size = (rows ,1 )) 22s = base + rng .integers (0 ,16 ,size = (rows ,cols )) 23m = rng .random ((rows ,cols ))< outliers 24s [m ]= rng .integers (0 ,127 ,size = int (m .sum ())) 25return s .astype (np .uint8 ) 26 27 28@ pytest . mark . parametrize ( "rows,cols" , [( 32 , 8 ), ( 640 , 160 ), ( 2560 , 40 )]) 29def test_csf_roundtrip_is_exact (rows ,cols ): 30s = _scales (rows ,cols ,rows + cols ) 31fixed ,exc = P .csf_encode (s ) 32assert fixed .shape == (rows // 16 ,16 * (1 + cols // 2 ))# the shapes of the real tensors 33assert np .array_equal (P .csf_decode (fixed ,exc ),s ) 34 35 36def test_csf_matches_the_spec_by_hand (): 37# one 16-row slab, 4 columns: base bytes 10..25, rows' codes = col index, one exception at row 3 col 2 38rows ,cols = 16 ,4 39fixed = np .zeros ((1 ,16 * (1 + cols // 2 )),np .uint8 ) 40fixed [0 , :16 ]= np .arange (10 ,26 ) 41for r in range (rows ): 42fixed [0 ,16 + r * 2 ]= 0 | (1 << 4 )# cols 0 (low nibble), 1 (high) 43fixed [0 ,16 + r * 2 + 1 ]= 2 | (3 << 4 )# cols 2, 3 44exc = np .array ([(3 * cols + 2 )| (99 << 24 )],np .uint32 ) 45got = P .csf_decode (fixed ,exc ) 46assert got [0 ].tolist ()== [10 ,11 ,12 ,13 ] 47assert got [5 ].tolist ()== [15 ,16 ,17 ,18 ] 48assert got [3 ].tolist ()== [13 ,14 ,99 ,16 ] 49 50 51def test_csf_rejects_bad_streams (): 52with pytest .raises (ValueError ): 53P .csf_decode (np .zeros ((1 ,33 ),np .uint8 ),np .zeros (0 ,np .uint32 )) 54fixed = np .zeros ((1 ,32 ),np .uint8 ) 55fixed [0 ,0 ]= 250 56with pytest .raises (ValueError ): 57P .csf_decode (fixed ,np .zeros (0 ,np .uint32 )) 58with pytest .raises (ValueError ): 59P .csf_decode (np .zeros ((1 ,32 ),np .uint8 ),np .array ([16 * 4 ],np .uint32 )) 60 61 62def test_mxfp8_dequant_exact (): 63torch = pytest .importorskip ("torch" ) 64rng = np .random .default_rng (3 ) 65vals = rng .integers (0 ,126 ,size = (4 ,64 )).astype (np .uint8 )| (rng .integers (0 ,2 ,size = (4 ,64 )).astype (np .uint8 )<< 7 ) 66sc = rng .integers (100 ,130 ,size = (4 ,2 )).astype (np .uint8 ) 67got = P .mxfp8_dequant (vals ,sc ).numpy () 68ref = torch .from_numpy (vals ).view (torch .float8_e4m3fn ).to (torch .float32 ).numpy ().reshape (4 ,2 ,32 ) 69ref = ref * np .exp2 (sc .astype (np .float64 )- 127 )[:, :,None ] 70assert np .array_equal (got .reshape (4 ,2 ,32 ),ref .astype (np .float32 )) 71# exactly representable in BF16 (what the converter hands on) 72bf = torch .from_numpy (got ).to (torch .bfloat16 ).to (torch .float32 ).numpy () 73assert np .array_equal (bf ,got ) 74 75 76def test_mxfp8_rejects_nan_scale (): 77pytest .importorskip ("torch" ) 78with pytest .raises (ValueError ): 79P .mxfp8_dequant (np .zeros ((1 ,32 ),np .uint8 ),np .full ((1 ,1 ),255 ,np .uint8 )) 80 81 82def test_ple_rows_are_codes_then_scales (): 83c = np .arange (160 ,dtype = np .uint8 ).reshape (2 ,80 ) 84s = np .arange (20 ,dtype = np .uint8 ).reshape (2 ,10 )+ 200 85r = P .interleave_rows (c ,s ) 86assert r .shape == (2 ,P .PLE_ROW_BYTES ) 87assert np .array_equal (r [1 , :80 ],c [1 ])and np .array_equal (r [1 ,80 :],s [1 ]) 88 89 90def test_nvfp4_dequant_by_hand (): 91# element 2i in the low nibble: byte 0x21 = codes 1 (0.5) and 2 (1.0); 0xF7 = 7 (6.0) and 15 (-6.0) 92codes = np .zeros ((1 ,8 ),np .uint8 ) 93codes [0 ,0 ],codes [0 ,1 ]= 0x21 ,0xF7 94sc = np .array ([[0x38 ]],np .uint8 )# E4M3 0x38 = 1.0 95got = P .nvfp4_dequant (codes ,sc ,2.0 ) 96assert got [0 , :4 ].tolist ()== [1.0 ,2.0 ,12.0 ,- 12.0 ] 97 98 99def test_e4m3_table_and_bf16_rounding (): 100t = P .e4m3_table () 101assert t [0x38 ]== 1.0 and t [0x7E ]== 448.0 and np .isnan (t [0x7F ])and t [0x01 ]== 2.0 ** - 9 102x = np .array ([1.0 ,1.0 + 2.0 ** - 8 ,1.0 + 3 * 2.0 ** - 9 ,- 2.5 ],np .float32 ) 103b = P .f32_to_bf16_bits (x ) 104back = (b .astype (np .uint32 )<< 16 ).view (np .float32 ) 105assert back .tolist ()== [1.0 ,1.0 ,1.0078125 ,- 2.5 ]# ties to even; 1+3*2^-9 rounds up 106 107 108def test_nvfp4_blocks_layout_by_hand (): 109# one row of 64 values: codes 0..15 repeated; scales 0x38 0x39 0x3A 0x3B with a sign bit set on the first (dropped) 110codes = np .arange (64 )% 16 111packed = (codes [0 ::2 ]| (codes [1 ::2 ]<< 4 )).astype (np .uint8 ).reshape (1 ,32 ) 112sc = np .array ([[0xB8 ,0x39 ,0x3A ,0x3B ]],np .uint8 ) 113out = P .nvfp4_blocks (packed ,sc ) 114assert out .shape == (1 ,36 ) 115assert out [0 , :4 ].tolist ()== [0x38 ,0x39 ,0x3A ,0x3B ] 116# within a 16-block: element j in the low nibble, element j+8 in the high one 117blk0 = out [0 ,4 :12 ] 118assert [int (b & 15 )for b in blk0 ]== list (range (8 ))and [int (b >> 4 )for b in blk0 ]== list (range (8 ,16 )) 119 120 121def _write_shard (path ,tensors ): 122"""tensors: name -> (dtype, shape, uint8 bytes), written safetensors-style (data after the header).""" 123hdr ,data ,off = {},bytearray (),0 124for name , (dt ,shape ,buf )in tensors .items (): 125hdr [name ]= {"dtype" :dt ,"shape" :shape ,"data_offsets" : [off ,off + len (buf )]} 126data += buf 127off += len (buf ) 128hj = json .dumps (hdr ).encode ("utf-8" ) 129hj += b" " * (- len (hj )% 8 ) 130with open (path ,"wb" )as f : 131f .write (struct .pack ("<Q" ,len (hj ))+ hj + data ) 132 133 134def test_checkpoint_reads_the_shard_bytes_exactly (tmp_path ): 135a = np .arange (200 ,dtype = np .uint8 ) 136_write_shard (tmp_path / "s1.safetensors" , {"t.a" : ("U8" , [100 ,2 ],a .tobytes ())}) 137d = np .arange (4 ,dtype = np .uint32 ) 138c = np .arange (32 ,dtype = np .uint8 ) 139_write_shard (tmp_path / "s2.safetensors" , {"t.d" : ("U32" , [4 ],d .tobytes ()),"t.c" : ("U8" , [8 ,4 ],c .tobytes ())}) 140 (tmp_path / "model.safetensors.index.json" ).write_text (json .dumps ({"weight_map" : { 141"t.a" :"s1.safetensors" ,"t.c" :"s2.safetensors" ,"t.d" :"s2.safetensors" }}),encoding = "utf-8" ) 142ck = P .Checkpoint (tmp_path ) 143assert "t.a" in ck and ck .shape ("t.a" )== [100 ,2 ]and ck .dtype ("t.a" )== "U8" 144assert np .array_equal (ck .raw ("t.a" ),a )# the bytes at the tensor's exact range 145assert np .array_equal (ck .array ("t.c" ,np .uint8 ),c .reshape (8 ,4 )) 146assert np .array_equal (ck .array ("t.d" ,np .uint32 ),d )# .view through a fresh buffer 147assert np .array_equal (ck .raw ("t.a" ),ck .raw ("t.a" ))# a second read is still correct 148 149 150def test_checkpoint_names_a_truncated_shard (tmp_path ): 151c = np .arange (32 ,dtype = np .uint8 ) 152_write_shard (tmp_path / "s1.safetensors" , {"t.c" : ("U8" , [8 ,4 ],c .tobytes ())}) 153p = tmp_path / "s1.safetensors" 154p .write_bytes (p .read_bytes ()[:- 8 ])# the last tensor's range now ends past EOF 155ck = P .Checkpoint (tmp_path ) 156with pytest .raises (EOFError ): 157ck .raw ("t.c" )