okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-gh-ctl: GitHub setup, Docker, docs and bench items for 0.2.7538acd098

main
6.9 KiB157 linesraw
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:
11    import pytest
12except ImportError:                                  # not in requirements.txt: python -m unittest skips this module instead of failing to import it (#3325)
13    raise 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):
20    rng = np.random.default_rng(seed)
21    base = rng.integers(60, 100, size=(rows, 1))
22    s = base + rng.integers(0, 16, size=(rows, cols))
23    m = rng.random((rows, cols)) < outliers
24    s[m] = rng.integers(0, 127, size=int(m.sum()))
25    return 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):
30    s = _scales(rows, cols, rows + cols)
31    fixed, exc = P.csf_encode(s)
32    assert fixed.shape == (rows // 16, 16 * (1 + cols // 2))     # the shapes of the real tensors
33    assert 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
38    rows, cols = 16, 4
39    fixed = np.zeros((1, 16 * (1 + cols // 2)), np.uint8)
40    fixed[0, :16] = np.arange(10, 26)
41    for r in range(rows):
42        fixed[0, 16 + r * 2] = 0 | (1 << 4)       # cols 0 (low nibble), 1 (high)
43        fixed[0, 16 + r * 2 + 1] = 2 | (3 << 4)   # cols 2, 3
44    exc = np.array([(3 * cols + 2) | (99 << 24)], np.uint32)
45    got = P.csf_decode(fixed, exc)
46    assert got[0].tolist() == [10, 11, 12, 13]
47    assert got[5].tolist() == [15, 16, 17, 18]
48    assert got[3].tolist() == [13, 14, 99, 16]
49
50
51def test_csf_rejects_bad_streams():
52    with pytest.raises(ValueError):
53        P.csf_decode(np.zeros((1, 33), np.uint8), np.zeros(0, np.uint32))
54    fixed = np.zeros((1, 32), np.uint8)
55    fixed[0, 0] = 250
56    with pytest.raises(ValueError):
57        P.csf_decode(fixed, np.zeros(0, np.uint32))
58    with pytest.raises(ValueError):
59        P.csf_decode(np.zeros((1, 32), np.uint8), np.array([16 * 4], np.uint32))
60
61
62def test_mxfp8_dequant_exact():
63    torch = pytest.importorskip("torch")
64    rng = np.random.default_rng(3)
65    vals = rng.integers(0, 126, size=(4, 64)).astype(np.uint8) | (rng.integers(0, 2, size=(4, 64)).astype(np.uint8) << 7)
66    sc = rng.integers(100, 130, size=(4, 2)).astype(np.uint8)
67    got = P.mxfp8_dequant(vals, sc).numpy()
68    ref = torch.from_numpy(vals).view(torch.float8_e4m3fn).to(torch.float32).numpy().reshape(4, 2, 32)
69    ref = ref * np.exp2(sc.astype(np.float64) - 127)[:, :, None]
70    assert np.array_equal(got.reshape(4, 2, 32), ref.astype(np.float32))
71    # exactly representable in BF16 (what the converter hands on)
72    bf = torch.from_numpy(got).to(torch.bfloat16).to(torch.float32).numpy()
73    assert np.array_equal(bf, got)
74
75
76def test_mxfp8_rejects_nan_scale():
77    pytest.importorskip("torch")
78    with pytest.raises(ValueError):
79        P.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():
83    c = np.arange(160, dtype=np.uint8).reshape(2, 80)
84    s = np.arange(20, dtype=np.uint8).reshape(2, 10) + 200
85    r = P.interleave_rows(c, s)
86    assert r.shape == (2, P.PLE_ROW_BYTES)
87    assert 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)
92    codes = np.zeros((1, 8), np.uint8)
93    codes[0, 0], codes[0, 1] = 0x21, 0xF7
94    sc = np.array([[0x38]], np.uint8)            # E4M3 0x38 = 1.0
95    got = P.nvfp4_dequant(codes, sc, 2.0)
96    assert got[0, :4].tolist() == [1.0, 2.0, 12.0, -12.0]
97
98
99def test_e4m3_table_and_bf16_rounding():
100    t = P.e4m3_table()
101    assert t[0x38] == 1.0 and t[0x7E] == 448.0 and np.isnan(t[0x7F]) and t[0x01] == 2.0 ** -9
102    x = np.array([1.0, 1.0 + 2.0 ** -8, 1.0 + 3 * 2.0 ** -9, -2.5], np.float32)
103    b = P.f32_to_bf16_bits(x)
104    back = (b.astype(np.uint32) << 16).view(np.float32)
105    assert 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)
110    codes = np.arange(64) % 16
111    packed = (codes[0::2] | (codes[1::2] << 4)).astype(np.uint8).reshape(1, 32)
112    sc = np.array([[0xB8, 0x39, 0x3A, 0x3B]], np.uint8)
113    out = P.nvfp4_blocks(packed, sc)
114    assert out.shape == (1, 36)
115    assert 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
117    blk0 = out[0, 4:12]
118    assert [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)."""
123    hdr, data, off = {}, bytearray(), 0
124    for name, (dt, shape, buf) in tensors.items():
125        hdr[name] = {"dtype": dt, "shape": shape, "data_offsets": [off, off + len(buf)]}
126        data += buf
127        off += len(buf)
128    hj = json.dumps(hdr).encode("utf-8")
129    hj += b" " * (-len(hj) % 8)
130    with open(path, "wb") as f:
131        f.write(struct.pack("<Q", len(hj)) + hj + data)
132
133
134def test_checkpoint_reads_the_shard_bytes_exactly(tmp_path):
135    a = np.arange(200, dtype=np.uint8)
136    _write_shard(tmp_path / "s1.safetensors", {"t.a": ("U8", [100, 2], a.tobytes())})
137    d = np.arange(4, dtype=np.uint32)
138    c = 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")
142    ck = P.Checkpoint(tmp_path)
143    assert "t.a" in ck and ck.shape("t.a") == [100, 2] and ck.dtype("t.a") == "U8"
144    assert np.array_equal(ck.raw("t.a"), a)                       # the bytes at the tensor's exact range
145    assert np.array_equal(ck.array("t.c", np.uint8), c.reshape(8, 4))
146    assert np.array_equal(ck.array("t.d", np.uint32), d)          # .view through a fresh buffer
147    assert 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):
151    c = np.arange(32, dtype=np.uint8)
152    _write_shard(tmp_path / "s1.safetensors", {"t.c": ("U8", [8, 4], c.tobytes())})
153    p = tmp_path / "s1.safetensors"
154    p.write_bytes(p.read_bytes()[:-8])                            # the last tensor's range now ends past EOF
155    ck = P.Checkpoint(tmp_path)
156    with pytest.raises(EOFError):
157        ck.raw("t.c")