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

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

test_tinyclip.py313 lines · 13.5 KiBRaw
1#!/usr/bin/env python3
2"""test_tinyclip.py - unit test for `maml_convert`'s TinyCLIP path.
3
4`collect_tinyclip` is the one converter arm that reads an ONNX graph **by name** rather than walking
5it topologically, and the reason is that TinyCLIP's export gives it no choice: two towers in one
6graph, interleaved, with all 80 projections held in anonymous `onnx::MatMul_NNNN` initializers.
7`check_architecture` is therefore the whole shape guard, and `collect_tinyclip`'s emission *order*
8is the whole contract with `nets::tinyclip`.
9
10Both are checked here against a toy graph of the same structure rather than the real 94 MB export,
11so this runs in a second and needs no download.
12
13What each check is defending against:
14
15* **The transpose, in two directions at once.** A `MatMul` weight is `[in, out]` and a 1x1 kernel is
16 `[out, in, 1, 1]`, so a projection is a transpose. But the `Conv` patch kernel is `[M, C, kH, kW]`
17 already and must **not** be transposed. Getting either wrong yields a tensor of the right shape
18 holding the wrong numbers; 76 of the 80 projections are square, so only `fc1`/`fc2` and the two
19 512-wide heads make it visible in a shape at all.
20* **The position tables, which go opposite ways.** The vision table is transposed to
21 `[width, 1, positions]` because the device adds it to a channel-major sequence; the text table is
22 left `[positions, width]` because the *host* reads it. Swapping them is silent.
23* **The order.** `nets::tinyclip` walks the tensor table positionally. A layer emitted out of order
24 loads cleanly and infers nonsense.
25* **The int8 triple.** `Builder::conv_int8` reads kernel, then per-output-channel scale, then bias.
26 The token embedding is the one **pair** — kernel and scale, no bias — because nothing convolves
27 with it; the host gathers a row.
28
29Run:
30
31 python3 scripts/ml/test/test_tinyclip.py
32
33Exit code 0 = all assertions passed.
34"""
35
36from __future__ import annotations
37
38import os
39import sys
40
41import numpy as np
42import onnx
43from onnx import helper, numpy_helper
44
45sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
46
47import maml_convert # noqa: E402 (needs the path above)
48
49# The real architecture with every dimension shrunk, so the table has the same *structure* — a
50# patch conv, a class token, two position tables, two towers of pre-norm layers and two projections
51# — at a size that builds instantly. `heads` is unused by the converter and kept so the toy is a
52# valid spec.
53TOY = {
54 "width": 4,
55 "heads": 2,
56 "ffn": 8,
57 "vision_layers": 2,
58 "text_layers": 1,
59 "patch": 2,
60 "grid": 3,
61 "vocab": 5,
62 "context": 6,
63 "projection": 3,
64}
65
66passed = 0
67failed = 0
68
69
70def check(what: str, ok: bool) -> None:
71 global passed, failed
72 if ok:
73 passed += 1
74 print(f" ok {what}")
75 else:
76 failed += 1
77 print(f" FAIL {what}")
78
79
80def toy_export(spec, transpose_projections: bool = False):
81 """An `onnx.ModelProto` of `spec`'s shape, filled with distinguishable values.
82
83 Only the initializer list and the node names are populated: those are all
84 `check_architecture` and `collect_tinyclip` read, and a topologically valid CLIP would be a
85 hundred lines of scaffolding testing nothing.
86 """
87 rng = np.random.default_rng(11)
88 parameters, projections = maml_convert.tinyclip_inventory(spec)
89 initializers = [
90 numpy_helper.from_array(rng.standard_normal(shape).astype(np.float32), name)
91 for name, shape in parameters.items()
92 ]
93 nodes = []
94 for index, (node_name, shape) in enumerate(sorted(projections.items())):
95 if transpose_projections:
96 shape = list(reversed(shape))
97 weight = f"onnx::MatMul_{index}"
98 initializers.append(
99 numpy_helper.from_array(rng.standard_normal(shape).astype(np.float32), weight)
100 )
101 nodes.append(
102 helper.make_node("MatMul", ["x", weight], [f"{node_name}_out"], name=node_name)
103 )
104 graph = helper.make_graph(nodes, "toy", [], [], initializer=initializers)
105 return helper.make_model(graph)
106
107
108def test_the_inventory_is_the_real_architecture() -> None:
109 print("inventory:")
110 spec = maml_convert.ARCHITECTURES["tinyclip"]
111 parameters, projections = maml_convert.tinyclip_inventory(spec)
112 # 10 vision layers and 3 text layers of 6 named tensors each, plus 15 outside the towers.
113 check(f"141 named parameters, got {len(parameters)}", len(parameters) == 141)
114 # 13 layers of 6 projections, plus the two towers' output heads.
115 check(f"80 projections, got {len(projections)}", len(projections) == 80)
116 check(
117 "the patch kernel is [width, 3, patch, patch]",
118 parameters["vision_model.embeddings.patch_embedding.weight"] == [256, 3, 16, 16],
119 )
120 check(
121 "the token embedding is [vocab, width]",
122 parameters["text_model.embeddings.token_embedding.weight"] == [49_408, 256],
123 )
124 check(
125 "the vision positions are the folded [1, 197, width]",
126 parameters[maml_convert.VISION_POSITIONS_FOLDED] == [1, 197, 256],
127 )
128 # The upstream typo, which is load-bearing: the vision tower normalises before the stack as
129 # well as after it, and missing that layer is a plausible-looking embedding.
130 check("pre_layrnorm is spelled the export's way", "vision_model.pre_layrnorm.weight" in parameters)
131 # The asymmetric pair a transpose would swap.
132 check(
133 "fc1 is [width, ffn]",
134 projections["/vision_model/encoder/layers.0/mlp/fc1/MatMul"] == [256, 1024],
135 )
136 check(
137 "fc2 is [ffn, width]",
138 projections["/vision_model/encoder/layers.0/mlp/fc2/MatMul"] == [1024, 256],
139 )
140 check(
141 "the text tower has three layers and no fourth",
142 "/text_model/encoder/layers.2/mlp/fc1/MatMul" in projections
143 and "/text_model/encoder/layers.3/mlp/fc1/MatMul" not in projections,
144 )
145 total = sum(int(np.prod(shape)) for shape in parameters.values())
146 total += sum(int(np.prod(shape)) for shape in projections.values())
147 check(f"23,446,016 parameters, got {total}", total == 23_446_016)
148
149
150def test_a_transposed_export_is_refused() -> None:
151 print("the transpose:")
152 spec = maml_convert.ARCHITECTURES["tinyclip"]
153 flipped = toy_export(TOY, transpose_projections=True)
154 try:
155 maml_convert.check_architecture(flipped, "tinyclip", TOY)
156 caught = ""
157 except SystemExit as exit:
158 caught = str(exit)
159 check("a transposed export is refused", bool(caught))
160 check("and fc1 is named in the message", "fc1" in caught)
161
162 toy = toy_export(TOY)
163 maml_convert.check_architecture(toy, "tinyclip", TOY)
164 check("the toy export is accepted against its own spec", True)
165 try:
166 maml_convert.check_architecture(toy, "tinyclip", spec)
167 refused = False
168 except SystemExit:
169 refused = True
170 check("and refused against the real one", refused)
171
172
173def test_the_table_order_is_the_contract() -> None:
174 print("order:")
175 layers, tensors = maml_convert.collect_tinyclip(toy_export(TOY), TOY)
176 ops = [layer.op for layer in layers]
177 layer_ops = ["LayerNorm"] + ["Linear8"] * 4 + ["LayerNorm", "Linear8", "Linear8"]
178 expected = (
179 ["Conv8", "Constant", "Constant", "LayerNorm"]
180 + layer_ops * TOY["vision_layers"]
181 + ["LayerNorm", "Linear8"]
182 + ["Embed8", "Constant"]
183 + layer_ops * TOY["text_layers"]
184 + ["LayerNorm", "Linear8"]
185 )
186 check("the whole table is vision then text, in forward order", ops == expected)
187 names = [layer.name for layer in layers]
188 check("the patch kernel comes first", names[0].endswith("patch_embedding.weight"))
189 check("then the class token", names[1].endswith("class_embedding"))
190 check("then the vision positions", names[2] == maml_convert.VISION_POSITIONS_FOLDED)
191 check("the visual projection ends the vision tower", "visual_projection" in names)
192 check("the text projection is last", names[-1] == "text_projection")
193 # The towers are contiguous, unlike the export, which interleaves them.
194 vision = [i for i, name in enumerate(names) if name.startswith("vision")]
195 text = [i for i, name in enumerate(names) if name.startswith("text")]
196 check("no text layer sits inside the vision tower", max(vision) < min(text))
197 # Every layer's tensors are contiguous and in order, which is how the Rust indexes them.
198 at = 0
199 contiguous = True
200 for layer in layers:
201 contiguous = contiguous and layer.first_tensor == at
202 at += layer.tensor_count
203 check("layer tensor ranges tile the table", contiguous and at == len(tensors))
204
205
206def test_a_projection_is_transposed_and_the_conv_is_not() -> None:
207 print("the two orientations:")
208 export = toy_export(TOY)
209 inits = {i.name: numpy_helper.to_array(i) for i in export.graph.initializer}
210 nodes = {n.name: n for n in export.graph.node}
211 layers, tensors = maml_convert.collect_tinyclip(export, TOY)
212
213 fc1 = next(layer for layer in layers if layer.name.endswith("mlp.fc1"))
214 kernel, scale, bias = tensors[fc1.first_tensor: fc1.first_tensor + 3]
215 check("fc1's kernel is int8", kernel.dtype == np.int8)
216 check(
217 f"shaped [{TOY['ffn']}, {TOY['width']}, 1, 1]",
218 list(kernel.shape) == [TOY["ffn"], TOY["width"], 1, 1],
219 )
220 check("with one scale per output channel", scale.shape == (TOY["ffn"],))
221 check("and the export's own bias", bias.shape == (TOY["ffn"],) and bias.any())
222 # The values, not just the shape: `kernel * scale` must reproduce the *transposed* weight.
223 node = "/vision_model/encoder/layers.0/mlp/fc1/MatMul"
224 held = next(x for x in nodes[node].input if x in inits)
225 want = inits[held].T
226 back = kernel.astype(np.float32).reshape(TOY["ffn"], TOY["width"]) * scale[:, None]
227 check("and reproduces the transposed weight", np.allclose(back, want, atol=0.02))
228
229 patch = layers[0]
230 kernel, scale, bias = tensors[patch.first_tensor: patch.first_tensor + 3]
231 original = inits["vision_model.embeddings.patch_embedding.weight"]
232 check("the patch kernel keeps ONNX's [M, C, kH, kW]", kernel.shape == original.shape)
233 back = kernel.astype(np.float32).reshape(TOY["width"], -1) * scale[:, None]
234 check(
235 "and is emitted verbatim, not transposed",
236 np.allclose(back.reshape(original.shape), original, atol=0.05),
237 )
238 check("with a synthesised zero bias", bias.shape == (TOY["width"],) and not bias.any())
239
240
241def test_the_position_tables_go_opposite_ways() -> None:
242 print("the position tables:")
243 export = toy_export(TOY)
244 inits = {i.name: numpy_helper.to_array(i) for i in export.graph.initializer}
245 layers, tensors = maml_convert.collect_tinyclip(export, TOY)
246 positions = TOY["grid"] ** 2 + 1
247
248 vision = next(layer for layer in layers if layer.name == maml_convert.VISION_POSITIONS_FOLDED)
249 table = tensors[vision.first_tensor]
250 check(
251 f"the vision table is [width, 1, {positions}]",
252 list(table.shape) == [TOY["width"], 1, positions],
253 )
254 original = np.squeeze(inits[maml_convert.VISION_POSITIONS_FOLDED])
255 check(
256 "transposed, so channel c of position p is table[c][0][p]",
257 np.allclose(table.reshape(TOY["width"], positions), original.T),
258 )
259
260 text = next(
261 layer for layer in layers if layer.name.endswith("position_embedding.weight")
262 )
263 table = tensors[text.first_tensor]
264 check(
265 f"the text table stays [{TOY['context']}, width]",
266 list(table.shape) == [TOY["context"], TOY["width"]],
267 )
268 check(
269 "unchanged, because the host reads it",
270 np.allclose(table, inits["text_model.embeddings.position_embedding.weight"]),
271 )
272
273 embedding = next(layer for layer in layers if layer.op == "Embed8")
274 check("the token embedding is a pair, not a triple", embedding.tensor_count == 2)
275 kernel, scale = tensors[embedding.first_tensor: embedding.first_tensor + 2]
276 check(
277 f"[{TOY['vocab']}, width, 1, 1] int8",
278 list(kernel.shape) == [TOY["vocab"], TOY["width"], 1, 1] and kernel.dtype == np.int8,
279 )
280 check("with one scale per row, which is per token", scale.shape == (TOY["vocab"],))
281
282
283def test_the_digest_covers_the_order() -> None:
284 print("the digest:")
285 layers, _ = maml_convert.collect_tinyclip(toy_export(TOY), TOY)
286 before = maml_convert.layer_table_digest(layers)
287 # A key is what the Rust hardcodes about a layer, not its name, so the pair swapped here has to
288 # differ in shape. Two `[width]` layer norms have the same key and are interchangeable in the
289 # digest, which is correct: swapping them changes nothing the forward pass can observe.
290 q_proj = next(i for i, layer in enumerate(layers) if layer.name.endswith("q_proj"))
291 fc1 = next(i for i, layer in enumerate(layers) if layer.name.endswith("fc1"))
292 swapped = list(layers)
293 swapped[q_proj], swapped[fc1] = swapped[fc1], swapped[q_proj]
294 check("a reordered pair changes it", maml_convert.layer_table_digest(swapped) != before)
295 check("the same table does not", maml_convert.layer_table_digest(list(layers)) == before)
296 # The synthesised biases are in the keys, so an export that grew one is not read as this table.
297 keys = "\n".join(layer.key() for layer in layers)
298 check("the three synthesised biases are recorded", keys.count("b0=synthesised") == 3)
299
300
301def main() -> int:
302 test_the_inventory_is_the_real_architecture()
303 test_a_transposed_export_is_refused()
304 test_the_table_order_is_the_contract()
305 test_a_projection_is_transposed_and_the_conv_is_not()
306 test_the_position_tables_go_opposite_ways()
307 test_the_digest_covers_the_order()
308 print(f"\n{passed} passed, {failed} failed")
309 return 1 if failed else 0
310
311
312if __name__ == "__main__":
313 raise SystemExit(main())