Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / s10_to_maml.py
s10_to_maml.py693 lines · 33.8 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """S10-sourced control conversion: transcribe Section 10's OWN transformer |
| 3 | weights (same layout/norms/scales the golden ran) into a MAML, to decide |
| 4 | whether the parity failure is in the ARTISAN weight decode or the runtime. |
| 5 | |
| 6 | Also emits the S10 embed file: S2-dump working table + S10 head table |
| 7 | (t2698, raw-scale `embedder.decode` composite) + shared projection/norm |
| 8 | from S10's own tensors + 35 per-layer mmap tables. The head table is the |
| 9 | piece the artisan bundle cannot supply (its 2-bit embedder packing is a |
| 10 | different checkpoint's arrangement); the tied head reads it raw-scale |
| 11 | (see nets::gemma4::EMBED_GAIN). |
| 12 | |
| 13 | Usage: |
| 14 | GEMMA4_EMBED_DUMP=analysis/maml-rebuild/embed_s2_fp32.bin \ |
| 15 | python scripts/ml/s10_to_maml.py -o build/gemma4-s10 --print-digest |
| 16 | (--text-only writes gemma4_text.maml alone and needs no dump.) |
| 17 | |
| 18 | Slim embed (the shipped file): |
| 19 | python scripts/ml/s10_to_maml.py -o build/gemma4-release \ |
| 20 | --slim-embed build/gemma4/gemma4_embed.maml |
| 21 | copies the token table triple (0-2) and the 35 per-layer int4 tables |
| 22 | (7+i*3) byte-for-byte out of a full embed file, with no S10 read and no |
| 23 | re-quantisation. SHARED_PROJ/norm (3-6) become four one-element fp16 |
| 24 | placeholders so every index the runtime reads holds (nets::gemma4::embed:: |
| 25 | SLIM_TENSORS, 112 tensors): the per-layer combine reads the text file's |
| 26 | copy (the 1094-tensor gemma4_text.maml, nets::gemma4::COMBINE_PROJ), and |
| 27 | the head table + both head-chunk copies are dropped because |
| 28 | gemma4_head.maml carries the head. ~1.4 GB instead of 3.6 GB. |
| 29 | Then: |
| 30 | cargo run --offline --release -p modelrunner --example check_gemma4_parity -- \ |
| 31 | build/gemma4-s10/gemma4_text.maml build/gemma4-s10/gemma4_embed.maml \ |
| 32 | build/gemma4/logits_golden.json build/gemma4/trace.json |
| 33 | |
| 34 | PASS => artisan payloads are the problem (port S10's tables). |
| 35 | FAIL => the runtime/net is the problem (same reading convention both sides). |
| 36 | """ |
| 37 | import argparse |
| 38 | import os |
| 39 | import sys |
| 40 | |
| 41 | import numpy as np |
| 42 | |
| 43 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 44 | import maml_convert as mc |
| 45 | from litertlm_to_maml import emit4, emit8, emit_vec |
| 46 | |
| 47 | import tflite |
| 48 | from tflite.Model import Model |
| 49 | |
| 50 | S10 = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'analysis', |
| 51 | 'base-sections', 'Section10_TFLiteModel_tf_lite_prefill_decode.tflite') |
| 52 | |
| 53 | # Base-bundle Section 3 (per-layer embedder). Its 35 composite tables |
| 54 | # (tensors 10..44 -> buffers 11..45, [262144,256] signed nibbles + 1 F32 |
| 55 | # scale/row, zp all 0) decode cos 1.000000 vs the live S3 signature runner, |
| 56 | # so they are the exact source the golden uses. Preferred over the artisan |
| 57 | # file when present (the artisan tables are a different checkpoint's |
| 58 | # arrangement: global XOR-2 code multisets, ~0.30 position-wise agreement). |
| 59 | S3 = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'analysis', |
| 60 | 'base-sections', 'Section3_TFLiteModel_tf_lite_per_layer_embedder.tflite') |
| 61 | |
| 62 | # GPU tied-head chunking (2026-09-26): HEAD_SPLITS rank-4 fp16 chunks of the |
| 63 | # head table, each small enough to fit one Vulkan segment window (~96 MiB at |
| 64 | # guaranteed 128 MiB maxStorageBufferRange). 16 x 16384 x 1536 x 2B ~= 50 MB |
| 65 | # per chunk. Overridable via GEMMA4_HEAD_SPLITS for devices whose |
| 66 | # maxStorageBufferRange queries smaller (raise the count, shrink the chunk). |
| 67 | HEAD_SPLITS = int(os.environ.get('GEMMA4_HEAD_SPLITS', '16')) |
| 68 | |
| 69 | |
| 70 | def m_OperatorCode(sg, o): |
| 71 | raise NotImplementedError |
| 72 | |
| 73 | |
| 74 | class S10Reader: |
| 75 | """Section-10 tensor access with TFLite-native int4 reading.""" |
| 76 | |
| 77 | def __init__(self, path): |
| 78 | with open(path, 'rb') as f: |
| 79 | self.sec = f.read() |
| 80 | self.model = Model.GetRootAs(bytearray(self.sec), 0) |
| 81 | self.sg = self.model.Subgraphs(0) |
| 82 | self.tensors = {} |
| 83 | for ti in range(self.sg.TensorsLength()): |
| 84 | t = self.sg.Tensors(ti) |
| 85 | self.tensors[t.Name().decode('utf-8')] = ti |
| 86 | |
| 87 | def const(self, ti): |
| 88 | t = self.sg.Tensors(ti) |
| 89 | b = self.model.Buffers(t.Buffer()) |
| 90 | return bytes(b.DataAsNumpy()) |
| 91 | |
| 92 | def f32(self, ti): |
| 93 | return np.frombuffer(self.const(ti), dtype=np.float32).copy() |
| 94 | |
| 95 | def dequant4(self, ti, rows, cols): |
| 96 | t = self.sg.Tensors(ti) |
| 97 | raw = np.frombuffer(self.const(ti), dtype=np.uint8) |
| 98 | assert raw.size * 2 >= rows * cols, (ti, raw.size, rows, cols) |
| 99 | lo = (raw & 0xF).astype(np.float32) |
| 100 | hi = ((raw >> 4) & 0xF).astype(np.float32) |
| 101 | flat = np.empty(raw.size * 2, dtype=np.float32) |
| 102 | flat[0::2] = lo |
| 103 | flat[1::2] = hi |
| 104 | flat = np.where(flat >= 8, flat - 16, flat).reshape(rows, cols) |
| 105 | q = t.Quantization() |
| 106 | s = np.array([q.Scale(i) for i in range(q.ScaleLength())], dtype=np.float32) |
| 107 | assert s.size == rows, (ti, s.size, rows) |
| 108 | out = flat * s[:, None] |
| 109 | m = float(np.abs(out).mean()) |
| 110 | if not (1e-6 < m < 10.0): |
| 111 | print(f'WARN t{ti}: mean abs {m:.2e}') |
| 112 | return out |
| 113 | |
| 114 | def dequant2(self, ti, rows, cols): |
| 115 | """2-bit table with the head codebook ([0,+s,-2s,-s]) -> fp32.""" |
| 116 | t = self.sg.Tensors(ti) |
| 117 | raw = np.frombuffer(self.const(ti), dtype=np.uint8) |
| 118 | assert raw.size * 4 >= rows * cols, (ti, raw.size, rows, cols) |
| 119 | v = np.empty(raw.size * 4, dtype=np.float64) |
| 120 | for k in range(4): |
| 121 | v[k::4] = ((raw >> (2 * k)) & 0x3).astype(np.float64) |
| 122 | v = v[:rows * cols].reshape(rows, cols) |
| 123 | codebook = np.array([0.0, 1.0, -2.0, -1.0]) |
| 124 | v = codebook[v.astype(int)] |
| 125 | q = t.Quantization() |
| 126 | s = np.array([q.Scale(i) for i in range(q.ScaleLength())], dtype=np.float32) |
| 127 | assert s.size == rows, (ti, s.size, rows) |
| 128 | return (v * s[:, None]).astype(np.float32) |
| 129 | |
| 130 | def dequant8(self, ti, rows, cols): |
| 131 | t = self.sg.Tensors(ti) |
| 132 | raw = np.frombuffer(self.const(ti), dtype=np.int8).astype(np.float32) |
| 133 | raw = raw[:rows * cols].reshape(rows, cols) |
| 134 | q = t.Quantization() |
| 135 | s = np.array([q.Scale(i) for i in range(q.ScaleLength())], dtype=np.float32) |
| 136 | assert s.size == rows, (ti, s.size, rows) |
| 137 | return raw * s[:, None] |
| 138 | |
| 139 | |
| 140 | class S3Reader: |
| 141 | """Section-3 per-layer tables (tensors 10..44 -> buffers 11..45). |
| 142 | |
| 143 | Each composite is [262144,256] signed nibbles (lo-first) with 1 F32 |
| 144 | scale/row (zp all 0): table[i] = nibbles * scales. Proven cos 1.000000 |
| 145 | vs the live S3 `per_layer_embedder` runner on sampled tokens. |
| 146 | """ |
| 147 | |
| 148 | def __init__(self, path): |
| 149 | with open(path, 'rb') as f: |
| 150 | self.sec = f.read() |
| 151 | self.model = Model.GetRootAs(bytearray(self.sec), 0) |
| 152 | self.sg = self.model.Subgraphs(0) |
| 153 | |
| 154 | def table(self, index): |
| 155 | ti = 10 + index |
| 156 | t = self.sg.Tensors(ti) |
| 157 | b = self.model.Buffers(t.Buffer()) |
| 158 | raw = np.frombuffer(bytes(b.DataAsNumpy()), dtype=np.uint8) |
| 159 | assert raw.size >= 262144 * 128, (ti, raw.size) |
| 160 | raw = raw[:262144 * 128] |
| 161 | lo = (raw & 0xF).astype(np.float32) |
| 162 | hi = ((raw >> 4) & 0xF).astype(np.float32) |
| 163 | flat = np.empty(262144 * 256, dtype=np.float32) |
| 164 | flat[0::2] = lo |
| 165 | flat[1::2] = hi |
| 166 | flat = np.where(flat >= 8, flat - 16, flat).reshape(262144, 256) |
| 167 | q = t.Quantization() |
| 168 | s = np.array([q.Scale(i) for i in range(q.ScaleLength())], dtype=np.float32) |
| 169 | assert s.size == 262144, (ti, s.size) |
| 170 | return flat * s[:, None] |
| 171 | |
| 172 | |
| 173 | # tensor ids mapped in collect_text (verified against the graph walk). |
| 174 | class T: |
| 175 | # norms: (tensor id, len) |
| 176 | FINAL = 37 |
| 177 | PRE = 303 |
| 178 | QN = 300 |
| 179 | KN = 299 |
| 180 | POSTA = 280 |
| 181 | PREFF = None # filled per layer below |
| 182 | POSTFF = 40 |
| 183 | POSTPL = 39 |
| 184 | SKIP = 276 |
| 185 | SHARED_NORM = None # embed file (shared) |
| 186 | |
| 187 | |
| 188 | def fc_weight(rdr, layer, frag): |
| 189 | """Find the FC weight tensor id for layer's fragment (the FC op itself).""" |
| 190 | import re |
| 191 | sg = rdr.sg |
| 192 | pat = re.compile(rf'layer_{layer}/') |
| 193 | for oi in range(sg.OperatorsLength()): |
| 194 | o = sg.Operators(oi) |
| 195 | if rdr.model.OperatorCodes(o.OpcodeIndex()).BuiltinCode() != 9: # FULLY_CONNECTED |
| 196 | continue |
| 197 | outs = [o.Outputs(i) for i in range(o.OutputsLength())] |
| 198 | if not outs: |
| 199 | continue |
| 200 | nm = sg.Tensors(outs[0]).Name().decode('utf-8') |
| 201 | if not pat.search(nm) or frag not in nm: |
| 202 | continue |
| 203 | ins = [o.Inputs(i) for i in range(o.InputsLength())] |
| 204 | for ii in ins: |
| 205 | if ii < 0: |
| 206 | continue |
| 207 | t = sg.Tensors(ii) |
| 208 | if t.ShapeLength() == 2: |
| 209 | return ii |
| 210 | raise KeyError((layer, frag)) |
| 211 | |
| 212 | |
| 213 | def collect_text(rdr): |
| 214 | layers, tensors = [], [] |
| 215 | fid = mc.Fidelity() |
| 216 | D = 1536 |
| 217 | sg = rdr.sg |
| 218 | # final norm + rotary tables. The angle tables are read off S10's own |
| 219 | # `maybe_rope` div constants (NOT generated from theta: S10's full-layer |
| 220 | # table has only 64 nonzero freqs of 256 — theta 1e6 over head_dim 512 |
| 221 | # for those, zeros after — and generating 256 freqs rotates 192 channel |
| 222 | # pairs the reference leaves fixed, breaking every full layer's Q and K). |
| 223 | # S10 tensor ids: 296 (sliding, 128 freqs), 245 (full, 256 entries). |
| 224 | emit_vec(layers, tensors, 'transformer.final_norm.scale', rdr.f32(T.FINAL)) |
| 225 | for kind, dim, freq_ti in (('local', 256, 296), ('global', 512, 245)): |
| 226 | freq = rdr.f32(freq_ti).astype(np.float64) |
| 227 | assert freq.size == dim // 2, (kind, freq.size, dim) |
| 228 | pos = np.arange(16384, dtype=np.float64)[:, None] |
| 229 | ang = pos * freq[None, :] |
| 230 | table = np.concatenate([np.cos(ang), np.sin(ang)], axis=1).astype(np.float32) |
| 231 | tensors.append(table) |
| 232 | layers.append(mc.Layer(len(layers), 'Rotary', f'{kind}_rotary_table', |
| 233 | f'Rotary t={list(table.shape)} S10-freq', |
| 234 | len(tensors) - 1, 1)) |
| 235 | # Shared all-ones vectors: the gamma of S10's parameter-free value_norm |
| 236 | # (see nets::gemma4::ONE_SLIDING). Head-dim-wide: [256] and [512]. |
| 237 | emit_vec(layers, tensors, 'transformer.ones_sliding', np.ones(256, dtype=np.float32)) |
| 238 | emit_vec(layers, tensors, 'transformer.ones_full', np.ones(512, dtype=np.float32)) |
| 239 | # Track E proved the claimed runtime inverse gain does not exist for FF1 |
| 240 | # (hence FF1_SCALE = 1.0 below). The o and pp /4s were the same shape of |
| 241 | # claim and equally uncompensated: no norm gamma in this file is |
| 242 | # multiplied, and the runtime applies no inverse gain. At /4 the branches |
| 243 | # ran at 1/4 trained magnitude on device; the post-branch norms erase the |
| 244 | # scale but the MM/qint grids then quantize the wrong magnitudes. |
| 245 | # (Proven at the o-tail: device o-quantize diverges, numpy |
| 246 | # exact-arithmetic does not.) |
| 247 | O_SCALE, FF1_SCALE, PL_SCALE = 1.0, 1.0, 1.0 |
| 248 | # NOTE (Track E, 2026-09-24): FF1_SCALE was 256.0 with a comment claiming |
| 249 | # the runtime re-applies the inverse gain. That gain does not exist |
| 250 | # anywhere in library/ml/src/main/rust/ (no such const; norm gammas match |
| 251 | # S10 source exactly), so /256 silently ran every layer's up-path at 1/256 |
| 252 | # trained magnitude on device. Full-scale re-measured safe (worst 21k vs |
| 253 | # fp16 max 65504). |
| 254 | # NOTE (parity closure, 2026-09-25): O_SCALE and PL_SCALE were 4.0 with a |
| 255 | # "Keep /4 on o/pp" note. Same finding as FF1: no compensating gain |
| 256 | # exists, and the int8 grids quantize absolute magnitudes, so /4 flipped |
| 257 | # codes at the o-tail. Both are 1.0 now; the quarantine record is in |
| 258 | # build/gemma4-s10-fullfix/BLESSED.txt. |
| 259 | # norm tensor ids per layer_0; other layers resolved by name scan |
| 260 | for index in range(35): |
| 261 | at = f'layer_{index}' |
| 262 | full = index % 5 == 4 |
| 263 | dim = 512 if full else 256 |
| 264 | qrows = 8 * dim |
| 265 | # locate per-layer norm GAMMAS: the composite outputs (e.g. 354) carry |
| 266 | # no bytes; resolve each to its const gamma input (2nd composite input). |
| 267 | import re |
| 268 | pat = re.compile(rf'layer_{index}/') |
| 269 | norms = {} |
| 270 | for ti in range(sg.TensorsLength()): |
| 271 | nm = sg.Tensors(ti).Name().decode('utf-8') |
| 272 | if not pat.search(nm): |
| 273 | continue |
| 274 | for key, frag in [('pre', 'pre_attention_norm/composite'), |
| 275 | ('posta', 'post_attention_norm/composite'), |
| 276 | ('preff', 'pre_ffw_norm/composite'), |
| 277 | ('postff', 'post_ffw_norm/composite'), |
| 278 | ('postpl', 'post_per_layer_input_norm/composite'), |
| 279 | ('qn', 'query_norm/composite'), |
| 280 | ('kn', 'key_norm/composite')]: |
| 281 | if frag in nm and key not in norms: |
| 282 | norms[key] = ti |
| 283 | for key, ti in list(norms.items()): |
| 284 | for oi in range(sg.OperatorsLength()): |
| 285 | o = sg.Operators(oi) |
| 286 | outs = [o.Outputs(i) for i in range(o.OutputsLength())] |
| 287 | if ti not in outs: |
| 288 | continue |
| 289 | ins = [o.Inputs(i) for i in range(o.InputsLength())] |
| 290 | # composite ins: [activation, gamma] |
| 291 | if len(ins) >= 2 and ins[1] >= 0: |
| 292 | norms[key] = ins[1] |
| 293 | qw = fc_weight(rdr, index, 'q_einsum/reshape;') |
| 294 | if index < 15: |
| 295 | kw = fc_weight(rdr, index, 'k_einsum/reshape;') |
| 296 | vw = fc_weight(rdr, index, 'v_einsum/reshape;') |
| 297 | ow = fc_weight(rdr, index, 'attn_vec_einsum/btH') |
| 298 | gw = fc_weight(rdr, index, 'gating_einsum1') |
| 299 | uw = fc_weight(rdr, index, 'gating_einsum2') |
| 300 | dw = fc_weight(rdr, index, 'mlp/linear') |
| 301 | pew = fc_weight(rdr, index, 'per_layer_embedding_gate') |
| 302 | pew2 = fc_weight(rdr, index, 'per_layer_embedding_projection') |
| 303 | emit_vec(layers, tensors, f'transformer.layer_{index}.pre_attention_norm.scale', |
| 304 | rdr.f32(norms['pre'])) |
| 305 | emit_vec(layers, tensors, f'transformer.layer_{index}.attn.q_norm.scale', |
| 306 | rdr.f32(norms['qn'])) |
| 307 | emit4(fid, layers, tensors, f'transformer.layer_{index}.attn.q.w', |
| 308 | rdr.dequant4(qw, qrows, D)) |
| 309 | if index < 15: |
| 310 | emit_vec(layers, tensors, f'transformer.layer_{index}.attn.k_norm.scale', |
| 311 | rdr.f32(norms['kn'])) |
| 312 | emit4(fid, layers, tensors, f'transformer.layer_{index}.attn.k.w', |
| 313 | rdr.dequant4(kw, dim, D)) |
| 314 | emit4(fid, layers, tensors, f'transformer.layer_{index}.attn.v.w', |
| 315 | rdr.dequant4(vw, dim, D)) |
| 316 | emit4(fid, layers, tensors, f'transformer.layer_{index}.attn.o.w', |
| 317 | rdr.dequant4(ow, D, qrows) / O_SCALE) |
| 318 | emit_vec(layers, tensors, f'transformer.layer_{index}.post_attention_norm.scale', |
| 319 | rdr.f32(norms['posta'])) |
| 320 | emit_vec(layers, tensors, f'transformer.layer_{index}.pre_ffw_norm.scale', |
| 321 | rdr.f32(norms['preff'])) |
| 322 | if index < 15: |
| 323 | emit4(fid, layers, tensors, f'transformer.layer_{index}.mlp.gate.w', |
| 324 | rdr.dequant4(gw, 6144, D)) |
| 325 | emit4(fid, layers, tensors, f'transformer.layer_{index}.mlp.ff1.w', |
| 326 | rdr.dequant4(uw, 6144, D) / FF1_SCALE) |
| 327 | emit4(fid, layers, tensors, f'transformer.layer_{index}.mlp.linear.w', |
| 328 | rdr.dequant4(dw, D, 6144)) |
| 329 | else: |
| 330 | # Slim layers: full-width 2-bit gate/up/down in S10's NATIVE code |
| 331 | # space through the head codebook [0,+s,-2s,-s] lo-first (same as |
| 332 | # t2698; S10Reader.dequant2 applies no XOR remap). The artisan |
| 333 | # file's slim bytes are the same convention XOR-2-remapped |
| 334 | # (exact global XOR-2 multisets, bit-identical scales) — that |
| 335 | # remap lives in litertlm_to_maml.dequant2, NOT here. Gate and up |
| 336 | # are separate 12288-wide tables; the runtime's ffn() is 12288 |
| 337 | # here, so no split. |
| 338 | emit4(fid, layers, tensors, f'transformer.layer_{index}.mlp.gate.w', |
| 339 | rdr.dequant2(gw, 12288, D)) |
| 340 | emit4(fid, layers, tensors, f'transformer.layer_{index}.mlp.ff1.w', |
| 341 | rdr.dequant2(uw, 12288, D) / FF1_SCALE) |
| 342 | emit4(fid, layers, tensors, f'transformer.layer_{index}.mlp.linear.w', |
| 343 | rdr.dequant2(dw, D, 12288)) |
| 344 | emit_vec(layers, tensors, f'transformer.layer_{index}.post_ffw_norm.scale', |
| 345 | rdr.f32(norms['postff'])) |
| 346 | emit8(fid, layers, tensors, f'transformer.layer_{index}.per_layer.gate.w', |
| 347 | rdr.dequant8(pew, 256, 1536)) |
| 348 | emit8(fid, layers, tensors, f'transformer.layer_{index}.per_layer.proj.w', |
| 349 | rdr.dequant8(pew2, 1536, 256) / PL_SCALE) |
| 350 | emit_vec(layers, tensors, f'transformer.layer_{index}.post_per_layer_input_norm.scale', |
| 351 | rdr.f32(norms['postpl'])) |
| 352 | # skip: per-layer scalar via the skip-mul consumer chain (op ~100 for L0) |
| 353 | layers_skip = None |
| 354 | for oi in range(sg.OperatorsLength()): |
| 355 | o = sg.Operators(oi) |
| 356 | outs = [o.Outputs(i) for i in range(o.OutputsLength())] |
| 357 | nm = sg.Tensors(outs[0]).Name().decode('utf-8') if outs else '' |
| 358 | if f'layer_{index}.' in nm and '_maybe_apply_skip_scale/mul' in nm: |
| 359 | ins = [o.Inputs(i) for i in range(o.InputsLength())] |
| 360 | # the scalar input is the [1,1,1] one |
| 361 | for ii in ins: |
| 362 | t = sg.Tensors(ii) |
| 363 | if t.ShapeLength() == 3: |
| 364 | layers_skip = rdr.f32(ii)[:1] |
| 365 | if layers_skip is not None: |
| 366 | break |
| 367 | skip = np.ascontiguousarray(layers_skip, dtype=np.float32) |
| 368 | tensors.append(skip) |
| 369 | layers.append(mc.Layer(len(layers), 'MulScalar', |
| 370 | f'transformer.layer_{index}.skip.scale', |
| 371 | 'MulScalar s=[1]', len(tensors) - 1, 1)) |
| 372 | # The per-layer combine's projection + norm, byte-identical to the embed |
| 373 | # file's tensors 3-6, appended so the text plans combine in their own |
| 374 | # submit (nets::gemma4::COMBINE_PROJ). Last, so every other index holds. |
| 375 | emit_combine(fid, layers, tensors, rdr) |
| 376 | fid.report(mc.MIN_INT4_COSINE) |
| 377 | return layers, tensors |
| 378 | |
| 379 | |
| 380 | def emit_combine(fid, layers, tensors, rdr): |
| 381 | """S10 t312 (int8 [8960,1536], 1 scale/row) + norm gamma t305 (256).""" |
| 382 | emit8(fid, layers, tensors, 'transformer.embedder.per_layer_model_projection.w', |
| 383 | rdr.dequant8(312, 8960, 1536)) |
| 384 | emit_vec(layers, tensors, 'transformer.embedder.per_layer_projection_norm.scale', |
| 385 | rdr.f32(305)) |
| 386 | |
| 387 | |
| 388 | def main(): |
| 389 | ap = argparse.ArgumentParser() |
| 390 | ap.add_argument('-o', '--outdir', required=True) |
| 391 | ap.add_argument('--print-digest', action='store_true') |
| 392 | ap.add_argument('--text-only', action='store_true', |
| 393 | help='write gemma4_text.maml only (no embed dump needed)') |
| 394 | ap.add_argument('--slim-embed', metavar='FULL_EMBED', |
| 395 | help='write only a slim gemma4_embed.maml copied from FULL_EMBED') |
| 396 | args = ap.parse_args() |
| 397 | os.makedirs(args.outdir, exist_ok=True) |
| 398 | if args.slim_embed: |
| 399 | write_slim_embed(args.slim_embed, os.path.join(args.outdir, 'gemma4_embed.maml')) |
| 400 | return |
| 401 | rdr = S10Reader(S10) |
| 402 | layers, tensors = collect_text(rdr) |
| 403 | digest = mc.layer_table_digest(layers) |
| 404 | print(f's10_text: {len(layers)} layers, {len(tensors)} tensors, digest {digest}') |
| 405 | import hashlib |
| 406 | sha = hashlib.sha256(open(S10, 'rb').read()).digest() |
| 407 | blob, _ = mc.build(layers, tensors, mc.GRAPHS['gemma4_text'], sha) |
| 408 | out = os.path.join(args.outdir, 'gemma4_text.maml') |
| 409 | open(out, 'wb').write(blob) |
| 410 | print(f'wrote {out} ({len(blob)} bytes)') |
| 411 | if args.text_only: |
| 412 | return |
| 413 | elayers, etensors = collect_embed(rdr) |
| 414 | edigest = mc.layer_table_digest(elayers) |
| 415 | print(f's10_embed: {len(elayers)} layers, {len(etensors)} tensors, digest {edigest}') |
| 416 | eblob, _ = mc.build(elayers, etensors, mc.GRAPHS['gemma4_embed'], sha) |
| 417 | eout = os.path.join(args.outdir, 'gemma4_embed.maml') |
| 418 | open(eout, 'wb').write(eblob) |
| 419 | print(f'wrote {eout} ({len(eblob)} bytes)') |
| 420 | # GPU head file (2026-09-27 OOM fix): the 48 int8 head triples ALONE. |
| 421 | # The head `Net` uploads its whole `Blob` verbatim; with the chunks inside |
| 422 | # EMBED that upload was 3.6 GB (TEXT 1.1 + EMBED 3.6 = OOM-reboot on P8). |
| 423 | # The head file is ~402 MB. `collect_head` re-derives the chunks from the |
| 424 | # same S10 table (no new numerics — same `fid.quantise` calls, same rows). |
| 425 | hlayers, htensors = collect_head(rdr) |
| 426 | hdigest = mc.layer_table_digest(hlayers) |
| 427 | print(f's10_head: {len(hlayers)} layers, {len(htensors)} tensors, digest {hdigest}') |
| 428 | hblob, _ = mc.build(hlayers, htensors, mc.GRAPHS['gemma4_head'], sha) |
| 429 | hout = os.path.join(args.outdir, 'gemma4_head.maml') |
| 430 | open(hout, 'wb').write(hblob) |
| 431 | print(f'wrote {hout} ({len(hblob)} bytes)') |
| 432 | |
| 433 | |
| 434 | # Slim embed layout (see the module docstring): kept source entries, in order, |
| 435 | # with SLIM_PLACEHOLDERS one-element fp16 tensors standing in for 3-6. |
| 436 | SLIM_LAYERS = 35 |
| 437 | SLIM_TABLES = 7 |
| 438 | SLIM_PLACEHOLDERS = range(3, SLIM_TABLES) |
| 439 | SLIM_TENSORS = SLIM_TABLES + SLIM_LAYERS * 3 |
| 440 | |
| 441 | |
| 442 | def read_maml_table(path): |
| 443 | """(graph_id, sha256, data_offset, entries) of a .maml; entry = (ndim, dims, dtype, offset, size).""" |
| 444 | import struct |
| 445 | with open(path, 'rb') as f: |
| 446 | header = f.read(mc.HEADER_BYTES) |
| 447 | if header[:4] != mc.MAGIC: |
| 448 | raise SystemExit(f'{path}: not a .maml') |
| 449 | _, graph_id, count = struct.unpack_from('<III', header, 4) |
| 450 | sha = header[16:48] |
| 451 | data_offset, _ = struct.unpack_from('<II', header, 48) |
| 452 | table = f.read(count * mc.TENSOR_ENTRY_BYTES) |
| 453 | entries = [] |
| 454 | for i in range(count): |
| 455 | fields = struct.unpack_from('<I4IIII', table, i * mc.TENSOR_ENTRY_BYTES) |
| 456 | ndim, dims, dtype, offset, size = fields[0], fields[1:5], fields[5], fields[6], fields[7] |
| 457 | entries.append((ndim, dims[:ndim], dtype, offset, size)) |
| 458 | return graph_id, sha, data_offset, entries |
| 459 | |
| 460 | |
| 461 | def read_payload(f, data_offset, entry): |
| 462 | _, _, dtype, offset, size = entry |
| 463 | f.seek(data_offset + offset) |
| 464 | want = mc.payload_bytes(dtype, size) |
| 465 | payload = f.read(want) |
| 466 | if len(payload) != want: |
| 467 | raise SystemExit(f'short read: {len(payload)} of {want} bytes') |
| 468 | return payload |
| 469 | |
| 470 | |
| 471 | def write_slim_embed(src, out): |
| 472 | """Slim gemma4_embed.maml from a full one, tables bit-identical (re-read and compared).""" |
| 473 | import hashlib |
| 474 | graph_id, sha, data_offset, entries = read_maml_table(src) |
| 475 | if graph_id != mc.GRAPHS['gemma4_embed']: |
| 476 | raise SystemExit(f'{src}: graph {graph_id}, not gemma4_embed') |
| 477 | if len(entries) < SLIM_TENSORS: |
| 478 | raise SystemExit(f'{src}: {len(entries)} tensors, fewer than the {SLIM_TENSORS} kept') |
| 479 | tensors = [] |
| 480 | with open(src, 'rb') as f: |
| 481 | for i in range(SLIM_TENSORS): |
| 482 | if i in SLIM_PLACEHOLDERS: |
| 483 | tensors.append(np.zeros(1, dtype=np.float16)) |
| 484 | continue |
| 485 | entry = entries[i] |
| 486 | tensors.append(mc.Raw(entry[2], entry[1], entry[4], read_payload(f, data_offset, entry))) |
| 487 | blob, _ = mc.build([], tensors, graph_id, sha) |
| 488 | with open(out, 'wb') as f: |
| 489 | f.write(blob) |
| 490 | del blob, tensors |
| 491 | _, _, out_data, out_entries = read_maml_table(out) |
| 492 | assert len(out_entries) == SLIM_TENSORS, len(out_entries) |
| 493 | with open(src, 'rb') as a, open(out, 'rb') as b: |
| 494 | for i in range(SLIM_TENSORS): |
| 495 | if i in SLIM_PLACEHOLDERS: |
| 496 | continue |
| 497 | want, got = entries[i], out_entries[i] |
| 498 | if want[:3] != got[:3] or want[4] != got[4]: |
| 499 | raise SystemExit(f'tensor {i}: entry {got} differs from {want}') |
| 500 | if hashlib.sha256(read_payload(a, data_offset, want)).digest() != \ |
| 501 | hashlib.sha256(read_payload(b, out_data, got)).digest(): |
| 502 | raise SystemExit(f'tensor {i}: payload differs from the source') |
| 503 | print(f'wrote {out} ({os.path.getsize(out)} bytes, {SLIM_TENSORS} tensors, ' |
| 504 | f'{SLIM_TENSORS - len(SLIM_PLACEHOLDERS)} bit-identical to {src})') |
| 505 | |
| 506 | |
| 507 | def collect_embed(rdr): |
| 508 | """gemma4_embed from S10's own tensors |
| 509 | |
| 510 | Layout matches the artisan path's embed file exactly (same tensor order, |
| 511 | same layer kinds), so the runtime reads either file identically: |
| 512 | - working table: exact S2 `embedder` fp32 rows [262144, 1536] via |
| 513 | GEMMA4_EMBED_DUMP (same requirement as the artisan path; the 2-bit |
| 514 | in-file packing is a different checkpoint's arrangement in both files). |
| 515 | - head table: S10 t2698 (`embedder.decode` composite, type 19 2-bit, |
| 516 | codebook [0,+s,-2s,-s] lo-first — 10/10 vs the golden ranking). The |
| 517 | tied head reads this raw-scale table (see nets::gemma4::EMBED_GAIN). |
| 518 | - shared projection: S10's OWN t312 (int8 [8960,1536], 1 scale/row) + |
| 519 | norm gamma t305 (256). Track-3 decision (live t318 oracle): S10-table + |
| 520 | x16-on-gather scores 0.99997 vs live t318 while the artisan table peaks |
| 521 | at 0.42 — the two files are different checkpoints for the dense tables |
| 522 | (L0 Q/O/gate artisan-vs-S10 full-cos ~0.0006, row-max ~0.10; S10 Q@hidden |
| 523 | vs live t357 = 0.989, artisan = -0.14), so the S10-control file defaults |
| 524 | to S10's table. (The old note claiming artisan 1.00000 vs S10 -0.09 was |
| 525 | scored against a trace.json itself generated with artisan weights — circular. |
| 526 | Gammas are identical either way, cos 1.000000.) |
| 527 | - 35 per-layer mmap tables: S10 has no per-layer embedder (that is |
| 528 | Section 3, not Section 10); these come from the artisan file's |
| 529 | `per_layer_embeddings.w` INT4 tables, whose signed-nibble read is |
| 530 | proven (cos 1.0000 vs base S3 output). |
| 531 | """ |
| 532 | import litertlm_to_maml as lt |
| 533 | layers, tensors = [], [] |
| 534 | fid = mc.Fidelity() |
| 535 | dump = os.environ.get('GEMMA4_EMBED_DUMP') |
| 536 | if not dump or not os.path.exists(dump): |
| 537 | raise SystemExit( |
| 538 | 'collect_embed needs GEMMA4_EMBED_DUMP=<embed_s2_fp32.bin> ' |
| 539 | '(scripts/ml/gemma4_embed_dump.py)') |
| 540 | out = np.memmap(dump, dtype=np.float32, mode='r', |
| 541 | shape=(262144, 1536)).astype(np.float32) |
| 542 | m = float(np.abs(out).mean()) |
| 543 | print(f'input_embedding S2 dump {dump}: mean abs {m:.4f}') |
| 544 | codes, scale = fid.quantise4('input_embedding', out) |
| 545 | bias = np.zeros(262144, dtype=np.float32) |
| 546 | tensors.extend([codes, scale, bias]) |
| 547 | layers.append(mc.Layer(len(layers), 'Embedding4', 'input_embedding', |
| 548 | 'Embedding4 2-bit source', len(tensors) - 3, 3)) |
| 549 | # Per-layer mmap tables: S10 carries none (that is Section 3, not |
| 550 | # Section 10). Prefer S3's own tables (exact golden source); fall back |
| 551 | # to the artisan file's signed-nibble read when S3 is absent. |
| 552 | art_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'analysis', |
| 553 | 'gpu-sections', |
| 554 | 'Section2_TFLiteModel_tf_lite_artisan_text_decoder.tflite') |
| 555 | s3rdr = S3Reader(S3) if os.path.exists(S3) else None |
| 556 | art = lt.LitertlmReader(art_path) if s3rdr is None else None |
| 557 | if s3rdr is None and art is None: |
| 558 | raise SystemExit('collect_embed needs S3 (analysis/base-sections/...) or the artisan file') |
| 559 | emit_combine(fid, layers, tensors, rdr) |
| 560 | for index in range(35): |
| 561 | if s3rdr is not None: |
| 562 | out = s3rdr.table(index) |
| 563 | else: |
| 564 | at = f'transformer.layer_{index}.per_layer_embeddings.w' |
| 565 | w = np.frombuffer(art.raw(at), dtype=np.uint8) |
| 566 | assert w.size >= 262144 * 128, f'{at}: {w.size}' |
| 567 | w = w[:262144 * 128] |
| 568 | lo = (w & 0xF).astype(np.float32) |
| 569 | hi = ((w >> 4) & 0xF).astype(np.float32) |
| 570 | flat = np.empty(262144 * 256, dtype=np.float32) |
| 571 | flat[0::2] = lo |
| 572 | flat[1::2] = hi |
| 573 | flat = np.where(flat >= 8, flat - 16, flat).reshape(262144, 256) |
| 574 | s = np.frombuffer(art.raw(at + '_quantized_scale'), dtype=np.float32) |
| 575 | assert s.size == 262144, f'{at} scales: {s.size}' |
| 576 | out = flat * s[:, None] |
| 577 | codes, scale = fid.quantise4(f'layer_{index}.per_layer_embeddings', out) |
| 578 | bias = np.zeros(262144, dtype=np.float32) |
| 579 | tensors.extend([codes, scale, bias]) |
| 580 | layers.append(mc.Layer(len(layers), 'Linear4', f'layer_{index}.per_layer_embeddings', |
| 581 | 'Linear4 mmap table', len(tensors) - 3, 3)) |
| 582 | # Head table LAST (see TABLES): appended after the per-layer tables so |
| 583 | # their file entries (7+i*3) match the artisan-path file exactly and old |
| 584 | # files without a head table still parse for gather. |
| 585 | # |
| 586 | # GPU tied-head (2026-09-26): the head is ALSO emitted as HEAD_SPLITS |
| 587 | # rank-4 fp16 chunks ([N,1536,1,1] + zero [N] bias each) that |
| 588 | # Builder::conv binds directly (kernel+bias, no bias-free path exists). |
| 589 | # One 262144-wide fp16 tensor spans ~768 MiB, far over the ~96 MiB |
| 590 | # segment-window reach at guaranteed 128 MiB maxStorageBufferRange |
| 591 | # (vulkan/segment.rs `for_op` refuses it: "Split the tensor in the |
| 592 | # converter"). 16x16384 chunks are ~50 MB each — inside the window with |
| 593 | # margin on both host and P8. Chunk tensors follow the legacy rank-2 |
| 594 | # table so old files (112 tensors, no head) still parse for gather and |
| 595 | # indices 0..111 are unchanged; the runtime binds chunks when present |
| 596 | # and falls back to the host head otherwise. Vocab order is preserved |
| 597 | # (chunk s holds classes [s*N,(s+1)*N)), so concat(chunks) == table. |
| 598 | head = rdr.dequant2(2698, 262144, 1536) |
| 599 | head = np.ascontiguousarray(head, dtype=np.float32).astype(np.float16) |
| 600 | tensors.append(head) |
| 601 | layers.append(mc.Layer(len(layers), 'Embedding4', 'head_table', |
| 602 | 'Embedding4 raw-scale S10 decode table fp16', |
| 603 | len(tensors) - 1, 1)) |
| 604 | n = head.shape[0] |
| 605 | assert n == 262144, n |
| 606 | per = n // HEAD_SPLITS |
| 607 | assert per * HEAD_SPLITS == n, (n, HEAD_SPLITS) |
| 608 | for s in range(HEAD_SPLITS): |
| 609 | rows = head[s * per:(s + 1) * per].astype(np.float32) |
| 610 | assert rows.shape == (per, 1536), rows.shape |
| 611 | kernel = np.ascontiguousarray(rows.reshape(per, 1536, 1, 1)) |
| 612 | bias = np.zeros(per, dtype=np.float32) |
| 613 | tensors.extend([kernel, bias]) |
| 614 | layers.append(mc.Layer(len(layers), 'Linear', f'head_split_{s}', |
| 615 | f'Linear w=[{per}, 1536, 1, 1] dtype=fp16 b=[{per}]', |
| 616 | len(tensors) - 2, 2)) |
| 617 | print(f'head_table: rank-2 fp16 [{n}, 1536] + {HEAD_SPLITS} rank-4 ' |
| 618 | f'fp16 chunks of [{per}, 1536, 1, 1] (+ zero bias)') |
| 619 | # int8 GPU-head chunks (Phase 2, 2026-09-26): the same rows quantised |
| 620 | # per-channel (`fid.quantise`, symmetric int8 * fp16 scale), 3 tensors |
| 621 | # per chunk (kernel, scale, bias). ~25 MB/chunk vs ~50 MB fp16 (~2x |
| 622 | # bandwidth), and chunks auto-route to `ConvVecInt8` at 1 position |
| 623 | # (mod_part9.rs), fixing the fp16 `ConvPoint` 93.75% idle-lane waste with |
| 624 | # no code change. The fp16 chunks above stay in-file during transition: |
| 625 | # the runtime binds int8 when present, fp16 otherwise. |
| 626 | # INVARIANT (byte-identity with the head file, 2026-09-27): these rows |
| 627 | # are the fp16-rounded `head` table, NOT fp32-direct dequant — keep it |
| 628 | # that way. `collect_head` rounds identically so its 48 triples are |
| 629 | # byte-identical to these chunks (quantising fp32-direct flips ~6-11% |
| 630 | # of codes by ±1, a second numerics variant for 0.00002 fidelity). |
| 631 | # CAUTION (binding): int8-per-channel over an S10-2-bit source is a |
| 632 | # requant — must pass the argmax-9079 gate before shipping, never cosine |
| 633 | # alone. Do NOT use the WORKING int4 table as head even with /39.25 |
| 634 | # (wrong source + LOGIT_CAP saturation). |
| 635 | for s in range(HEAD_SPLITS): |
| 636 | rows = head[s * per:(s + 1) * per].astype(np.float32) |
| 637 | kernel8, scale8 = fid.quantise(f'head_split8_{s}', |
| 638 | np.ascontiguousarray(rows).reshape(per, 1536, 1, 1)) |
| 639 | bias8 = np.zeros(per, dtype=np.float32) |
| 640 | tensors.extend([kernel8, scale8, bias8]) |
| 641 | layers.append(mc.Layer(len(layers), 'Linear8', f'head_split8_{s}', |
| 642 | f'Linear8 w=[{per}, 1536, 1, 1] dtype=int8 b=[{per}]', |
| 643 | len(tensors) - 3, 3)) |
| 644 | print(f'head_table int8: {HEAD_SPLITS} chunks of [{per}, 1536, 1, 1] ' |
| 645 | f'int8 (+ [per] scale, zero bias)') |
| 646 | fid.report(mc.MIN_INT4_COSINE) |
| 647 | return layers, tensors |
| 648 | |
| 649 | |
| 650 | def collect_head(rdr): |
| 651 | """gemma4_head: the 48 int8 head triples ALONE (OOM fix, 2026-09-27). |
| 652 | |
| 653 | Same S10 t2698 source, same fp16-rounded rows, same `fid.quantise` |
| 654 | calls, same row order as the int8 chunks `collect_embed` appends — |
| 655 | factored so the head `Net` uploads ~402 MB instead of the whole |
| 656 | 3.6 GB EMBED file. The fp16 rounding mirrors `collect_embed`'s head |
| 657 | section exactly (quantising the same rows the fp16 chunks store), so |
| 658 | the head file's 48 triples are byte-identical to the EMBED int8 |
| 659 | chunks — one numerics variant in the field, byte-comparable. |
| 660 | Chunk `s` owns tensors `s * 3 .. s * 3 + 2` (kernel |
| 661 | `[per, 1536, 1, 1]` int8, scale `[per]` fp16, bias `[per]` fp16); |
| 662 | vocab order preserved. |
| 663 | """ |
| 664 | layers, tensors = [], [] |
| 665 | fid = mc.Fidelity() |
| 666 | head = rdr.dequant2(2698, 262144, 1536) |
| 667 | # fp16 round FIRST, exactly as `collect_embed` does before its int8 |
| 668 | # chunks: quantising fp32-direct flips ~6-11% of codes by ±1 (measured |
| 669 | # 2026-09-27, scales ~0.05%), a second numerics variant for no gain |
| 670 | # (direct-fp32 fidelity 0.999922 vs fp16-rounded 0.999900, both far |
| 671 | # above MIN_INT8_COSINE 0.999). |
| 672 | head = np.ascontiguousarray(head, dtype=np.float32).astype(np.float16) |
| 673 | n = head.shape[0] |
| 674 | assert n == 262144, n |
| 675 | per = n // HEAD_SPLITS |
| 676 | assert per * HEAD_SPLITS == n, (n, HEAD_SPLITS) |
| 677 | for s in range(HEAD_SPLITS): |
| 678 | rows = head[s * per:(s + 1) * per].astype(np.float32) |
| 679 | kernel8, scale8 = fid.quantise(f'head_split8_{s}', |
| 680 | np.ascontiguousarray(rows).reshape(per, 1536, 1, 1)) |
| 681 | bias8 = np.zeros(per, dtype=np.float32) |
| 682 | tensors.extend([kernel8, scale8, bias8]) |
| 683 | layers.append(mc.Layer(len(layers), 'Linear8', f'head_split8_{s}', |
| 684 | f'Linear8 w=[{per}, 1536, 1, 1] dtype=int8 b=[{per}]', |
| 685 | len(tensors) - 3, 3)) |
| 686 | print(f'head file: {HEAD_SPLITS} int8 chunks of [{per}, 1536, 1, 1] ' |
| 687 | f'(+ [per] scale, zero bias)') |
| 688 | fid.report(mc.MIN_INT4_COSINE) |
| 689 | return layers, tensors |
| 690 | |
| 691 | |
| 692 | if __name__ == '__main__': |
| 693 | main() |