Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / ml / test / test_quantise.py

test_quantise.py324 lines · 15.0 KiBRaw
1#!/usr/bin/env python3
2"""test_quantise.py - unit test for `maml_convert.quantise_per_channel`.
3
4The int8 quantiser is the one part of the converter with no oracle beside it. Every other
5transform is checked end to end by `scripts/ml/onnx_parity.py`, which needs the ONNX export and
6onnxruntime; this needs neither, and the properties below are the ones a wrong quantiser breaks
7while still producing a `.maml` of exactly the right size.
8
9What each check is defending against, since none of them is arbitrary:
10
11* **Round trip.** An absmax quantiser's error is bounded by half a code, `scale / 2`. A quantiser
12 that divided by the wrong row's scale reconstructs plausible numbers that are wrong by a factor,
13 and nothing about the file's shape reveals it.
14* **The axis.** `library/ml`'s shaders index the scale by *output* channel, so a quantiser that
15 reduced over axis 0 instead of the rest gives a tensor of the right length holding the wrong
16 per-channel ranges. A kernel whose rows differ in scale by 1000x is what separates the two.
17* **The range.** int8 is -128..127 and the scale is `absmax / 127`, so the extreme weight must
18 land on ±127 exactly. Using 128 puts it out of range on one side.
19* **Zero.** The quantisation is symmetric with no zero point, so an exactly-zero weight must
20 reconstruct as exactly zero - `conv_int8.comp` has nowhere to put an offset.
21
22Run:
23
24 python3 scripts/ml/test/test_quantise.py
25
26Exit code 0 = all assertions passed.
27"""
28from __future__ import annotations
29
30import os
31import struct
32import sys
33
34import numpy as np
35
36sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
37
38import maml_convert # noqa: E402 (needs the path above)
39import supertonic_fold # noqa: E402 (needs the path above)
40
41passed = 0
42failed = 0
43
44
45def check(what: str, ok: bool) -> None:
46 global passed, failed
47 if ok:
48 passed += 1
49 print(f" ok {what}")
50 else:
51 failed += 1
52 print(f" FAIL {what}")
53
54
55def test_round_trip_is_within_half_a_code() -> None:
56 print("round trip:")
57 rng = np.random.default_rng(11)
58 kernel = rng.standard_normal((17, 23, 1, 1)).astype(np.float32)
59 quantised, scale = maml_convert.quantise_per_channel(kernel)
60
61 check("the kernel keeps its shape", quantised.shape == kernel.shape)
62 check("the payload is int8", quantised.dtype == np.int8)
63 check("one scale per output channel", scale.shape == (17,))
64
65 rows = kernel.reshape(17, -1)
66 back = quantised.astype(np.float32).reshape(17, -1) * scale[:, None]
67 # Half a code, plus the fp16 rounding of the scale itself, which multiplies the whole row.
68 allowance = scale[:, None] * 0.5 + np.abs(back) * 2.0 ** -11
69 check("every weight is within half a code", bool((np.abs(rows - back) <= allowance).all()))
70
71
72def test_the_scale_is_per_output_channel_not_per_input() -> None:
73 print("the reduction axis:")
74 # Row `i` spans ±(i + 1), so the per-output-channel scales must differ by 20x across the
75 # kernel. A quantiser that reduced over the output axis instead would give 23 identical-ish
76 # scales, and only 20 of them, so the shape check alone nearly catches it - hence the
77 # non-square shape.
78 kernel = np.zeros((20, 23, 1, 1), dtype=np.float32)
79 for row in range(20):
80 kernel[row, :, 0, 0] = np.linspace(-(row + 1.0), row + 1.0, 23)
81 quantised, scale = maml_convert.quantise_per_channel(kernel)
82
83 check("there are as many scales as output channels", scale.shape == (20,))
84 check("the scales rise with the rows", bool((np.diff(scale) > 0).all()))
85 # Each row's own extreme must reach the top code, which is what per-channel buys: under one
86 # tensor-wide scale row 0 would be quantised against row 19's range and lose 20x resolution.
87 reached = [int(np.abs(quantised[row]).max()) for row in range(20)]
88 check("every row reaches the top code", reached == [127] * 20)
89
90
91def test_the_extremes_land_on_the_symmetric_range() -> None:
92 print("the range:")
93 kernel = np.array([[-4.0, 4.0, 0.0, 1.0]], dtype=np.float32).reshape(1, 4, 1, 1)
94 quantised, scale = maml_convert.quantise_per_channel(kernel)
95 flat = quantised.reshape(-1).tolist()
96
97 check("the negative extreme is -127", flat[0] == -127)
98 check("the positive extreme is +127", flat[1] == 127)
99 check("nothing exceeds int8's range", all(-128 <= c <= 127 for c in flat))
100 check("the scale is absmax / 127", abs(float(scale[0]) - 4.0 / 127.0) < 1e-4)
101
102
103def test_zero_reconstructs_as_zero() -> None:
104 print("zero:")
105 kernel = np.array([[-2.0, 0.0, 2.0]], dtype=np.float32).reshape(1, 3, 1, 1)
106 quantised, _ = maml_convert.quantise_per_channel(kernel)
107 check("an exactly-zero weight quantises to code 0", int(quantised.reshape(-1)[1]) == 0)
108
109 # An all-zero output channel has an absmax of 0, so its scale would be a division by zero.
110 # It is given 1.0, which reproduces the row exactly for the same reason any scale would.
111 kernel = np.zeros((2, 5, 1, 1), dtype=np.float32)
112 kernel[1] = 3.0
113 quantised, scale = maml_convert.quantise_per_channel(kernel)
114 check("an all-zero channel has a finite scale", bool(np.isfinite(scale).all()))
115 check("an all-zero channel is all zeros", bool((quantised[0] == 0).all()))
116 check("its neighbour is unaffected", int(np.abs(quantised[1]).max()) == 127)
117
118
119def test_the_scale_survives_fp16() -> None:
120 print("fp16 storage:")
121 # The scale is stored as fp16 beside the weights, so a scale the file cannot hold would make
122 # the device compute something the converter never saw. Returning it already rounded is what
123 # keeps the two agreeing.
124 rng = np.random.default_rng(5)
125 kernel = (rng.standard_normal((9, 11, 1, 1)) * 1e-3).astype(np.float32)
126 _, scale = maml_convert.quantise_per_channel(kernel)
127 check(
128 "the scale is exactly representable in fp16",
129 bool((scale.astype(np.float16).astype(np.float32) == scale).all()),
130 )
131
132
133def test_a_non_finite_kernel_is_refused() -> None:
134 print("refusals:")
135 kernel = np.array([[1.0, np.inf]], dtype=np.float32).reshape(1, 2, 1, 1)
136 try:
137 maml_convert.quantise_per_channel(kernel)
138 check("an infinite weight is refused", False)
139 except SystemExit:
140 check("an infinite weight is refused", True)
141
142
143def test_a_quantised_conv_reaches_the_file_as_int8() -> None:
144 print("the table entry:")
145 # The trap `Table.add` exists to avoid: it coerces every tensor to fp32, and a quantised kernel
146 # that went through that path would be written as fp16 - the file would be *larger* than the
147 # unquantised one, load without complaint, and infer nonsense, because `weights.rs` reads an
148 # int8 entry with a 1-byte stride and an fp16 one with 2.
149 channels, inputs = 6, 8
150 held = {
151 "block.pwconv2.weight": np.linspace(-1.0, 1.0, channels * inputs)
152 .reshape(channels, inputs)
153 .astype(np.float32),
154 "block.pwconv2.bias": np.arange(channels, dtype=np.float32),
155 }
156 table = supertonic_fold.Table(held)
157 table.conv("block.pwconv2", channels, int8=True)
158
159 check("one layer, three tensors", len(table.layers) == 1 and len(table.tensors) == 3)
160 check("the kernel stayed int8", table.tensors[0].dtype == np.int8)
161 check("the scale is one per output channel", table.tensors[1].shape == (channels,))
162 check("the bias follows the scale", table.tensors[2].shape == (channels,))
163 check("the key records the dtype", "dtype=int8" in table.layers[0].key())
164
165 blob, _ = maml_convert.build(table.layers, table.tensors, 12, b"\0" * 32)
166 entry = maml_convert.HEADER_BYTES
167 dtype = int.from_bytes(blob[entry + 20:entry + 24], "little")
168 length = int.from_bytes(blob[entry + 28:entry + 32], "little")
169 check("the table entry says int8", dtype == maml_convert.DTYPE_I8)
170 check("it declares every tap", length == channels * inputs)
171
172 # Three tensors at 16-byte alignment: 48 int8 bytes padded to 48, then two 6-element fp16
173 # tensors of 12 bytes padded to 16 each. An fp16 kernel would have made the first 96.
174 data_length = int.from_bytes(blob[52:56], "little")
175 check("the kernel occupies one byte a tap", data_length == 48 + 16 + 12)
176
177
178def test_a_shape_the_shaders_cannot_serve_is_refused() -> None:
179 print("ineligible convolutions:")
180 # Neither int8 shader edge-pads or indexes a grouped kernel, so a call site asking for one is a
181 # mistake that must not reach the `.maml`: the tensor indices after it would already have
182 # shifted by one, and the Rust would read the right shapes holding the wrong numbers.
183 held = {
184 "block.dwconv.weight": np.ones((4, 1, 1, 5), dtype=np.float32),
185 "block.dwconv.bias": np.zeros(4, dtype=np.float32),
186 }
187 for what, kwargs in [
188 ("a depthwise kernel", {"group": 4, "kernel": (1, 5)}),
189 ("a padded kernel", {"kernel": (1, 5), "pads": (0, 2, 0, 2)}),
190 ]:
191 try:
192 supertonic_fold.Table(held).conv("block.dwconv", 4, int8=True, **kwargs)
193 check(f"{what} is refused", False)
194 except SystemExit:
195 check(f"{what} is refused", True)
196
197
198def test_int4_round_trip_is_within_half_a_block_code():
199 """As the int8 round trip, but the bound is that block's scale, not that row's.
200
201 A quantiser that used one scale per row - the int8 behaviour - would still produce codes in
202 range and a file of exactly the right size, and would blow this bound on any row whose blocks
203 differ in magnitude. So the fixture makes them differ by 100x on purpose.
204 """
205 rng = np.random.RandomState(11)
206 rows, taps = 6, maml_convert.I4_BLOCK * 3 + 7
207 kernel = rng.randn(rows, taps).astype(np.float32)
208 # Every third block is a hundred times louder, which one row-wide scale cannot serve.
209 for block in range(0, taps, maml_convert.I4_BLOCK * 3):
210 kernel[:, block : block + maml_convert.I4_BLOCK] *= 100.0
211 codes, scale = maml_convert.quantise_per_block(kernel)
212 blocks = scale.shape[1]
213 check("the scale table is (rows, blocks)", scale.shape == (rows, blocks))
214 check("blocks cover the taps", blocks == -(-taps // maml_convert.I4_BLOCK))
215 worst = 0.0
216 for r in range(rows):
217 for t in range(taps):
218 block = t // maml_convert.I4_BLOCK
219 rebuilt = float(codes[r, t]) * float(scale[r, block])
220 worst = max(worst, abs(rebuilt - float(kernel[r, t])) / float(scale[r, block]))
221 check(f"every weight is within half a code of its block ({worst:.4f})", worst <= 0.5001)
222
223
224def test_int4_codes_stay_inside_the_signed_nibble():
225 """-8..7 is what `int4_at`'s `bitfieldExtract` sign-extends to, and 7 is the divisor.
226
227 A quantiser dividing by 8 would put `+absmax` on code 8, which reads back as -8: the largest
228 positive weight in the tensor becomes the largest negative one.
229 """
230 kernel = np.array([[-4.0, 4.0, 0.0, 1.0]], dtype=np.float32)
231 codes, scale = maml_convert.quantise_per_block(kernel)
232 check("no code exceeds the nibble", int(codes.min()) >= -8 and int(codes.max()) <= 7)
233 check("the extreme lands on 7", int(np.abs(codes).max()) == 7)
234 check("zero stays zero", int(codes[0, 2]) == 0)
235 check("the scale is absmax/7", abs(float(scale[0, 0]) - np.float16(4.0 / 7.0)) < 1e-6)
236
237
238def test_int4_packing_is_low_nibble_first_and_rounds_odd_lengths_up():
239 """The one place the converter and `weights.rs` can disagree without either looking wrong.
240
241 Five elements are two and a half bytes. Writing two would produce a file that parses - the
242 reader's bounds check would pass - whose last element read as whatever followed it.
243 """
244 packed = maml_convert.pack_int4(np.array([-8, -1, 0, 1, 7], dtype=np.int8))
245 check("five elements occupy three bytes", len(packed) == 3)
246 check("low nibble first, sign kept", packed[0] == 0xF8)
247 check("second pair", packed[1] == 0x10)
248 check("the odd tail pads its high nibble", packed[2] == 0x07)
249 even = maml_convert.pack_int4(np.zeros(64, dtype=np.int8))
250 check("an even length is exactly half", len(even) == 32)
251 try:
252 maml_convert.pack_int4(np.array([8], dtype=np.int8))
253 check("a code past the nibble is refused", False)
254 except SystemExit:
255 check("a code past the nibble is refused", True)
256
257
258def test_an_int4_tensor_reaches_the_file_as_dtype_two():
259 """End to end through `build`, since `Int4` is what tells it the dtype."""
260 codes, scale = maml_convert.quantise_per_block(
261 np.random.RandomState(3).randn(4, 70).astype(np.float32)
262 )
263 blob, _ = maml_convert.build(
264 ["one"],
265 [maml_convert.Int4(codes), scale.astype(np.float32), np.zeros(4, np.float32)],
266 maml_convert.GRAPHS["supertonic_ve"],
267 bytes(32),
268 )
269 # Tensor 0's dtype word sits at offset 20 of its 32-byte entry, after rank and four dims.
270 entry = maml_convert.HEADER_BYTES
271 dtype = struct.unpack_from("<I", blob, entry + 20)[0]
272 length = struct.unpack_from("<I", blob, entry + 28)[0]
273 check("the table says int4", dtype == maml_convert.DTYPE_I4)
274 check("the length is elements, not bytes", length == 4 * 70)
275
276
277def test_a_block_whose_scale_underflows_fp16_is_not_nan():
278 """The failure mode: silent NaN codes and an undefined cast, not an error.
279
280 `absmax / 7` for a block of very small weights rounds to **zero** in fp16. The division that
281 follows is then `0 / 0` for every zero in the block, `numpy` produces NaN, and
282 `NaN.astype(int8)` is undefined behaviour - so the block reaches the file as arbitrary codes
283 with nothing to indicate anything went wrong.
284
285 Found by a `RuntimeWarning` while converting the vision tower, which means real weights hit
286 it. Both quantisers are guarded on the same terms.
287 """
288 tiny = np.zeros((2, maml_convert.I4_BLOCK * 2), dtype=np.float32)
289 tiny[0, 0] = 1e-8
290 tiny[1, maml_convert.I4_BLOCK] = 3e-9
291 codes, scale = maml_convert.quantise_per_block(tiny)
292 check("no code is NaN", not np.isnan(codes.astype(np.float32)).any())
293 check("no code is infinite", np.isfinite(codes.astype(np.float32)).all())
294 check("every scale is positive", bool((scale > 0).all()))
295 check("codes stay inside the nibble", int(np.abs(codes).max()) <= 7)
296
297 # And the int8 path, on the same terms.
298 row = np.zeros((1, 8), dtype=np.float32)
299 row[0, 0] = 1e-9
300 codes8, scale8 = maml_convert.quantise_per_channel(row)
301 check("int8 codes are finite", np.isfinite(codes8.astype(np.float32)).all())
302 check("int8 scale is positive", bool((scale8 > 0).all()))
303
304
305def main() -> int:
306 test_round_trip_is_within_half_a_code()
307 test_the_scale_is_per_output_channel_not_per_input()
308 test_the_extremes_land_on_the_symmetric_range()
309 test_zero_reconstructs_as_zero()
310 test_the_scale_survives_fp16()
311 test_a_non_finite_kernel_is_refused()
312 test_a_quantised_conv_reaches_the_file_as_int8()
313 test_a_shape_the_shaders_cannot_serve_is_refused()
314 test_int4_round_trip_is_within_half_a_block_code()
315 test_int4_codes_stay_inside_the_signed_nibble()
316 test_int4_packing_is_low_nibble_first_and_rounds_odd_lengths_up()
317 test_an_int4_tensor_reaches_the_file_as_dtype_two()
318 test_a_block_whose_scale_underflows_fp16_is_not_nan()
319 print(f"\n{passed} passed, {failed} failed")
320 return 1 if failed else 0
321
322
323if __name__ == "__main__":
324 raise SystemExit(main())