Download code/tt_dsocr/tests/dev_decoder.py from changh95/DeepSeek-OCR-2: direct link, hf CLI and curl.
- Browser
- Download file 7.8 kB
-
https://huggingface.co/changh95/DeepSeek-OCR-2/resolve/main/code/tt_dsocr/tests/dev_decoder.py
- Command line
-
hf download hf://changh95/DeepSeek-OCR-2/code/tt_dsocr/tests/dev_decoder.py
-
curl -L -o dev_decoder.py https://huggingface.co/changh95/DeepSeek-OCR-2/resolve/main/code/tt_dsocr/tests/dev_decoder.py
7.8 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Device check of the ttnn decoder (prefill + decode) against the official fp32 goldens, fed with the golden image | |
| embedding rows (decoder only: the vision encoder is checked by dev_vision.py). | |
| bin/devrun -t 900 -- python -u common/dsocr/tt_dsocr/tests/dev_decoder.py --cases formula_quad__tiny \ | |
| [--tf-steps 64] [--gen 64] [--trace] [--mlp bfp8 --experts bfp8 --head bf16] | |
| Per case: prefill logits vs golden step 0 (PCC, top-1), routing of every prompt row (top-6 set agreement), teacher- | |
| forced decode over the golden tokens (TVD over the golden top-128 + rest mass, top-1), free greedy decode (tokens vs | |
| golden), ms / step. Results -> assets/dsocr/runs/dec_<tag>.json. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| import torch | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(HERE))) | |
| from tt_dsocr.reference import model as R # noqa: E402 | |
| from tt_dsocr.tests._paths import GOLDEN, MODELS, RUNS # noqa: E402 | |
| def pcc(a, b): | |
| a, b = a.double().flatten(), b.double().flatten() | |
| a, b = a - a.mean(), b - b.mean() | |
| return float((a @ b) / (a.norm() * b.norm() + 1e-30)) | |
| def tvd_top(logits: torch.Tensor, top_v, top_i, lse) -> float: | |
| p = torch.softmax(logits.float(), -1) | |
| gp = (top_v.float() - lse.float()).exp() | |
| gi = top_i.long() | |
| return 0.5 * float((p[gi] - gp).abs().sum() + ((1 - p[gi].sum()) - (1 - gp.sum())).abs()) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--variant", default="deepseek-ocr") | |
| ap.add_argument("--cases", default="formula_quad__tiny") | |
| ap.add_argument("--tf-steps", type=int, default=64) | |
| ap.add_argument("--gen", type=int, default=0) | |
| ap.add_argument("--trace", action="store_true") | |
| ap.add_argument("--attn", default="bf16") | |
| ap.add_argument("--mlp", default="bfp8") | |
| ap.add_argument("--experts", default="bfp8") | |
| ap.add_argument("--head", default="bf16") | |
| ap.add_argument("--fidelity", default="HiFi2") | |
| ap.add_argument("--tag", default="") | |
| args = ap.parse_args() | |
| import ttnn | |
| from tt_dsocr.ttaw.device import open_device, close_device | |
| from tt_dsocr.tt.ttnn_decoder import TtnnDecoder | |
| gdir = GOLDEN[args.variant] | |
| cases = [] | |
| for c in args.cases.split(","): | |
| d = os.path.join(gdir, c) | |
| cases.append((c, json.load(open(os.path.join(d, "meta.json"))), | |
| torch.load(os.path.join(d, "tensors.pt"), weights_only=True), | |
| torch.load(os.path.join(d, "steps.pt"), weights_only=True))) | |
| W = R.Weights(MODELS[args.variant]) | |
| log = lambda s: print(s, flush=True) # noqa: E731 | |
| Ls = [m["n_prompt"] for _, m, _, _ in cases] | |
| buckets = sorted({max(128, -(-L // 128) * 128) for L in Ls}) | |
| max_seq = max(L + len(m["gen_ids"]) for L, (_, m, _, _) in zip(Ls, cases)) + 64 | |
| dev = open_device(0, dispatch="eth", trace_region_size=512 << 20) | |
| res = {"args": vars(args), "cases": {}} | |
| gg = dev.compute_with_storage_grid_size() | |
| geo = {"grid": [int(gg.x), int(gg.y)]} | |
| for k, noc in (("opt0", ttnn.NOC.NOC_0), ("opt1", ttnn.NOC.NOC_1)): | |
| geo[k] = [[int(c.x), int(c.y)] for c in dev.get_optimal_dram_bank_to_logical_worker_assignment(noc)] | |
| os.makedirs(os.path.join(RUNS, "..", "cache"), exist_ok=True) | |
| json.dump(geo, open(os.path.join(RUNS, "..", "cache", "geo.json"), "w")) | |
| log(f"[dev_decoder] geometry {geo}") | |
| try: | |
| t0 = time.time() | |
| dec = TtnnDecoder(dev, W, buckets, max_seq, attn_dtype=args.attn, mlp_dtype=args.mlp, | |
| expert_dtype=args.experts, head_dtype=args.head, pre_fidelity=args.fidelity) | |
| log(f"[dev_decoder] weights up in {time.time() - t0:.0f} s, buckets {buckets}, max_seq {dec.max_seq}") | |
| embed = W.get("model.embed_tokens.weight") | |
| for name, meta, gt, gs in cases: | |
| r = {} | |
| ids, L, gen = meta["input_ids"], meta["n_prompt"], meta["gen_ids"] | |
| rows = embed[torch.tensor(ids)].clone() | |
| m = gt["seq_mask"] | |
| rows[m] = gt["img_emb"] | |
| stages = {} | |
| t0 = time.time() | |
| dec.prefill(rows, L, stages=stages) | |
| lg = dec.logits_host() | |
| ttnn.synchronize_device(dev) | |
| r["prefill_eager_s"] = time.time() - t0 | |
| r["prefill_pcc"] = pcc(lg, gs["logits16"][0].float()) | |
| r["prefill_top1"] = int(lg.argmax()) == int(gs["top_i"][0][0]) | |
| r["prefill_tvd"] = tvd_top(lg, gs["top_v"][0], gs["top_i"][0], gs["lse"][0]) | |
| agree = [] | |
| for i in range(1, 12): | |
| w = ttnn.to_torch(stages[f"route{i}"]).float().reshape(-1, 64)[:L] | |
| dev_sets = (w > 0) | |
| gid = gt["pre_route_ids"][i - 1].long() | |
| gold = torch.zeros(L, 64, dtype=torch.bool) | |
| gold.scatter_(1, gid, True) | |
| agree.append(float((dev_sets == gold).all(-1).float().mean())) | |
| r["route_agree_prompt"] = agree | |
| log(f"[{name}] L {L}: prefill PCC {r['prefill_pcc']:.5f} top1 {r['prefill_top1']} TVD " | |
| f"{r['prefill_tvd']:.4f}; routing agreement per MoE layer min {min(agree):.4f} mean " | |
| f"{sum(agree) / len(agree):.4f} ({r['prefill_eager_s']:.1f} s eager)") | |
| # teacher-forced decode over the golden tokens | |
| T = min(args.tf_steps, len(gen)) | |
| tv, t1 = [], 0 | |
| tt = [] | |
| for s in range(1, T): | |
| t0 = time.time() | |
| dec.step(gen[s - 1], L + s - 1) | |
| l = dec.logits_host() | |
| tt.append(time.time() - t0) | |
| tv.append(tvd_top(l, gs["top_v"][s], gs["top_i"][s], gs["lse"][s])) | |
| t1 += int(int(l.argmax()) == int(gs["top_i"][s][0])) | |
| if tv: | |
| tvs = torch.tensor(tv) | |
| r.update(tf_steps=len(tv), tf_tvd_mean=float(tvs.mean()), tf_tvd_p95=float(tvs.quantile(0.95)), | |
| tf_tvd_max=float(tvs.max()), tf_top1=t1 / len(tv), step_eager_ms=1e3 * sum(tt) / len(tt)) | |
| log(f"[{name}] TF {len(tv)} steps: TVD mean {r['tf_tvd_mean']:.5f} p95 {r['tf_tvd_p95']:.5f} max " | |
| f"{r['tf_tvd_max']:.4f}, top-1 {r['tf_top1']:.4f}, {r['step_eager_ms']:.1f} ms / step eager") | |
| if args.gen: | |
| if args.trace and dec.loop_trace is None: | |
| dec.capture(prefill=False) | |
| dec.prefill(rows, L) | |
| tok = int(dec.logits_host().argmax()) | |
| out = [tok] | |
| t0 = time.time() | |
| pos = L | |
| while len(out) < min(args.gen, len(gen) + 8) and out[-1] != 1: | |
| toks = ttnn.to_torch(dec.loop(out[-1], pos)).reshape(-1).tolist() | |
| pos += len(toks) | |
| out += [int(t) for t in toks] | |
| dt = time.time() - t0 | |
| n = len(out) - 1 | |
| ref = gen[:len(out)] | |
| same = 0 | |
| while same < min(len(out), len(gen)) and out[same] == gen[same]: | |
| same += 1 | |
| r.update(gen_tokens=n, gen_ms_per_token=1e3 * dt / max(1, n), gen_prefix_match=same, | |
| gen_identical=out[:len(gen)] == gen[:len(out)]) | |
| log(f"[{name}] greedy loop: {n} tokens, {r['gen_ms_per_token']:.2f} ms / token " | |
| f"({'traced' if args.trace else 'eager'}), first {same} tokens identical to the golden") | |
| res["cases"][name] = r | |
| finally: | |
| os.makedirs(RUNS, exist_ok=True) | |
| json.dump(res, open(os.path.join(RUNS, f"dec_{args.tag or 'run'}.json"), "w"), indent=1) | |
| close_device(dev) | |
| if __name__ == "__main__": | |
| main() | |