|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Layer-by-layer diff: HF reference npz vs our engine's raw bin dumps. |
| 3 | +
|
| 4 | +Generalized from tools/pillar1/diff_layers.py. Produces a tabular report |
| 5 | +and exits 0 (PASS) / 1 (FAIL) based on thresholds. |
| 6 | +
|
| 7 | +Usage: |
| 8 | + python diff_layers.py ref.npz engine_dump/ \ |
| 9 | + --threshold-l2-rel 0.05 \ |
| 10 | + --threshold-cosine 0.90 |
| 11 | +
|
| 12 | +Output (stdout): |
| 13 | + slot dim us_norm hf_norm max_abs L2_rel cosine [PASS|FAIL] |
| 14 | + emb ... |
| 15 | + h0 ... |
| 16 | + ... |
| 17 | + → PASS / FAIL — first divergence at layer X |
| 18 | +
|
| 19 | +Exit codes: |
| 20 | + 0 — all layers within threshold |
| 21 | + 1 — divergence detected; diff report identifies layer |
| 22 | + 2 — environment / config error |
| 23 | +""" |
| 24 | +import argparse |
| 25 | +import os |
| 26 | +import sys |
| 27 | + |
| 28 | +import numpy as np |
| 29 | + |
| 30 | + |
| 31 | +def read_bin(path: str) -> np.ndarray: |
| 32 | + return np.fromfile(path, dtype=np.float32) |
| 33 | + |
| 34 | + |
| 35 | +def compare(hf_vec: np.ndarray, us_vec: np.ndarray): |
| 36 | + diff = us_vec - hf_vec |
| 37 | + max_abs = float(np.max(np.abs(diff))) if diff.size else 0.0 |
| 38 | + l2 = float(np.linalg.norm(diff)) |
| 39 | + hf_norm = float(np.linalg.norm(hf_vec)) |
| 40 | + us_norm = float(np.linalg.norm(us_vec)) |
| 41 | + l2_rel = l2 / max(hf_norm, 1e-9) |
| 42 | + denom = max(us_norm * hf_norm, 1e-9) |
| 43 | + cosine = float(np.dot(us_vec, hf_vec) / denom) |
| 44 | + return us_norm, hf_norm, max_abs, l2_rel, cosine |
| 45 | + |
| 46 | + |
| 47 | +def main(): |
| 48 | + ap = argparse.ArgumentParser() |
| 49 | + ap.add_argument("ref_npz", help="HF reference .npz") |
| 50 | + ap.add_argument("engine_dir", help="engine dump directory") |
| 51 | + ap.add_argument("--pos", type=int, default=None, |
| 52 | + help="position to compare in HF (default: 0 — matches " |
| 53 | + "engine's TQ_DUMP_POS=0 default)") |
| 54 | + ap.add_argument("--threshold-l2-rel", type=float, default=0.05, |
| 55 | + help="max L2_rel per hidden layer (default 0.05 = 5%%)") |
| 56 | + ap.add_argument("--threshold-cosine", type=float, default=0.90, |
| 57 | + help="min cosine similarity at logits (default 0.90)") |
| 58 | + args = ap.parse_args() |
| 59 | + |
| 60 | + try: |
| 61 | + hf = np.load(args.ref_npz) |
| 62 | + except Exception as e: |
| 63 | + print(f"error: cannot load {args.ref_npz}: {e}", file=sys.stderr) |
| 64 | + return 2 |
| 65 | + |
| 66 | + # Engine's TQ_DUMP_HIDDEN default is pos=0 (first token); align by default |
| 67 | + seq_len = hf["h0"].shape[0] if hf["h0"].ndim == 2 else 1 |
| 68 | + pos = 0 if args.pos is None else args.pos |
| 69 | + if pos >= seq_len: |
| 70 | + print(f"error: pos {pos} >= seq_len {seq_len}", file=sys.stderr) |
| 71 | + return 2 |
| 72 | + |
| 73 | + # Determine layer count from engine dumps |
| 74 | + engine_files = os.listdir(args.engine_dir) |
| 75 | + max_h = -1 |
| 76 | + for f in engine_files: |
| 77 | + if f.startswith("h") and f.endswith(".bin"): |
| 78 | + try: |
| 79 | + max_h = max(max_h, int(f[1:-4])) |
| 80 | + except ValueError: |
| 81 | + pass |
| 82 | + slots = ["emb"] + [f"h{i}" for i in range(max_h + 1)] |
| 83 | + has_post_norm = os.path.exists(os.path.join(args.engine_dir, "post_norm.bin")) |
| 84 | + if has_post_norm: |
| 85 | + slots.append("post_norm") |
| 86 | + |
| 87 | + print(f"{'slot':<12} {'dim':>6} {'us_norm':>10} {'hf_norm':>10} " |
| 88 | + f"{'max_abs':>10} {'L2_rel':>10} {'cosine':>8} status") |
| 89 | + print("-" * 85) |
| 90 | + |
| 91 | + first_fail = None |
| 92 | + all_rows = [] |
| 93 | + for slot in slots: |
| 94 | + bin_path = os.path.join(args.engine_dir, f"{slot}.bin") |
| 95 | + if not os.path.exists(bin_path): |
| 96 | + continue |
| 97 | + us = read_bin(bin_path) |
| 98 | + if slot == "post_norm": |
| 99 | + # HF npz doesn't usually have post_norm; skip if absent |
| 100 | + if "post_norm" not in hf.files: |
| 101 | + continue |
| 102 | + hf_arr = hf["post_norm"] |
| 103 | + hf_vec = hf_arr[pos] if hf_arr.ndim == 2 else hf_arr |
| 104 | + else: |
| 105 | + if slot not in hf.files: |
| 106 | + continue |
| 107 | + hf_arr = hf[slot] |
| 108 | + hf_vec = hf_arr[pos] if hf_arr.ndim == 2 else hf_arr |
| 109 | + |
| 110 | + if us.shape != hf_vec.shape: |
| 111 | + print(f"{slot:<12} shape mismatch us={us.shape} hf={hf_vec.shape}") |
| 112 | + continue |
| 113 | + |
| 114 | + us_norm, hf_norm, max_abs, l2_rel, cosine = compare(hf_vec, us) |
| 115 | + status = "PASS" |
| 116 | + if l2_rel > args.threshold_l2_rel: |
| 117 | + status = "FAIL" |
| 118 | + if first_fail is None: |
| 119 | + first_fail = slot |
| 120 | + |
| 121 | + print(f"{slot:<12} {len(us):>6} {us_norm:>10.3f} {hf_norm:>10.3f} " |
| 122 | + f"{max_abs:>10.4f} {l2_rel:>10.4%} {cosine:>8.4f} {status}") |
| 123 | + all_rows.append((slot, status, l2_rel, cosine)) |
| 124 | + |
| 125 | + # Compare top-5 logits |
| 126 | + logits_path = os.path.join(args.engine_dir, "logits.bin") |
| 127 | + logits_pass = True |
| 128 | + if os.path.exists(logits_path) and "logits" in hf.files: |
| 129 | + us_l = read_bin(logits_path) |
| 130 | + hf_l = hf["logits"][pos] if hf["logits"].ndim == 2 else hf["logits"] |
| 131 | + if us_l.shape == hf_l.shape: |
| 132 | + top1_us = int(us_l.argmax()) |
| 133 | + top1_hf = int(hf_l.argmax()) |
| 134 | + cos_l = float(np.dot(us_l, hf_l) / |
| 135 | + max(np.linalg.norm(us_l) * np.linalg.norm(hf_l), 1e-9)) |
| 136 | + print() |
| 137 | + print(f"logits cosine={cos_l:.4f} top1 hf={top1_hf} us={top1_us} " |
| 138 | + f"{'PASS' if (cos_l >= args.threshold_cosine and top1_us == top1_hf) else 'FAIL'}") |
| 139 | + if cos_l < args.threshold_cosine or top1_us != top1_hf: |
| 140 | + logits_pass = False |
| 141 | + if first_fail is None: |
| 142 | + first_fail = "logits" |
| 143 | + |
| 144 | + print() |
| 145 | + if first_fail is None and logits_pass: |
| 146 | + print("→ PASS — all layers within threshold") |
| 147 | + return 0 |
| 148 | + else: |
| 149 | + print(f"→ FAIL — first divergence at {first_fail}") |
| 150 | + return 1 |
| 151 | + |
| 152 | + |
| 153 | +if __name__ == "__main__": |
| 154 | + sys.exit(main()) |
0 commit comments