|
| 1 | +"""Gemma-4-26B heterogeneous-head_dim check / repro / fix verification. |
| 2 | +
|
| 3 | +Gemma-4 uses head_dim=256 (sliding_attention layers) and global_head_dim=512 |
| 4 | +(full_attention layers). This script: |
| 5 | + 1. loads the model (text-only generate), |
| 6 | + 2. inspects the per-layer K head_dim from a bf16 DynamicCache, |
| 7 | + 3. tries KakeyaLatticePackedCache (E8 Q=38) and reports success/CR/coherence |
| 8 | + or the assertion (pre-fix repro). |
| 9 | +""" |
| 10 | +from __future__ import annotations |
| 11 | +import argparse, json, os, traceback |
| 12 | +import torch |
| 13 | +from transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache |
| 14 | +from kakeyalattice.hf import KakeyaLatticePackedCache |
| 15 | + |
| 16 | + |
| 17 | +def layer_kv_dims(cache): |
| 18 | + dims = [] |
| 19 | + if hasattr(cache, "layers"): |
| 20 | + for layer in cache.layers: |
| 21 | + k = getattr(layer, "keys", None) |
| 22 | + dims.append(None if k is None else int(k.shape[-1])) |
| 23 | + return dims |
| 24 | + |
| 25 | + |
| 26 | +def main(): |
| 27 | + ap = argparse.ArgumentParser() |
| 28 | + ap.add_argument("--model", default="google/gemma-4-26B-A4B-it") |
| 29 | + ap.add_argument("--max-new", type=int, default=24) |
| 30 | + ap.add_argument("--out", default="/root/kakeyalattice-test/reports/v1_5_release/gemma4_hetero_headdim_2026-06-15/gemma4_check.json") |
| 31 | + args = ap.parse_args() |
| 32 | + dev = "cuda" |
| 33 | + tok = AutoTokenizer.from_pretrained(args.model) |
| 34 | + model = AutoModelForCausalLM.from_pretrained(args.model, dtype=torch.bfloat16, device_map=dev).eval() |
| 35 | + cfg = model.config |
| 36 | + tcfg = getattr(cfg, "text_config", cfg) |
| 37 | + L = tcfg.num_hidden_layers |
| 38 | + hd = getattr(tcfg, "head_dim", None) |
| 39 | + ghd = getattr(tcfg, "global_head_dim", None) |
| 40 | + print(f"[cfg] layers={L} head_dim={hd} global_head_dim={ghd}", flush=True) |
| 41 | + print(f"[cfg] layer_types={getattr(tcfg,'layer_types',None)}", flush=True) |
| 42 | + |
| 43 | + msgs = [{"role": "user", "content": "In one sentence, what is lattice quantization?"}] |
| 44 | + enc = tok.apply_chat_template(msgs, add_generation_prompt=True, return_tensors="pt", return_dict=True) |
| 45 | + ids = enc["input_ids"].to(dev) |
| 46 | + in_len = ids.shape[1] |
| 47 | + gen = dict(max_new_tokens=args.max_new, do_sample=False, use_cache=True) |
| 48 | + |
| 49 | + report = {"model": args.model, "layers": L, "head_dim": hd, "global_head_dim": ghd} |
| 50 | + |
| 51 | + # 1) bf16 baseline + per-layer K dims |
| 52 | + cacheA = DynamicCache() |
| 53 | + with torch.inference_mode(): |
| 54 | + outA = model.generate(ids, past_key_values=cacheA, **gen) |
| 55 | + dimsA = layer_kv_dims(cacheA) |
| 56 | + base_bytes = sum( |
| 57 | + (layer.keys.element_size()*layer.keys.numel() + layer.values.element_size()*layer.values.numel()) |
| 58 | + for layer in cacheA.layers if getattr(layer, "keys", None) is not None) |
| 59 | + textA = tok.decode(outA[0][in_len:], skip_special_tokens=True) |
| 60 | + print(f"[bf16] per-layer K head_dim = {dimsA}", flush=True) |
| 61 | + print(f"[bf16] distinct dims = {sorted(set(d for d in dimsA if d))}", flush=True) |
| 62 | + print(f"[bf16] text: {textA[:160]}", flush=True) |
| 63 | + report["per_layer_kv_dim"] = dimsA |
| 64 | + report["distinct_dims"] = sorted(set(d for d in dimsA if d)) |
| 65 | + report["bf16_text"] = textA |
| 66 | + report["bf16_kv_bytes"] = base_bytes |
| 67 | + seqA = int(outA.shape[1]); del cacheA, outA; torch.cuda.empty_cache() |
| 68 | + |
| 69 | + # 2) packed cache (E8 Q=38) |
| 70 | + try: |
| 71 | + cacheB = KakeyaLatticePackedCache(variant="e8", q_range=38, |
| 72 | + num_hidden_layers=L, head_dim=hd or 256, device=dev) |
| 73 | + with torch.inference_mode(): |
| 74 | + outB = model.generate(ids, past_key_values=cacheB, **gen) |
| 75 | + textB = tok.decode(outB[0][in_len:], skip_special_tokens=True) |
| 76 | + kb = cacheB.kv_storage_bytes() |
| 77 | + cr = base_bytes / kb if kb else None |
| 78 | + codec_dims = {li: (c.D_shape if c is not None else None) |
| 79 | + for li, c in enumerate(cacheB._codecs)} |
| 80 | + print(f"[packed] OK seq={int(outB.shape[1])} kv={kb/2**20:.2f}MiB realCR={cr:.3f}x lossless={cacheB.packed_pack_unpack_ok()}", flush=True) |
| 81 | + print(f"[packed] per-layer codec D_shape = {codec_dims}", flush=True) |
| 82 | + print(f"[packed] text: {textB[:160]}", flush=True) |
| 83 | + report.update({"packed_ok": True, "packed_kv_bytes": kb, "packed_real_cr": cr, |
| 84 | + "packed_text": textB, "codec_dims": codec_dims, |
| 85 | + "lossless": cacheB.packed_pack_unpack_ok()}) |
| 86 | + except Exception as e: |
| 87 | + print(f"[packed] FAILED: {type(e).__name__}: {e}", flush=True) |
| 88 | + traceback.print_exc() |
| 89 | + report.update({"packed_ok": False, "error": f"{type(e).__name__}: {e}"}) |
| 90 | + |
| 91 | + os.makedirs(os.path.dirname(args.out), exist_ok=True) |
| 92 | + with open(args.out, "w") as f: |
| 93 | + json.dump(report, f, indent=2, default=str) |
| 94 | + print(f"[out] {args.out}", flush=True) |
| 95 | + |
| 96 | + |
| 97 | +if __name__ == "__main__": |
| 98 | + main() |
0 commit comments