Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / gemma4_embed_dump.py
gemma4_embed_dump.py79 lines · 3.3 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Dump all 262144 S2 embedder rows to exact fp32 (A1 fallback). |
| 3 | |
| 4 | The artisan 2-bit `input_embedding.w` packing is undecoded (every mapping |
| 5 | tried gives cosine ~0 vs S2 rows, histograms differ, no row permutation |
| 6 | helps). S2's own `embedder` signature output IS the reference embedding the |
| 7 | converter claims to transcribe, so dump it directly and hand the exact rows |
| 8 | to the existing `fid.quantise4` path in `collect_embed`. |
| 9 | |
| 10 | Writes raw fp32 [262144, 1536] to the given path (~1.6GB; read back with |
| 11 | `np.memmap(path, dtype=np.float32, shape=(262144, 1536))`). Fast (~1 min: |
| 12 | the signature is a gather+mul at ~5us/call). |
| 13 | |
| 14 | python scripts/ml/gemma4_embed_dump.py -o build/gemma4/embed_s2_fp32.bin |
| 15 | """ |
| 16 | import argparse |
| 17 | import os |
| 18 | import sys |
| 19 | import time |
| 20 | |
| 21 | import numpy as np |
| 22 | |
| 23 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 24 | |
| 25 | VOCAB = 262144 |
| 26 | DIM = 1536 |
| 27 | |
| 28 | |
| 29 | def main(): |
| 30 | ap = argparse.ArgumentParser(description=__doc__) |
| 31 | ap.add_argument("-o", "--out", required=True, help="output raw fp32 path (.bin)") |
| 32 | ap.add_argument("--s2", default="analysis/base-sections/Section2_TFLiteModel_tf_lite_embedder.tflite") |
| 33 | ap.add_argument("--resume", action="store_true", |
| 34 | help="continue into existing .npy, skipping nonzero rows") |
| 35 | args = ap.parse_args() |
| 36 | |
| 37 | from ai_edge_litert.interpreter import Interpreter |
| 38 | s2 = Interpreter(model_path=args.s2).get_signature_runner("embedder") |
| 39 | |
| 40 | if args.resume and os.path.exists(args.out): |
| 41 | all_rows = np.memmap(args.out, dtype=np.float32, mode="r+", shape=(VOCAB, DIM)) |
| 42 | done = int((all_rows.any(axis=1)).sum()) |
| 43 | print(f"resuming {args.out}: {done}/{VOCAB} rows present") |
| 44 | start = done |
| 45 | else: |
| 46 | os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) |
| 47 | all_rows = np.memmap(args.out, dtype=np.float32, mode="w+", shape=(VOCAB, DIM)) |
| 48 | start = 0 |
| 49 | # probe row 0 to fail fast on a bad section file |
| 50 | probe = s2(token_ids=np.array([[0]], np.int32))["embeddings"].ravel() |
| 51 | assert probe.shape == (DIM,), probe.shape |
| 52 | print(f"probe row 0: rms {float(np.sqrt((probe.astype(np.float64) ** 2).mean())):.4f}") |
| 53 | |
| 54 | t0 = time.time() |
| 55 | for tok in range(start, VOCAB): |
| 56 | row = s2(token_ids=np.array([[tok]], np.int32))["embeddings"].ravel() |
| 57 | all_rows[tok] = row |
| 58 | if (tok + 1) % 32768 == 0: |
| 59 | dt = time.time() - t0 |
| 60 | print(f" {tok + 1}/{VOCAB} ({dt:.0f}s, {(tok + 1 - start) / dt:.0f} rows/s)", |
| 61 | flush=True) |
| 62 | all_rows.flush() |
| 63 | dt = time.time() - t0 |
| 64 | print(f"wrote {args.out} ({VOCAB}x{DIM} fp32) in {dt:.0f}s") |
| 65 | # validate: reload rows for the parity prompt tokens and compare vs live S2 |
| 66 | check = np.memmap(args.out, dtype=np.float32, mode="r", shape=(VOCAB, DIM)) |
| 67 | worst = 0.0 |
| 68 | for tok in [2, 818, 5279, 529, 7001, 563]: |
| 69 | live = s2(token_ids=np.array([[tok]], np.int32))["embeddings"].ravel().astype(np.float64) |
| 70 | got = check[tok].astype(np.float64) |
| 71 | cos = float(live @ got / max(1e-30, np.linalg.norm(live) * np.linalg.norm(got))) |
| 72 | worst = max(worst, abs(1.0 - cos)) |
| 73 | print(f" tok {tok}: dump-vs-live cosine {cos:.6f}") |
| 74 | assert worst < 1e-6, f"dump mismatch: {worst}" |
| 75 | print("dump self-check PASS") |
| 76 | |
| 77 | |
| 78 | if __name__ == "__main__": |
| 79 | raise SystemExit(main()) |