Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / gemma4_vision_parity.py
gemma4_vision_parity.py314 lines · 13.5 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Golden for Gemma 4's vision tower: onnxruntime's answer on a reproducible image. |
| 3 | |
| 4 | `examples/check_gemma4_vision_parity.rs` reads what this writes. Nothing else in the port |
| 5 | compares the vision tower's *numbers* against the export they came from - the layout tests check |
| 6 | that 637 tensors are declared in the order the converter writes them, which a transposed read |
| 7 | satisfies perfectly. |
| 8 | |
| 9 | # The image is generated, not loaded |
| 10 | |
| 11 | Both sides build the same pixels from `synthetic_pixel` below, so the golden carries no image and |
| 12 | the two cannot drift. The pattern is a hash rather than a gradient because a linear ramp is |
| 13 | nearly rank-one, and a rank-one input hides exactly the errors this is looking for. |
| 14 | |
| 15 | # The image is not square, deliberately |
| 16 | |
| 17 | A patch has a row and a column, and they are used four separate ways: two learned position |
| 18 | tables, and two independent rotary blocks inside every head. On a square grid, swapping either |
| 19 | pair changes nothing that any shape check or any norm would notice. On a 33x18 grid it changes |
| 20 | everything. See `nets::gemma4_vision::COLUMN_POSITIONS`. |
| 21 | |
| 22 | # The control is the point |
| 23 | |
| 24 | The device runs int4 weights and the export runs fp16 ones, so the two cannot agree closely and |
| 25 | the interesting question is never "how close is it" but "is it as close as four bits allow". This |
| 26 | runs the reference twice - as exported, and with every linear round-tripped through the |
| 27 | converter's own `quantise_per_block` - and writes both. The second is the bar. |
| 28 | |
| 29 | Without it the numbers are unreadable. The tower's output lands at cosine 0.95 against the exact |
| 30 | reference no matter what, because sixteen layers amplify four-bit noise; measured against the |
| 31 | int4 reference instead, a correct device sits far higher. |
| 32 | |
| 33 | # What it writes |
| 34 | |
| 35 | layer_in_0 .. layer_in_15 four probe patches each, 768 wide |
| 36 | tower_out the tower before pooling |
| 37 | pooled_in what reaches the final norm |
| 38 | image_features the whole output, [soft_tokens, 1536] |
| 39 | |
| 40 | each with a `_rows` list of which patches were probed and an `_int4` control. The per-layer |
| 41 | entries are four patches rather than the whole map because the whole map is 1.7 M floats a layer, |
| 42 | and four is enough to bisect: an error of composition moves every patch. |
| 43 | |
| 44 | python scripts/ml/gemma4_vision_parity.py vision_encoder_fp16.onnx \\ |
| 45 | -o vision_golden.json --width 1600 --height 900 --soft-tokens 70 |
| 46 | """ |
| 47 | import argparse |
| 48 | import json |
| 49 | import math |
| 50 | import os |
| 51 | import sys |
| 52 | |
| 53 | import numpy as np |
| 54 | import onnx |
| 55 | import onnxruntime as ort |
| 56 | from onnx import numpy_helper |
| 57 | |
| 58 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 59 | from maml_convert import I4_BLOCK, quantise_per_block # noqa: E402 |
| 60 | |
| 61 | PATCH = 16 |
| 62 | POOL = 3 |
| 63 | SIDE_MULTIPLE = PATCH * POOL |
| 64 | LAYERS = 16 |
| 65 | D_MODEL = 768 |
| 66 | |
| 67 | |
| 68 | def synthetic_pixel(y: int, x: int, channel: int) -> int: |
| 69 | """A reproducible byte for pixel `(y, x)`, channel `(0, 1, 2)` = `(r, g, b)`. |
| 70 | |
| 71 | Must stay bit-identical to `synthetic_pixel` in `check_gemma4_vision_parity.rs`. Everything |
| 72 | is masked to 32 bits so Python's unbounded integers behave like Rust's `u32`. |
| 73 | """ |
| 74 | mask = 0xFFFFFFFF |
| 75 | h = (y * 73_856_093) ^ (x * 19_349_663) ^ (channel * 83_492_791) |
| 76 | h &= mask |
| 77 | h ^= h >> 13 |
| 78 | h = (h * 1_274_126_177) & mask |
| 79 | h ^= h >> 16 |
| 80 | return h & 0xFF |
| 81 | |
| 82 | |
| 83 | def aspect_preserving_size(height, width, max_patches): |
| 84 | """`get_aspect_ratio_preserving_size` from `Gemma4ImageProcessor`, ported verbatim.""" |
| 85 | target_px = max_patches * PATCH**2 |
| 86 | factor = math.sqrt(target_px / (height * width)) |
| 87 | target_height = int(math.floor(factor * height / SIDE_MULTIPLE)) * SIDE_MULTIPLE |
| 88 | target_width = int(math.floor(factor * width / SIDE_MULTIPLE)) * SIDE_MULTIPLE |
| 89 | max_side = (max_patches // POOL**2) * SIDE_MULTIPLE |
| 90 | if target_height == 0 and target_width == 0: |
| 91 | raise SystemExit(f"{width}x{height} resizes to nothing") |
| 92 | if target_height == 0: |
| 93 | target_height = SIDE_MULTIPLE |
| 94 | target_width = min(int(math.floor(width / height)) * SIDE_MULTIPLE, max_side) |
| 95 | elif target_width == 0: |
| 96 | target_width = SIDE_MULTIPLE |
| 97 | target_height = min(int(math.floor(height / width)) * SIDE_MULTIPLE, max_side) |
| 98 | return target_height, target_width |
| 99 | |
| 100 | |
| 101 | def build_inputs(rows, cols): |
| 102 | """`pixel_values [1, T, 768]` in [0, 1] and `pixel_position_ids [1, T, 2]` as (column, row). |
| 103 | |
| 104 | The patchify is `convert_image_to_patches`: `(C, H, W)` reshaped to `(C, nph, 16, npw, 16)` |
| 105 | then permuted `(1, 3, 2, 4, 0)`, so a patch's 768 values run y, then x, then channel. |
| 106 | """ |
| 107 | height, width = rows * PATCH, cols * PATCH |
| 108 | y = np.arange(height, dtype=np.int64)[:, None, None] |
| 109 | x = np.arange(width, dtype=np.int64)[None, :, None] |
| 110 | c = np.arange(3, dtype=np.int64)[None, None, :] |
| 111 | mask = 0xFFFFFFFF |
| 112 | h = ((y * 73_856_093) ^ (x * 19_349_663) ^ (c * 83_492_791)) & mask |
| 113 | h ^= h >> 13 |
| 114 | h = (h * 1_274_126_177) & mask |
| 115 | h ^= h >> 16 |
| 116 | image = (h & 0xFF).astype(np.float32) / 255.0 # (H, W, C) |
| 117 | |
| 118 | patches = image.reshape(rows, PATCH, cols, PATCH, 3).transpose(0, 2, 1, 3, 4) |
| 119 | pixel_values = patches.reshape(rows * cols, PATCH * PATCH * 3).astype(np.float32) |
| 120 | |
| 121 | # meshgrid(arange(width), arange(height), indexing="xy") stacked last: (column, row). |
| 122 | columns = np.tile(np.arange(cols, dtype=np.int64), rows) |
| 123 | rows_ids = np.repeat(np.arange(rows, dtype=np.int64), cols) |
| 124 | position_ids = np.stack([columns, rows_ids], axis=-1) |
| 125 | return pixel_values[None, ...], position_ids[None, ...] |
| 126 | |
| 127 | |
| 128 | def numbered(node, prefix): |
| 129 | """The index in `prefix`, `prefix_1`, ... - the same anchor `collect_gemma4_vision` uses.""" |
| 130 | name = (node.name or "").replace("_fused_rms_norm/node_mean", "node_mean") |
| 131 | if not name.startswith(prefix): |
| 132 | return None |
| 133 | tail = name[len(prefix):] |
| 134 | if tail == "": |
| 135 | return 0 |
| 136 | return int(tail[1:]) if tail.startswith("_") and tail[1:].isdigit() else None |
| 137 | |
| 138 | |
| 139 | def trace_points(model): |
| 140 | """`{label: tensor_name}`: the input to layers 0, 1 and 8, the tower's output, the pooled map. |
| 141 | |
| 142 | Layer `i`'s seven norms are `node_mean_{7i}` .. `node_mean_{7i+6}`, so the input to layer `i` |
| 143 | is the input of `node_mean_{7i}` - the same numbering anchor `collect_gemma4_vision` relies |
| 144 | on. `node_mean_{7 * LAYERS}` is the final norm, whose input is already **pooled**, so the |
| 145 | tower's own output has to come from the masked fill that feeds the pooling instead. |
| 146 | """ |
| 147 | norms, masked_fill = {}, None |
| 148 | for node in model.graph.node: |
| 149 | if node.op_type == "SimplifiedLayerNormalization": |
| 150 | index = numbered(node, "node_mean") |
| 151 | if index is not None: |
| 152 | norms[index] = node.input[0] |
| 153 | elif node.op_type == "Where" and (node.name or "").endswith("masked_fill"): |
| 154 | masked_fill = node.input[2] |
| 155 | if len(norms) != LAYERS * 7 + 1: |
| 156 | raise SystemExit( |
| 157 | f"{len(norms)} norms, not {LAYERS * 7 + 1} - the node numbering has changed" |
| 158 | ) |
| 159 | if masked_fill is None: |
| 160 | raise SystemExit("no masked_fill node - the pooling tail has changed") |
| 161 | points = {f"layer_in_{i}": norms[7 * i] for i in range(LAYERS)} |
| 162 | points["tower_out"] = masked_fill |
| 163 | points["pooled_in"] = norms[7 * LAYERS] |
| 164 | return points |
| 165 | |
| 166 | |
| 167 | def quantise_in_place(model): |
| 168 | """Replace every linear's weight with its own int4 round-trip. Returns how many. |
| 169 | |
| 170 | This is the control, and it is the whole reason this script is worth running. The device has |
| 171 | int4 weights and the export has fp16 ones, so a cosine of 0.95 at the output could be a |
| 172 | composition error or could be four bits over sixteen layers - and the per-layer bisect cannot |
| 173 | separate them, because both grow with depth. |
| 174 | |
| 175 | Running the reference a second time like this puts a number on what four bits alone costs. A |
| 176 | device that lands on the same number is right; one that lands short of it is not. |
| 177 | |
| 178 | The two projections at the ends are **skipped**, because the converter leaves them at fp16 - |
| 179 | see `collect_gemma4_vision.dense`. A control that quantised them would be a bar the device is |
| 180 | not trying to meet, and the device would appear to beat it. |
| 181 | """ |
| 182 | init = {i.name: i for i in model.graph.initializer} |
| 183 | ends = {"node_linear", f"node_linear_{LAYERS * 7 + 1}"} |
| 184 | touched = 0 |
| 185 | for node in model.graph.node: |
| 186 | if node.op_type not in ("MatMul", "Gemm"): |
| 187 | continue |
| 188 | name = node.name or "" |
| 189 | if not name.startswith("node_linear") or name in ends: |
| 190 | continue |
| 191 | for weight in node.input: |
| 192 | if weight not in init: |
| 193 | continue |
| 194 | matrix = numpy_helper.to_array(init[weight]).astype(np.float32) |
| 195 | if matrix.ndim != 2: |
| 196 | continue |
| 197 | # The converter quantises the `[out, in]` kernel, so the blocks run along the |
| 198 | # contraction axis. A `Gemm` with `transB` already holds that; a `MatMul` does not. |
| 199 | already = node.op_type == "Gemm" |
| 200 | kernel = matrix if already else matrix.T |
| 201 | codes, scale = quantise_per_block(kernel) |
| 202 | flat = kernel.reshape(kernel.shape[0], -1) |
| 203 | wide = np.repeat(scale, I4_BLOCK, axis=1)[:, : flat.shape[1]] |
| 204 | back = (np.asarray(codes).astype(np.float32).reshape(flat.shape) * wide) |
| 205 | back = back.reshape(kernel.shape) |
| 206 | init[weight].CopyFrom( |
| 207 | numpy_helper.from_array((back if already else back.T).astype(np.float16), weight) |
| 208 | ) |
| 209 | touched += 1 |
| 210 | return touched |
| 211 | |
| 212 | |
| 213 | def collect(model, points, pixel_values, position_ids): |
| 214 | """`{label: array}` for every trace point plus `image_features`, from one session.""" |
| 215 | existing = {o.name for o in model.graph.output} |
| 216 | for tensor in points.values(): |
| 217 | if tensor not in existing: |
| 218 | # Name only: onnxruntime infers the type, and asserting one here would just be a |
| 219 | # second place to get fp16-versus-fp32 wrong. |
| 220 | model.graph.output.add().name = tensor |
| 221 | existing.add(tensor) |
| 222 | session = ort.InferenceSession( |
| 223 | model.SerializeToString(), providers=["CPUExecutionProvider"] |
| 224 | ) |
| 225 | names = [o.name for o in session.get_outputs()] |
| 226 | raw = dict( |
| 227 | zip(names, session.run(names, { |
| 228 | "pixel_values": pixel_values, |
| 229 | "pixel_position_ids": position_ids, |
| 230 | })) |
| 231 | ) |
| 232 | out = {"image_features": np.asarray(raw["image_features"], dtype=np.float32)} |
| 233 | for label, tensor in points.items(): |
| 234 | out[label] = np.asarray(raw[tensor], dtype=np.float32).reshape(-1, D_MODEL) |
| 235 | return out |
| 236 | |
| 237 | |
| 238 | def cosine(a, b): |
| 239 | a = np.asarray(a, dtype=np.float64).ravel() |
| 240 | b = np.asarray(b, dtype=np.float64).ravel() |
| 241 | return float(a @ b / max(np.linalg.norm(a) * np.linalg.norm(b), 1e-30)) |
| 242 | |
| 243 | |
| 244 | def main(): |
| 245 | ap = argparse.ArgumentParser(description=__doc__) |
| 246 | ap.add_argument("onnx", help="vision_encoder_fp16.onnx") |
| 247 | ap.add_argument("-o", "--out", required=True) |
| 248 | ap.add_argument("--width", type=int, default=1600) |
| 249 | ap.add_argument("--height", type=int, default=900) |
| 250 | ap.add_argument("--soft-tokens", type=int, default=70) |
| 251 | ap.add_argument( |
| 252 | "--no-control", |
| 253 | action="store_true", |
| 254 | help="skip the int4 reference, which is most of the runtime and all of the value", |
| 255 | ) |
| 256 | args = ap.parse_args() |
| 257 | |
| 258 | max_patches = args.soft_tokens * POOL**2 |
| 259 | target_h, target_w = aspect_preserving_size(args.height, args.width, max_patches) |
| 260 | rows, cols = target_h // PATCH, target_w // PATCH |
| 261 | print(f"{args.width}x{args.height} -> {target_w}x{target_h} px = {cols}x{rows} patches") |
| 262 | print(f"{rows * cols} patches, {(rows // POOL) * (cols // POOL)} soft tokens") |
| 263 | if rows == cols: |
| 264 | print("WARNING: a square grid cannot tell a row from a column", file=sys.stderr) |
| 265 | |
| 266 | pixel_values, position_ids = build_inputs(rows, cols) |
| 267 | model = onnx.load(args.onnx) |
| 268 | points = trace_points(model) |
| 269 | print("tracing " + ", ".join(f"{k}={v}" for k, v in points.items())) |
| 270 | |
| 271 | print("running the reference as exported") |
| 272 | exact = collect(model, points, pixel_values, position_ids) |
| 273 | |
| 274 | control = None |
| 275 | if not args.no_control: |
| 276 | touched = quantise_in_place(model) |
| 277 | print(f"running it again with {touched} weights round-tripped through int4") |
| 278 | control = collect(model, points, pixel_values, position_ids) |
| 279 | |
| 280 | golden = { |
| 281 | "rows": rows, |
| 282 | "cols": cols, |
| 283 | "soft_tokens": (rows // POOL) * (cols // POOL), |
| 284 | "image_features": exact["image_features"].reshape(-1).tolist(), |
| 285 | } |
| 286 | if control is not None: |
| 287 | golden["image_features_int4"] = control["image_features"].reshape(-1).tolist() |
| 288 | |
| 289 | print() |
| 290 | print(f"{'tensor':<14}{'rows':>8}{'rms':>12}{'int4 vs exact':>16}") |
| 291 | for label in points: |
| 292 | value = exact[label] |
| 293 | probes = sorted({0, 1, min(7, value.shape[0] - 1), value.shape[0] - 1}) |
| 294 | golden[label] = value[probes].reshape(-1).tolist() |
| 295 | golden[f"{label}_rows"] = probes |
| 296 | note = "" |
| 297 | if control is not None: |
| 298 | golden[f"{label}_int4"] = control[label][probes].reshape(-1).tolist() |
| 299 | note = f"{cosine(control[label], value):>16.6f}" |
| 300 | print(f"{label:<14}{value.shape[0]:>8}{float(np.sqrt((value**2).mean())):>12.4f}{note}") |
| 301 | if control is not None: |
| 302 | bar = cosine(control["image_features"], exact["image_features"]) |
| 303 | print(f"{'image_features':<14}{exact['image_features'].shape[0]:>8}{'':>12}{bar:>16.6f}") |
| 304 | print() |
| 305 | print(f"four bits alone cost {1 - bar:.4f} of cosine at the output.") |
| 306 | print("A device that lands here is right; one that lands short of it is not.") |
| 307 | |
| 308 | with open(args.out, "w", encoding="utf-8") as f: |
| 309 | json.dump(golden, f) |
| 310 | print(f"wrote {args.out}") |
| 311 | |
| 312 | |
| 313 | if __name__ == "__main__": |
| 314 | main() |