Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / litertlm_to_maml.py
litertlm_to_maml.py451 lines · 23.7 KiBRaw
| 1 | """Convert litertlm artisan Gemma bundle DIRECTLY to .maml files. The ONNX is a different model; litertlm is truth. |
| 2 | |
| 3 | FILE-DRIVEN shapes (TFLite INT4 shapefield = nibble count; INT8/U8/F32 = elements): |
| 4 | NOTE on the artisan shapefield quirk: every shapefield in this file is a |
| 5 | BYTE count (verified: F32 `final_norm.scale` shapefield [6144] holds 6144 B |
| 6 | = 1536 floats; `skip.scale` shapefield [4] holds 4 B = 1 float). INT4 |
| 7 | [1572864] = 1572864 bytes = 2x nibbles. |
| 8 | sliding (0-3,5-8,10-13, head_dim 256): q [2048,1536] (8x256), k/v [256,1536], |
| 9 | o [1536,2048] |
| 10 | full (4,9,14,... index%5==4, head_dim 512): q [4096,1536] (8x512), |
| 11 | k/v [512,1536], o [1536,4096] |
| 12 | MLP owning (0-14): gate+ff1 [6144,1536], linear [1536,6144], signed INT4 |
| 13 | MLP slim (15-34): gate+ff1 [12288,1536], linear [1536,12288], artisan 2-bit |
| 14 | (INT8-tagged, 4 vals/byte, 1 F32 scale/row); same geometry as the base |
| 15 | bundle's own Section 10 weights (type 19) |
| 16 | scales: 1 F32 scale per row for EVERY table (verified scale counts: q 2048/ |
| 17 | 2048 rows, O 1536/1536, gate 6144/6144, slim 12288/12288, PLE proj 8960/ |
| 18 | 8960, per-layer gate 256/256, per-layer proj 1536/1536, per-layer embed |
| 19 | 262144/262144). Zero-points all 0. |
| 20 | embedder: working table = exact S2 `embedder` fp32 rows [262144, 1536] via |
| 21 | GEMMA4_EMBED_DUMP (the artisan 2-bit `input_embedding.w` packing is a |
| 22 | different checkpoint's arrangement, uncorrelated ~-0.03); shared proj |
| 23 | [8960,1536] INT8; per-layer [262144,256] signed INT4 x35 (33.5MB each, |
| 24 | 1 fp32 scale/row) |
| 25 | norms: q_norm/k_norm are head-dim-wide full vectors ([256] sliding, [512] |
| 26 | full — shapefields read [1024]/[2048] bytes); pre/post norms [1536]. NO |
| 27 | head table in this file (tied head reads the S2 working table); sampler |
| 28 | TOP_P 64/0.95/1.0 |
| 29 | |
| 30 | Emits via maml_convert.build (symmetric per-block int4 requant, fidelity-gated): |
| 31 | gemma4_text.maml (graph 20), gemma4_embed.maml (graph 21). |
| 32 | """ |
| 33 | |
| 34 | import argparse |
| 35 | import os |
| 36 | import sys |
| 37 | |
| 38 | import numpy as np |
| 39 | |
| 40 | sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)))) |
| 41 | import maml_convert as mc |
| 42 | |
| 43 | import tflite |
| 44 | from tflite.Model import Model |
| 45 | |
| 46 | |
| 47 | class LitertlmReader: |
| 48 | def __init__(self, path): |
| 49 | with open(path, 'rb') as f: |
| 50 | self.sec = f.read() |
| 51 | self.model = Model.GetRootAs(bytearray(self.sec), 0) |
| 52 | sg = self.model.Subgraphs(0) |
| 53 | self.tensors = {} |
| 54 | for ti in range(sg.TensorsLength()): |
| 55 | t = sg.Tensors(ti) |
| 56 | self.tensors[t.Name().decode('utf-8')] = t |
| 57 | |
| 58 | def raw(self, name): |
| 59 | # FILE QUIRK: every shapefield is a BYTE count (INT4 included: |
| 60 | # shape = bytes = nibbles/2). See dequant4 docstring. |
| 61 | t = self.tensors[name] |
| 62 | b = self.model.Buffers(t.Buffer()) |
| 63 | n = 1 |
| 64 | for i in range(t.ShapeLength()): |
| 65 | n *= t.Shape(i) |
| 66 | off = b.Offset() |
| 67 | return self.sec[off:off + n] |
| 68 | |
| 69 | def f32(self, name): |
| 70 | return np.frombuffer(self.raw(name), dtype=np.float32).copy() |
| 71 | |
| 72 | def dequant4(self, name, rows, cols): |
| 73 | """INT4 signed nibbles + F32 scales (1 per row) -> fp32 [rows, cols]. |
| 74 | |
| 75 | PROVEN (cos 1.0000 vs base S3 output): nibbles are SIGN-EXTENDED 4-bit |
| 76 | (-8..7), not unsigned-with-zp-8. The old `(code - 8)` read every table |
| 77 | sign-flipped. sum_i/static scales are not consumed by this converter. |
| 78 | |
| 79 | FILE QUIRK (verified by buffer extents): every shapefield in this file |
| 80 | is a BYTE count (F32 [N] = N bytes = N/4 floats; INT4 [N] = N bytes = |
| 81 | 2N nibbles). |
| 82 | """ |
| 83 | t = self.tensors[name] |
| 84 | n = rows * cols |
| 85 | raw = self.raw(name) |
| 86 | assert len(raw) * 2 >= n, f'{name}: {len(raw)}B < {n} nibbles' |
| 87 | u8 = np.frombuffer(raw, dtype=np.uint8) |
| 88 | lo = (u8 & 0xF).astype(np.float32) |
| 89 | hi = ((u8 >> 4) & 0xF).astype(np.float32) |
| 90 | flat = np.empty(n, dtype=np.float32) |
| 91 | flat[0::2] = lo[:n // 2] |
| 92 | flat[1::2] = hi[:n // 2] |
| 93 | flat = np.where(flat >= 8, flat - 16, flat).reshape(rows, cols) |
| 94 | sname = name + '_quantized_scale' |
| 95 | sraw = self.raw(sname) |
| 96 | scales = np.frombuffer(sraw, dtype=np.float32) |
| 97 | assert scales.size % rows == 0, f'{sname}: {scales.size} vs {rows} rows' |
| 98 | per_row = scales.size // rows |
| 99 | scales = scales.reshape(rows, per_row) |
| 100 | g = cols // per_row |
| 101 | out = np.empty((rows, cols), dtype=np.float32) |
| 102 | for gi in range(per_row): |
| 103 | out[:, gi * g:(gi + 1) * g] = flat[:, gi * g:(gi + 1) * g] * scales[:, gi:gi + 1] |
| 104 | m = float(np.abs(out).mean()) |
| 105 | if not (1e-6 < m < 10.0): |
| 106 | print(f'WARN {name}: mean abs {m:.2e}') |
| 107 | return out |
| 108 | |
| 109 | def dequant8(self, name, rows, cols, zp=0.0): |
| 110 | """INT8/U8 symmetric, 1 or 4 scales per row -> fp32.""" |
| 111 | raw = np.frombuffer(self.raw(name), dtype=np.int8).astype(np.float32) |
| 112 | assert raw.size >= rows * cols, f'{name}: {raw.size} < {rows}x{cols}' |
| 113 | raw = raw[:rows * cols].reshape(rows, cols) |
| 114 | sname = name + '_quantized_scale' |
| 115 | scales = np.frombuffer(self.raw(sname), dtype=np.float32) |
| 116 | assert scales.size % rows == 0, f'{sname}: {scales.size} vs {rows}' |
| 117 | per_row = scales.size // rows |
| 118 | scales = scales.reshape(rows, per_row) |
| 119 | g = cols // per_row |
| 120 | out = np.empty((rows, cols), dtype=np.float32) |
| 121 | for gi in range(per_row): |
| 122 | out[:, gi * g:(gi + 1) * g] = (raw[:, gi * g:(gi + 1) * g] - zp) * scales[:, gi:gi + 1] |
| 123 | return out |
| 124 | |
| 125 | |
| 126 | def dequant2(name_or_rdr, name=None, rows=None, cols=None): |
| 127 | """Artisan 2-bit (INT8-tagged, 4 values/byte, row-major, lo-first) -> fp32. |
| 128 | |
| 129 | Codebook is the SAME head codebook as S10's type-19 tables |
| 130 | (`embedder.decode` t2698, slim gates t1587...): [0, +s, -2s, -s] lo-first |
| 131 | (s10_to_maml.S10Reader.dequant2). BUT the artisan slim bytes are stored |
| 132 | XOR-2-remapped relative to S10 storage: exact global XOR-2 code multisets |
| 133 | (L15/L16/L20 gate artisan counts == S10 counts permuted c->c^2) with |
| 134 | bit-identical per-row scales (L15 full-cos 1.000000), while position-wise |
| 135 | agreement after remap is only ~0.30 (different checkpoint arrangement, same |
| 136 | 2-bit convention). So artisan codes are mapped `(code ^ 2)` through the |
| 137 | head codebook. Without the remap the read centers at -0.021 with 68% |
| 138 | negative; with it, at -0.003 with 32% negative / 39% zero — matching the |
| 139 | head-table statistics (negfrac 0.34) and zero-mean trained-weight priors. |
| 140 | |
| 141 | Applies to every slim-layer MLP table (layers 15-34 gate/ff1/linear). |
| 142 | S10's own slim gates decode WITHOUT the remap (native S10 code space). |
| 143 | Parity still arbitrates end to end. |
| 144 | """ |
| 145 | if name is None: |
| 146 | raise SystemExit('dequant2 takes (rdr, name, rows, cols)') |
| 147 | rdr, name = name_or_rdr, name |
| 148 | raw = rdr.raw(name) |
| 149 | assert len(raw) * 4 >= rows * cols, f'{name}: {len(raw)}B < {rows}x{cols} 2-bit' |
| 150 | u8 = np.frombuffer(raw, dtype=np.uint8) |
| 151 | vals = np.empty(rows * cols, dtype=np.float32) |
| 152 | for k in range(4): |
| 153 | vals[k::4] = ((u8 >> (2 * k)) & 0x3).astype(np.float32) |
| 154 | # XOR-2 storage remap into the S10/head code space (see docstring). |
| 155 | vals = np.bitwise_xor(vals.astype(np.uint8), np.uint8(2)).astype(np.float32) |
| 156 | codebook = np.array([0.0, 1.0, -2.0, -1.0], dtype=np.float32) |
| 157 | vals = codebook[vals.astype(int)].reshape(rows, cols) |
| 158 | s = np.frombuffer(rdr.raw(name + '_quantized_scale'), dtype=np.float32) |
| 159 | assert s.size == rows, f'{name} scales: {s.size} vs {rows} rows' |
| 160 | out = vals * s[:, None] |
| 161 | m = float(np.abs(out).mean()) |
| 162 | if not (1e-6 < m < 10.0): |
| 163 | print(f'WARN {name}: mean abs {m:.2e}') |
| 164 | return out |
| 165 | |
| 166 | |
| 167 | def emit4(fid, layers, tensors, logical, weight): |
| 168 | # 4D `[out, in, 1, 1]`: the file convention every device-bound projection uses |
| 169 | # (see Builder::conv_quantised, which checks `[m, per_group, kh, kw]`). The |
| 170 | # quantiser flattens the tap axis, so this changes only the stored shape. |
| 171 | rows, cols = weight.shape |
| 172 | weight4 = np.ascontiguousarray(weight).reshape(rows, cols, 1, 1) |
| 173 | codes, scale = fid.quantise4(logical, weight4) |
| 174 | bias = np.zeros(rows, dtype=np.float32) |
| 175 | tensors.extend([codes, scale, bias]) |
| 176 | layers.append(mc.Layer(len(layers), 'Linear4', logical, |
| 177 | f'Linear4 w=[{rows}, {cols}, 1, 1] dtype=int4', len(tensors) - 3, 3)) |
| 178 | |
| 179 | |
| 180 | def emit8(fid, layers, tensors, logical, weight): |
| 181 | rows, cols = weight.shape |
| 182 | weight4 = np.ascontiguousarray(weight).reshape(rows, cols, 1, 1) |
| 183 | kernel, scale = fid.quantise(logical, weight4) |
| 184 | bias = np.zeros(rows, dtype=np.float32) |
| 185 | tensors.extend([kernel, scale, bias]) |
| 186 | layers.append(mc.Layer(len(layers), 'Linear8', logical, |
| 187 | f'Linear8 w=[{rows}, {cols}, 1, 1] dtype=int8', len(tensors) - 3, 3)) |
| 188 | |
| 189 | |
| 190 | def emit_vec(layers, tensors, logical, values): |
| 191 | values = np.ascontiguousarray(values, dtype=np.float32) |
| 192 | tensors.append(values) |
| 193 | layers.append(mc.Layer(len(layers), 'RmsNorm', logical, |
| 194 | f'RmsNorm g={list(values.shape)}', len(tensors) - 1, 1)) |
| 195 | |
| 196 | |
| 197 | def collect_text(rdr, rope_theta_local=10000.0, rope_theta_global=1000000.0): |
| 198 | """gemma4_text in litertlm order. Returns (layers, tensors). |
| 199 | |
| 200 | The transformer ONLY: final norm, two rotary tables, 35 layers. The shared |
| 201 | per-layer projection + norm live in the EMBED file and the host applies them |
| 202 | in gather (see nets::gemma4::gather) - they are intentionally absent here. |
| 203 | |
| 204 | Rotary thetas read off the BASE bundle's own Section 10 graph: its |
| 205 | `maybe_rope` div constants are freq tables with freq[1] = 0.93057203 |
| 206 | (sliding, 128 freqs over head_dim 256, S10 t296 — full match) and |
| 207 | 0.9474635 (full, 256 entries over head_dim 512, S10 t245 — only the first |
| 208 | 64 nonzero), implying theta=1e4 and theta=1e6 (verified freq[2] both). |
| 209 | Track-3 evidence: global theta-regen first-64 vs native t245 = 1.000000, |
| 210 | truncated-regen vs native full = 1.000000, full 256-freq regen vs native = |
| 211 | 0.9995 — because S10's full table is zero-padded after 64, generating 256 |
| 212 | freqs rotates 192 channel pairs the reference leaves fixed. PREFER native |
| 213 | t296/t245 reads (s10_to_maml.collect_text); this theta path is a fallback |
| 214 | and SHOULD truncate the global table to its 64 nonzero freqs. |
| 215 | Caution: the table ENTRY count is half the head dim (64 freqs would imply |
| 216 | theta=100/1000 - wrong); the exponent's dim is the head dim 256/512, and |
| 217 | S10's (1,1,8,128) pre_qk tensor is a norm reshape, not the head dim. |
| 218 | --rope-theta sets BOTH (bisect escape hatch). |
| 219 | """ |
| 220 | layers, tensors = [], [] |
| 221 | fid = mc.Fidelity() |
| 222 | D = 1536 |
| 223 | emit_vec(layers, tensors, 'transformer.final_norm.scale', |
| 224 | rdr.f32('transformer.final_norm.scale')) |
| 225 | # Rotary tables: litertlm computes these internally (none stored). Emit standard |
| 226 | # RoPE cut to MAX_CONTEXT, cos|sin interleaved per Builder::rotary. Thetas read |
| 227 | # off the base bundle's own Section 10 `maybe_rope` constants (freq[1] implies |
| 228 | # theta): 1e4 sliding / 1e6 full. Parity vs the base-bundle golden arbitrates. |
| 229 | # If global diverges, try proportional scaling before anything else. |
| 230 | for kind, dim, theta in (('local', 256, rope_theta_local), |
| 231 | ('global', 512, rope_theta_global)): |
| 232 | pos = np.arange(16384, dtype=np.float32)[:, None] |
| 233 | freq = theta ** (-2.0 * np.arange(dim // 2, dtype=np.float32) / dim) |
| 234 | ang = pos * freq[None, :] |
| 235 | table = np.concatenate([np.cos(ang), np.sin(ang)], axis=1).astype(np.float32) |
| 236 | tensors.append(table) |
| 237 | layers.append(mc.Layer(len(layers), 'Rotary', f'{kind}_rotary_table', |
| 238 | f'Rotary t={list(table.shape)} theta-{theta:g}', len(tensors) - 1, 1)) |
| 239 | # Shared all-ones vectors: the gamma of S10's parameter-free value_norm |
| 240 | # (see nets::gemma4::ONE_SLIDING). Head-dim-wide: [256] and [512]. |
| 241 | emit_vec(layers, tensors, 'transformer.ones_sliding', np.ones(256, dtype=np.float32)) |
| 242 | emit_vec(layers, tensors, 'transformer.ones_full', np.ones(512, dtype=np.float32)) |
| 243 | # FP16-ARENA RESCALING (measured, analysis/probe_all_layers.py): |
| 244 | # Gemma 3n's activations have huge outlier channels. Worst max|.| over all |
| 245 | # 35 layers on real embeddings: gelu_up 233k, down_out 4.04M, pl_proj_out |
| 246 | # 52k, o_proj_out 32k - every one of them a materialised fp16 tensor, and |
| 247 | # anything past 65504 stores as inf, then NaNs the consuming norm |
| 248 | # (inf/inf). The reference runs fp32 arithmetic, so it never sees this. |
| 249 | # Each rescaled projection feeds ONLY its norm (o -> post_attention_norm, |
| 250 | # ff1 -> mul -> down -> post_ffw_norm, pl proj -> post_per_layer norm), |
| 251 | # and an RMS norm erases uniform input scaling exactly, so pow2 weight |
| 252 | # scaling is computation-neutral: it only shrinks what fp16 must hold. |
| 253 | # The gate stays full-scale (gelu is nonlinear; scaling it would move the |
| 254 | # operating point), and scaling the LINEAR up-path is exact. The runtime |
| 255 | # re-applies the inverse gain on the norm side (see nets::gemma4 rescale |
| 256 | # consts), so end-to-end numerics are unchanged up to fp16 rounding. |
| 257 | # |
| 258 | # TRACK-E CORRECTION (verified 2026-09-24): the claimed runtime inverse |
| 259 | # gain DOES NOT EXIST - no O_SCALE/FF1_SCALE/PL_SCALE const exists anywhere |
| 260 | # in library/ml/src/main/rust/, and post_ffw norm gammas match S10 source |
| 261 | # at cos 1.000000 (no hidden gain). The /256 on `up` therefore ran every |
| 262 | # layer's up-path at 1/256 trained magnitude on device (staged-maml weights |
| 263 | # reproduce the exact device failure signature 7001/3; S10-source gives |
| 264 | # 9079/6; only S10_up restore flips it). Full-scale safety re-measured |
| 265 | # under TRUE 6-token chained inputs: worst |gelu*up| 21k, worst |down_out| |
| 266 | # 14k (both L0), 3-4x headroom under fp16 max 65504 - no overflow risk. |
| 267 | # So FF1_SCALE = 1.0: emit `up` at FULL scale. Keep /4 on o/pp (harmless |
| 268 | # through their norms, no breakage observed). |
| 269 | # |
| 270 | # PARITY-CLOSURE CORRECTION (2026-09-25): the /4 on o/pp is NOT harmless. |
| 271 | # The post-branch norms erase uniform scale, but the live int8 MM/qint |
| 272 | # grids quantize absolute magnitudes: a /4 weight table makes the device |
| 273 | # round-trip at 1/4 the trained grid step, flipping codes the live model |
| 274 | # never flips. The device `quantize` op reproduces live exactly only at |
| 275 | # full-scale tables (proven: mm-only device-vs-numpy 0.9943 with FF1 at |
| 276 | # 1.0; the o-tail diverges with o at /4). So O_SCALE = PL_SCALE = 1.0: |
| 277 | # emit o/pp at FULL scale. fp16 headroom re-verified (worst |down_out| |
| 278 | # 14k vs fp16 max 65504). |
| 279 | O_SCALE, FF1_SCALE, PL_SCALE = 1.0, 1.0, 1.0 |
| 280 | for index in range(35): |
| 281 | at = f'transformer.layer_{index}' |
| 282 | full = index % 5 == 4 |
| 283 | dim = 512 if full else 256 |
| 284 | qrows = 8 * dim |
| 285 | kvrows = dim |
| 286 | # Slim layers (15-34, shared KV) run a 12288-wide MLP in artisan 2-bit |
| 287 | # storage (type tag INT8, 4 values/byte, 1 F32 scale/row). Same |
| 288 | # checkpoint convention as the base bundle's own Section 10 type-19 |
| 289 | # slim weights: exact global XOR-2 code multisets (L15/L16/L20) with |
| 290 | # bit-identical per-row scales — decoded via dequant2's (code ^ 2) |
| 291 | # remap through the head codebook (see its docstring). Proven by byte |
| 292 | # counts (4718592 B = 12288x1536/4) and scale counts (12288 = rows). |
| 293 | slim = index >= 15 |
| 294 | inner = 12288 if slim else 6144 |
| 295 | emit_vec(layers, tensors, f'{at}.pre_attention_norm.scale', rdr.f32(f'{at}.pre_attention_norm.scale')) |
| 296 | emit_vec(layers, tensors, f'{at}.attn.q_norm.scale', rdr.f32(f'{at}.attn.q_norm.scale')) |
| 297 | emit4(fid, layers, tensors, f'{at}.attn.q.w', |
| 298 | rdr.dequant4(f'{at}.attn.q.w', qrows, D)) |
| 299 | if index < 15: |
| 300 | emit_vec(layers, tensors, f'{at}.attn.k_norm.scale', rdr.f32(f'{at}.attn.k_norm.scale')) |
| 301 | emit4(fid, layers, tensors, f'{at}.attn.k.w', |
| 302 | rdr.dequant4(f'{at}.attn.k.w', kvrows, D)) |
| 303 | emit4(fid, layers, tensors, f'{at}.attn.v.w', |
| 304 | rdr.dequant4(f'{at}.attn.v.w', kvrows, D)) |
| 305 | emit4(fid, layers, tensors, f'{at}.attn.o.w', |
| 306 | rdr.dequant4(f'{at}.attn.attn_vec_einsum.w', D, qrows) / O_SCALE) |
| 307 | emit_vec(layers, tensors, f'{at}.post_attention_norm.scale', rdr.f32(f'{at}.post_attention_norm.scale')) |
| 308 | emit_vec(layers, tensors, f'{at}.pre_ffw_norm.scale', rdr.f32(f'{at}.pre_ffw_norm.scale')) |
| 309 | if slim: |
| 310 | emit4(fid, layers, tensors, f'{at}.mlp.gate.w', |
| 311 | dequant2(rdr, f'{at}.mlp.ff_gate.w', inner, D)) |
| 312 | emit4(fid, layers, tensors, f'{at}.mlp.ff1.w', |
| 313 | dequant2(rdr, f'{at}.mlp.ff1.w', inner, D) / FF1_SCALE) |
| 314 | emit4(fid, layers, tensors, f'{at}.mlp.linear.w', |
| 315 | dequant2(rdr, f'{at}.mlp.linear.w', D, inner)) |
| 316 | else: |
| 317 | emit4(fid, layers, tensors, f'{at}.mlp.gate.w', |
| 318 | rdr.dequant4(f'{at}.mlp.ff_gate.w', 6144, D)) |
| 319 | emit4(fid, layers, tensors, f'{at}.mlp.ff1.w', |
| 320 | rdr.dequant4(f'{at}.mlp.ff1.w', 6144, D) / FF1_SCALE) |
| 321 | emit4(fid, layers, tensors, f'{at}.mlp.linear.w', |
| 322 | rdr.dequant4(f'{at}.mlp.linear.w', D, 6144)) |
| 323 | emit_vec(layers, tensors, f'{at}.post_ffw_norm.scale', rdr.f32(f'{at}.post_ffw_norm.scale')) |
| 324 | emit8(fid, layers, tensors, f'{at}.per_layer.gate.w', |
| 325 | rdr.dequant8(f'{at}.per_layer_embedding_gate.w', 256, 1536)) |
| 326 | emit8(fid, layers, tensors, f'{at}.per_layer.proj.w', |
| 327 | rdr.dequant8(f'{at}.per_layer_embedding_projection.w', 1536, 256) / PL_SCALE) |
| 328 | emit_vec(layers, tensors, f'{at}.post_per_layer_input_norm.scale', |
| 329 | rdr.f32(f'{at}.post_per_layer_input_norm.scale')) |
| 330 | # Skip multiplier: the reference scales the whole residual (x + branch) |
| 331 | # by this AFTER add2 (`_maybe_apply_skip_scale/mul` in S10). Missing it |
| 332 | # leaves layer 0 at min -173.6/max 11.6 vs ideal -4.66/0.32 (37x = the |
| 333 | # missing 0.027) and corrupts every downstream residual direction. |
| 334 | # A 1-elem fp16 tensor consumed by Builder::mul_scalar. The assert is the |
| 335 | # point: a file variant with a wider skip tensor must fail here rather |
| 336 | # than silently taking its first element. |
| 337 | skip_raw = rdr.f32(f'{at}.skip.scale') |
| 338 | assert skip_raw.size == 1, f'{at}.skip.scale: {skip_raw.size} elems, not 1' |
| 339 | skip = np.ascontiguousarray(skip_raw[:1], dtype=np.float32) |
| 340 | tensors.append(skip) |
| 341 | layers.append(mc.Layer(len(layers), 'MulScalar', f'{at}.skip.scale', |
| 342 | 'MulScalar s=[1]', len(tensors) - 1, 1)) |
| 343 | fid.report(mc.MIN_INT4_COSINE) |
| 344 | return layers, tensors |
| 345 | |
| 346 | |
| 347 | def collect_embed(rdr): |
| 348 | """gemma4_embed: working table + shared projection + 35 mmap tables + norms. |
| 349 | |
| 350 | STORAGE DECODINGS (verified by byte counts + consumer dims): |
| 351 | - input_embedding: exact S2 `embedder` fp32 rows [262144, 1536] via |
| 352 | GEMMA4_EMBED_DUMP (gemma4_embed_dump.py); the artisan 2-bit packing is |
| 353 | undecoded, legacy `(vals - 1.5) * s` path is approximate only. |
| 354 | Token hidden rows + TIED head source. |
| 355 | - per_layer_embeddings[L]: INT4 [262144, 256] in U8-typed storage |
| 356 | (33.5MB = 262144x256/2), 1 fp32 scale/row. Nibbles are SIGNED (-8..7), |
| 357 | same as every other int4 table. The per-layer |
| 358 | path is 256-wide (gate [256,1536] takes hidden, output modulates the row). |
| 359 | - per_layer_model_projection: INT8 [8960, 1536] (35x256 stacked), 1/row. |
| 360 | """ |
| 361 | layers, tensors = [], [] |
| 362 | fid = mc.Fidelity() |
| 363 | # working table: exact S2 fp32 rows, required. The artisan 2-bit packing of |
| 364 | # `input_embedding.w` is undecoded - every mapping tried gives cosine ~0 vs |
| 365 | # S2 rows - and the legacy `(vals - 1.5)` guess below it is uncorrelated |
| 366 | # with the true embeddings (measured cosine ~-0.03 on sample rows), so |
| 367 | # silently emitting it would ship a garbage working table and a garbage |
| 368 | # tied head. Produce the dump with scripts/ml/gemma4_embed_dump.py and pass |
| 369 | # it as GEMMA4_EMBED_DUMP; refusing here is what makes a missing dump a |
| 370 | # loud build failure rather than a fluent wrong model. |
| 371 | dump = os.environ.get('GEMMA4_EMBED_DUMP') |
| 372 | if not dump or not os.path.exists(dump): |
| 373 | raise SystemExit( |
| 374 | 'collect_embed needs GEMMA4_EMBED_DUMP=<embed_s2_fp32.bin> ' |
| 375 | '(scripts/ml/gemma4_embed_dump.py); the in-file fallback is ' |
| 376 | 'proven uncorrelated with the true rows and is no longer emitted') |
| 377 | out = np.memmap(dump, dtype=np.float32, mode='r', |
| 378 | shape=(262144, 1536)).astype(np.float32) |
| 379 | m = float(np.abs(out).mean()) |
| 380 | print(f'input_embedding S2 dump {dump}: mean abs {m:.4f}') |
| 381 | codes, scale = fid.quantise4('input_embedding', out) |
| 382 | bias = np.zeros(262144, dtype=np.float32) |
| 383 | tensors.extend([codes, scale, bias]) |
| 384 | layers.append(mc.Layer(len(layers), 'Embedding4', 'input_embedding', |
| 385 | 'Embedding4 2-bit source', len(tensors) - 3, 3)) |
| 386 | emit8(fid, layers, tensors, 'transformer.embedder.per_layer_model_projection.w', |
| 387 | rdr.dequant8('transformer.embedder.per_layer_model_projection.w', 8960, 1536)) |
| 388 | emit_vec(layers, tensors, 'transformer.embedder.per_layer_projection_norm.scale', |
| 389 | rdr.f32('transformer.embedder.per_layer_projection_norm.scale')) |
| 390 | for index in range(35): |
| 391 | at = f'transformer.layer_{index}.per_layer_embeddings.w' |
| 392 | w = np.frombuffer(rdr.raw(at), dtype=np.uint8) |
| 393 | assert w.size >= 262144 * 128, f'{at}: {w.size}' |
| 394 | w = w[:262144 * 128] |
| 395 | # INT4 nibbles packed in U8 storage: 128 bytes = 256 nibbles per row. |
| 396 | # SIGNED nibbles (proven cos 1.0000 vs base S3): sign-extend, no zp. |
| 397 | lo = (w & 0xF).astype(np.float32) |
| 398 | hi = ((w >> 4) & 0xF).astype(np.float32) |
| 399 | flat = np.empty(262144 * 256, dtype=np.float32) |
| 400 | flat[0::2] = lo |
| 401 | flat[1::2] = hi |
| 402 | flat = np.where(flat >= 8, flat - 16, flat).reshape(262144, 256) |
| 403 | s = np.frombuffer(rdr.raw(at + '_quantized_scale'), dtype=np.float32) |
| 404 | assert s.size == 262144, f'{at} scales: {s.size}' |
| 405 | out = flat * s[:, None] |
| 406 | codes, scale = fid.quantise4(f'layer_{index}.per_layer_embeddings', out) |
| 407 | bias = np.zeros(262144, dtype=np.float32) |
| 408 | tensors.extend([codes, scale, bias]) |
| 409 | layers.append(mc.Layer(len(layers), 'Linear4', f'layer_{index}.per_layer_embeddings', |
| 410 | 'Linear4 mmap table', len(tensors) - 3, 3)) |
| 411 | fid.report(mc.MIN_INT4_COSINE) |
| 412 | return layers, tensors |
| 413 | |
| 414 | |
| 415 | def main(): |
| 416 | ap = argparse.ArgumentParser() |
| 417 | ap.add_argument('--model', required=True) |
| 418 | ap.add_argument('-o', '--outdir', required=True) |
| 419 | ap.add_argument('--print-digest', action='store_true') |
| 420 | ap.add_argument('--rope-theta', type=float, default=None, |
| 421 | help='RoPE base frequency for BOTH tables (bisect escape hatch; ' |
| 422 | 'default: 1e4 sliding / 1e6 full, read off the base bundle)') |
| 423 | args = ap.parse_args() |
| 424 | os.makedirs(args.outdir, exist_ok=True) |
| 425 | rdr = LitertlmReader(args.model) |
| 426 | print('tensors:', len(rdr.tensors)) |
| 427 | theta = args.rope_theta |
| 428 | layers, tensors = collect_text( |
| 429 | rdr, |
| 430 | rope_theta_local=theta if theta is not None else 10000.0, |
| 431 | rope_theta_global=theta if theta is not None else 1000000.0, |
| 432 | ) |
| 433 | digest = mc.layer_table_digest(layers) |
| 434 | print(f'gemma4_text: {len(layers)} layers, {len(tensors)} tensors, digest {digest}') |
| 435 | import hashlib |
| 436 | sha = hashlib.sha256(open(args.model, 'rb').read()).digest() |
| 437 | blob, count = mc.build(layers, tensors, mc.GRAPHS['gemma4_text'], sha) |
| 438 | out = os.path.join(args.outdir, 'gemma4_text.maml') |
| 439 | open(out, 'wb').write(blob) |
| 440 | print(f'wrote {out} ({len(blob)} bytes)') |
| 441 | elayers, etensors = collect_embed(rdr) |
| 442 | edigest = mc.layer_table_digest(elayers) |
| 443 | print(f'gemma4_embed: {len(elayers)} layers, {len(etensors)} tensors, digest {edigest}') |
| 444 | eblob, ecount = mc.build(elayers, etensors, mc.GRAPHS['gemma4_embed'], sha) |
| 445 | eout = os.path.join(args.outdir, 'gemma4_embed.maml') |
| 446 | open(eout, 'wb').write(eblob) |
| 447 | print(f'wrote {eout} ({len(eblob)} bytes)') |
| 448 | |
| 449 | |
| 450 | if __name__ == '__main__': |
| 451 | main() |