glm53_tap_report.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. #!/usr/bin/env python3
  2. """Offline report over glm53_step_tap output.
  3. python3 glm53_tap_report.py DIR [--req SUBSTR] [--steps A-B] [--all-pairs]
  4. python3 glm53_tap_report.py --compare DECODE.pt PREFILL.pt --pos N [--rel 0.05]
  5. --compare diffs the row at absolute position N of two vector dumps (one from
  6. a decode step, one from a prefill replay of the same ids) checkpoint by
  7. checkpoint, in float, in the decode file's execution order, and flags the
  8. first checkpoint whose relative difference exceeds --rel. KDA state rows are
  9. absent from prefill dumps (one state per request), so the first divergence
  10. there is read from kda.qkv/g1/beta (layer input) vs kda.out (kernel output).
  11. DIR holds tap-rank<r>.jsonl for one or more ranks (copy each box's file into
  12. the same directory). Steps are aligned by their step number: every rank runs
  13. the same scheduler output sequence, so step N is the same batch on every rank.
  14. Sections:
  15. pairs per step, per pair: first checkpoint where the two rows differ
  16. (execution order), and the step a pair first split
  17. events host/device num_computed mismatch, SM90 planned!=valid,
  18. KDA state changed between steps, MLA cache row changed
  19. between steps, sampler argmax!=sampled
  20. ranks cross-rank disagreement on fed tokens, input ids, positions,
  21. slots, and every replicated checkpoint hash
  22. tokens per request: the token fed at each step on rank 0 (find the
  23. step where the wrong token appears, then look up the sections
  24. above at that step and the one before it)
  25. """
  26. from __future__ import annotations
  27. import argparse
  28. import glob
  29. import json
  30. import os
  31. import sys
  32. from collections import defaultdict
  33. SHARDED = ("kda.", "mla.q", "mla.out", "mla.kvidx", "mla.attn_out", "attn_mla.out", "attn_kda.out")
  34. def load(d: str):
  35. ranks = {}
  36. for p in sorted(glob.glob(os.path.join(d, "tap-rank*.jsonl"))):
  37. r = int(os.path.basename(p)[len("tap-rank") : -len(".jsonl")])
  38. recs = []
  39. hdr = None
  40. with open(p) as f:
  41. for line in f:
  42. line = line.strip()
  43. if not line:
  44. continue
  45. try:
  46. o = json.loads(line)
  47. except json.JSONDecodeError:
  48. continue
  49. if o.get("header"):
  50. hdr = o
  51. else:
  52. recs.append(o)
  53. ranks[r] = (hdr, {o["step"]: o for o in recs})
  54. return ranks
  55. def replicated(name: str) -> bool:
  56. return not any(s in name for s in SHARDED)
  57. def compare(a_path: str, b_path: str, pos: int, rel_thr: float) -> int:
  58. import torch
  59. A = torch.load(a_path, map_location="cpu")
  60. B = torch.load(b_path, map_location="cpu")
  61. def row_of(blob, name):
  62. cands = [i for i, r in enumerate(blob["rows"]) if r["pos"] == pos]
  63. if not cands:
  64. print(f"{name}: no row at pos {pos}; positions {sorted({r['pos'] for r in blob['rows']})[:12]}...")
  65. return None
  66. return cands[-1]
  67. ia, ib = row_of(A, a_path), row_of(B, b_path)
  68. if ia is None or ib is None:
  69. return 1
  70. print(f"row A {A['rows'][ia]}\nrow B {B['rows'][ib]}")
  71. first = None
  72. for name, ta in A["cps"].items():
  73. tb = B["cps"].get(name)
  74. if tb is None:
  75. continue
  76. va, vb = ta[ia].float().reshape(-1), tb[ib].float().reshape(-1)
  77. if va.numel() != vb.numel():
  78. print(f"{name:32s} shape mismatch {tuple(ta.shape)} vs {tuple(tb.shape)}")
  79. continue
  80. if ta.dtype in (torch.int32, torch.int64, torch.uint8, torch.int8):
  81. neq = int((va != vb).sum())
  82. mark = " <-- differs" if neq else ""
  83. print(f"{name:32s} int {neq} of {va.numel()} entries differ{mark}")
  84. if neq and first is None:
  85. first = name
  86. continue
  87. d = (va - vb).abs()
  88. rel = float(d.norm() / (vb.norm() + 1e-12))
  89. mark = ""
  90. if rel > rel_thr and first is None:
  91. first = name
  92. mark = " <-- FIRST above threshold"
  93. print(f"{name:32s} maxabs {float(d.max()):.4g} rel {rel:.4g} |B|max {float(vb.abs().max()):.4g}{mark}")
  94. print("\nfirst checkpoint above threshold:", first)
  95. return 0
  96. def main() -> int:
  97. ap = argparse.ArgumentParser()
  98. ap.add_argument("dir", nargs="?")
  99. ap.add_argument("--compare", nargs=2, metavar=("A.pt", "B.pt"))
  100. ap.add_argument("--pos", type=int)
  101. ap.add_argument("--rel", type=float, default=0.05)
  102. ap.add_argument("--req", default="")
  103. ap.add_argument("--steps", default="")
  104. ap.add_argument("--all-pairs", action="store_true", help="print every pair every step, not only splits")
  105. args = ap.parse_args()
  106. if args.compare:
  107. if args.pos is None:
  108. print("--compare needs --pos N (absolute position of the row)")
  109. return 2
  110. return compare(args.compare[0], args.compare[1], args.pos, args.rel)
  111. if not args.dir:
  112. ap.print_help()
  113. return 2
  114. ranks = load(args.dir)
  115. if not ranks:
  116. print("no tap-rank*.jsonl in", args.dir)
  117. return 1
  118. lo, hi = 0, 1 << 40
  119. if args.steps:
  120. a, _, b = args.steps.partition("-")
  121. lo, hi = int(a or 0), int(b or hi)
  122. def want(o):
  123. return lo <= o["step"] <= hi and (not args.req or any(args.req in x["req"] for x in o["rows"]))
  124. for r, (hdr, _) in sorted(ranks.items()):
  125. print(f"rank {r}: {json.dumps(hdr) if hdr else 'no header'}")
  126. r0 = min(ranks)
  127. steps0 = ranks[r0][1]
  128. print("\n== pairs ==")
  129. seen_split = set()
  130. for s in sorted(steps0):
  131. o = steps0[s]
  132. if not want(o):
  133. continue
  134. for p in o.get("pairs", []):
  135. key = (p["a"], p["b"])
  136. split = p.get("first_diff")
  137. if split and key not in seen_split:
  138. seen_split.add(key)
  139. print(f"step {s} pos {p['pos']} pair {p['a']} / {p['b']}: FIRST SPLIT at {split} "
  140. f"({p.get('ndiff')} of {p.get('ncp')} checkpoints differ; {p.get('first_diff_nbytes_ne')} bytes differ there)")
  141. print(" differing:", ", ".join(p.get("diffs", [])[:40]))
  142. elif args.all_pairs or (split and args.req):
  143. print(f"step {s} pos {p['pos']} pair {p['a']} / {p['b']}: {split or 'identical'} ({p.get('ndiff')}/{p.get('ncp')})")
  144. if not seen_split:
  145. print("(no pair split in the selected steps)")
  146. print("\n== events ==")
  147. n_ev = 0
  148. for r, (_, steps) in sorted(ranks.items()):
  149. for s in sorted(steps):
  150. o = steps[s]
  151. if not want(o):
  152. continue
  153. for k in ("host_dev_mismatch", "plan_mismatch", "state_changed", "kv_changed", "err"):
  154. v = o.get(k)
  155. if v:
  156. n_ev += 1
  157. print(f"rank {r} step {s} {k}: {json.dumps(v)[:600]}")
  158. for sm in o.get("sample", []):
  159. if sm.get("sampled") is not None and sm["sampled"] != sm["argmax"]:
  160. n_ev += 1
  161. print(f"rank {r} step {s} sampled!=argmax {sm}")
  162. if not n_ev:
  163. print("(none)")
  164. print("\n== ranks ==")
  165. if len(ranks) < 2:
  166. print("(single rank file; nothing to compare)")
  167. else:
  168. n_bad = 0
  169. for s in sorted(steps0):
  170. o0 = steps0[s]
  171. if not want(o0):
  172. continue
  173. others = [(r, ranks[r][1].get(s)) for r in sorted(ranks) if r != r0]
  174. for r, o in others:
  175. if o is None:
  176. print(f"step {s}: rank {r} has no record")
  177. n_bad += 1
  178. continue
  179. bad = []
  180. for f in ("fed", "nc_after", "sampled0"):
  181. if o0.get(f) != o.get(f):
  182. bad.append(f"{f} r{r0}={o0.get(f)} r{r}={o.get(f)}")
  183. rows0 = [(x["req"], x["pos"], x["tok"], x["seq_dev"], x["nc_dev"]) for x in o0["rows"]]
  184. rows1 = [(x["req"], x["pos"], x["tok"], x["seq_dev"], x["nc_dev"]) for x in o["rows"]]
  185. if rows0 != rows1:
  186. bad.append(f"rows r{r0}={rows0} r{r}={rows1}")
  187. for n, h in o0.get("cps", {}).items():
  188. if not replicated(n):
  189. continue
  190. h1 = o.get("cps", {}).get(n)
  191. if h1 is not None and h1 != h:
  192. bad.append(f"cp {n}")
  193. for n, v in o0.get("ints", {}).items():
  194. if n.endswith((".mla.slot", ".idx.slot", ".idx.tail_slot", ".kda.state_idx", ".mla.planned", ".mla.valid")):
  195. v1 = o.get("ints", {}).get(n)
  196. if v1 is not None and v1 != v:
  197. bad.append(f"int {n} r{r0}={v} r{r}={v1}")
  198. if bad:
  199. n_bad += 1
  200. print(f"step {s} rank {r} vs {r0}: " + "; ".join(bad[:12]) + (" ..." if len(bad) > 12 else ""))
  201. if not n_bad:
  202. print("(all ranks agree on fed tokens, rows, placement and replicated checkpoints)")
  203. print("\n== tokens (rank %d) ==" % r0)
  204. per_req = defaultdict(list)
  205. for s in sorted(steps0):
  206. o = steps0[s]
  207. if not want(o):
  208. continue
  209. for req, tok in (o.get("fed") or {}).items():
  210. if not args.req or args.req in req:
  211. pos = next((x["pos"] for x in o["rows"] if x["req"] == req), None)
  212. per_req[req].append((s, pos, tok))
  213. for req, seq in per_req.items():
  214. print(f"{req}: " + " ".join(f"{s}:{p}>{t}" for s, p, t in seq))
  215. return 0
  216. if __name__ == "__main__":
  217. sys.exit(main())