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

Modern-Apps.git / scripts / ml / gemma4_text_parity.py

gemma4_text_parity.py196 lines · 9.2 KiBRaw
1#!/usr/bin/env python3
2"""Golden for Gemma 4's text decoder: litertlm's own answer on a short prompt.
3
4`examples/check_gemma4_parity.rs` reads what this writes. Nothing else in the
5port compares the text tower's *numbers* against the model they came from -
6the layout tests check that 999 tensors are declared in the order the
7converter writes them, which a transposed read satisfies perfectly.
8
9# Reference choice
10
11The plan lists candidates in order: the ExecuTorch `.pte` via an
12optimum-executorch runner, the litertlm bundle via its python engine, the
13artisan TFLite via ai-edge-litert, else cross-check vs base sections. The
14first two are not runnable on this host (no optimum, no litertlm engine
15build); what IS runnable is the next best thing, and it is exact, not a
16fallback: the BASE bundle's own Sections 2 (embedder) + 3 (per-layer
17embedder) + 10 (prefill_decode), driven through ai-edge-litert's interpreter.
18`litertlm_to_maml.py` reads those same sections, so this is the reference the
19converter claims to transcribe.
20
21# Drive protocol (read off litertlm's own executor)
22
23`runtime/executor/litert_compiled_model_executor_utils.cc`,
24`FillSingleBufferCacheParamTensor`: `param_tensor = [start, end, end, 0...]`
25with `end = start + update_length`. `FillAttentionMask`: bool mask memset 0,
26then the attended `[causal_start, causal_end)` range filled - True attends.
27The prompt is short (6 tokens, inside every sliding window), so a plain
28causal mask is exactly right for both layer types. KV caches start zeroed
29and are carried step to step; `input_pos = [position]`.
30
31# What it writes
32
33 logits_golden.json {"tokens": [...], "top_ids": [...10], "top_logits": [...10]}
34 from the last decode step's [1,1,262144] logits.
35 trace.json {"ple_combined": [...]} for the Rust bisect.
36
37 Trace coverage note: the Rust harness also looks for `l0_out`/`l1_out`
38 (hidden states after layers 0/1) and prints "not in the trace file" when
39 absent. Those are layer outputs, which Section 10 does not expose - its
40 intermediates are not readable through the interpreter API, and rebuilding
41 the 818 MB flatbuffer with extra outputs is not worth it for a bisect aid.
42 `ple_combined` is the one that arbitrates the embed-assembly suspect, and
43 any composition error inside the layers moves the logits ranking, which the
44 gate catches. If the gate fails, layer outputs can be lifted by naming the
45 `layer_N.post_qkv/add2` tensors (ids 453/531) as extra model outputs.
46
47 `ple_combined` is computed in numpy from the reference's own S2/S3 outputs
48 plus the shared-projection weights from the file (same dequantisation the
49 converter uses - the check this arbitrates is the gather + combination,
50 not the dequant): projected = W @ hidden, grouped RMS norm over 35x256,
51 plus 16x the S3 gather (t307), over sqrt(2) (t304). It matches the `per_layer`
52 the Rust `Trace { layers: 0 }` path returns.
53
54 python scripts/ml/gemma4_text_parity.py -o build/gemma4
55"""
56import argparse
57import json
58import os
59
60import numpy as np
61from ai_edge_litert.interpreter import Interpreter
62from tokenizers import Tokenizer
63
64import os
65import sys
66
67sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
68from litertlm_to_maml import LitertlmReader
69from s10_to_maml import S10Reader
70
71# A short text-only prompt, inside every sliding window so one causal mask
72# serves both layer types. Tokenizer already prepends <bos> (id 2).
73PROMPT = "The capital of France is"
74CONTEXT = 32003
75
76EPSILON = 1e-6
77
78
79def load_interpreter(path):
80 it = Interpreter(model_path=path)
81 it.allocate_tensors()
82 return it
83
84
85def ple_combined(hidden, embedded, proj_w, proj_norm):
86 """The per-layer combination exactly as `gemma4::build` computes it.
87
88 `hidden` [1536] is S2's embedding; `embedded` [35, 256] is S3's gather;
89 the projection/norm come from the file. Returns [8960].
90
91 Proven from the S10 graph walk (t319 <- t30 input): PLE slice =
92 (grouped_rmsnorm(W @ hidden) + 16 x S3_gather) / sqrt(2), with x16 =
93 t307 on the gather path and 1/sqrt(2) = t304. There is no sqrt(1536)
94 anywhere in S10 (full-file constant scan finds only 16.0 and 1/sqrt(2));
95 /sqrt(1536) before a grouped RMS-norm would be computation-neutral
96 (uniform scale erased by the norm) but spec-divergent, so it is dropped.
97 Track-3 evidence: S10-table + x16-on-gather vs live t318 = 0.999974
98 (x16-on-normed 0.847, no-x16 0.867).
99 """
100 projected = (proj_w.astype(np.float64) @ hidden.astype(np.float64))
101 grouped = projected.reshape(35, 256)
102 var = (grouped ** 2).mean(axis=1, keepdims=True)
103 normed = grouped / np.sqrt(var + EPSILON) * proj_norm.reshape(1, 256)
104 combined = 16.0 * embedded.reshape(35, 256) + normed
105 return (combined / np.sqrt(2.0)).reshape(-1)
106
107
108def main():
109 ap = argparse.ArgumentParser(description=__doc__)
110 ap.add_argument("-o", "--out", required=True, help="output dir")
111 ap.add_argument("--tokenizer", default="analysis/et-gemma/tokenizer.json")
112 ap.add_argument("--s2", default="analysis/base-sections/Section2_TFLiteModel_tf_lite_embedder.tflite")
113 ap.add_argument("--s3", default="analysis/base-sections/Section3_TFLiteModel_tf_lite_per_layer_embedder.tflite")
114 ap.add_argument("--s10", default="analysis/base-sections/Section10_TFLiteModel_tf_lite_prefill_decode.tflite")
115 ap.add_argument("--weights", default=None,
116 help="optional artisan text decoder holding the shared "
117 "projection/norm (legacy path: artisan table scores only "
118 "0.42 vs live t318 — different checkpoint). When omitted "
119 "(default), the trace uses S10's OWN t312/t305 so the "
120 "S10-control pair is S10-self-consistent (S10 table + "
121 "x16-gather vs live t318 = 0.99997).")
122 args = ap.parse_args()
123 os.makedirs(args.out, exist_ok=True)
124
125 tokens = Tokenizer.from_file(args.tokenizer).encode(PROMPT).ids
126 print(f"prompt {PROMPT!r} -> {len(tokens)} tokens {tokens}")
127
128 s2 = Interpreter(model_path=args.s2).get_signature_runner("embedder")
129 s3 = Interpreter(model_path=args.s3).get_signature_runner("per_layer_embedder")
130 if args.weights:
131 # Legacy artisan path (kept for the artisan-file golden only): the
132 # artisan PLE table is a different checkpoint from S10's t312
133 # (full-cos ~0.0005), so its trace can never match live t318.
134 rdr = LitertlmReader(args.weights)
135 proj_w = rdr.dequant8("transformer.embedder.per_layer_model_projection.w", 8960, 1536)
136 proj_norm = rdr.f32("transformer.embedder.per_layer_projection_norm.scale")
137 else:
138 s10rdr = S10Reader(args.s10)
139 proj_w = s10rdr.dequant8(312, 8960, 1536)
140 proj_norm = s10rdr.f32(305)
141 # True-carry drive (Track 11): the `decode` signature runner returns the
142 # UPDATED caches as dict outputs (`kv_cache_k_0`, ...), mirroring
143 # analysis/live_kv.py. The old raw-interpreter loop carried via
144 # get_tensor() on INPUT indices, which reads back the just-fed values
145 # (no-op: fed nonzero returns bit-identical), so caches stayed zero all
146 # 6 steps and the golden (argmax 95375) was a zero-carry artifact. The
147 # runner-output path is deterministic (1.000000 across fresh runs).
148 dec = Interpreter(model_path=args.s10).get_signature_runner("decode")
149 in_details = dec.get_input_details()
150 cache_keys = [k for k in in_details if "kv_cache" in k]
151 cache = {}
152 for k in cache_keys:
153 cache[k] = np.zeros(list(in_details[k]["shape"]), np.int8)
154
155 logits = None
156 for step, token in enumerate(tokens):
157 emb = s2(token_ids=np.array([[token]], np.int32))["embeddings"]
158 ple = s3(token_ids=np.array([[token]], np.int32))["embeddings"]
159 if step == len(tokens) - 1:
160 last_hidden = emb.ravel().copy()
161 last_embedded = ple.ravel().copy()
162 mask = np.zeros([1, 1, 1, CONTEXT], bool)
163 mask[0, 0, 0, : step + 1] = True
164 feed = dict(cache)
165 feed["embeddings"] = emb
166 feed["per_layer_embeddings"] = ple
167 feed["input_pos"] = np.array([step], np.int32)
168 feed["mask"] = mask
169 feed["param_tensor"] = np.array([[[[step, step + 1, step + 1, 0, 0, 0, 0]]]], np.int32)
170 out = dec(**feed)
171 for k in cache_keys:
172 if k in out:
173 cache[k] = np.asarray(out[k])
174 logits = np.asarray(out["logits"]).ravel().astype(np.float64)
175 top = np.argsort(logits)[-3:]
176 print(f" step {step} token {token}: top {top.tolist()}")
177
178 order = np.argsort(logits)[::-1][:10]
179 golden = {
180 "tokens": tokens,
181 "top_ids": [int(i) for i in order],
182 "top_logits": [float(logits[i]) for i in order],
183 }
184 with open(os.path.join(args.out, "logits_golden.json"), "w") as f:
185 json.dump(golden, f)
186 print(f"argmax {order[0]} logit {logits[order[0]]:.4f}")
187
188 trace = {"ple_combined": ple_combined(last_hidden, last_embedded, proj_w, proj_norm).tolist()}
189 print(f"trace shapes: ple {len(trace['ple_combined'])}")
190 with open(os.path.join(args.out, "trace.json"), "w") as f:
191 json.dump(trace, f)
192 print(f"wrote {args.out}/logits_golden.json + trace.json")
193
194
195if __name__ == "__main__":
196 raise SystemExit(main())