interplane.Get Omega
Read in your language

CUDApp

CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit.

Brought by drakestapleton

branch main Branches Tags History

CUDApp / tools / latmeas / fill_template.py

235 lines · 10354 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3"""Fill the GB10-vs-NAK markdown from a launch JSON file.
4
5A synthetic input is refused unless --allow-synthetic is set, and then every
6measured cell is the word FAKE. Missing stall_required stays blank. This
7script never invents a cycle count.
8"""
9import argparse
10import json
11import os
12import sys
13import tempfile
14
15CATALOG = os.path.join(os.path.dirname(__file__), "catalog.json")
16
17
18def load_catalog():
19 with open(CATALOG, encoding="utf-8") as f:
20 return json.load(f)
21
22
23def cell(text):
24 return "" if text is None or text == "" else str(text)
25
26
27def agree(measured, nak_stall, enc_stall):
28 if measured is None or nak_stall is None:
29 return ""
30 if measured == nak_stall and measured == enc_stall:
31 return "NAK and nvcc"
32 if measured == nak_stall:
33 return "NAK"
34 if measured == enc_stall:
35 return "nvcc"
36 return "neither"
37
38
39def runs_text(case, runs):
40 if not case:
41 return ""
42 parts = ["%d runs" % runs]
43 if case.get("stall_required") is None:
44 parts.append("no failing stall in the sweep")
45 else:
46 parts.append("stall spread %s" % case.get("stall_spread"))
47 if case.get("cycle_median") is not None:
48 parts.append("cycles at that stall median %s spread %s" % (case["cycle_median"], case.get("cycle_spread")))
49 if case.get("cycle_median_stall1") is not None:
50 parts.append("programmed stall 1 cycles median %s spread %s (not the stall under the threshold)" % (case["cycle_median_stall1"], case.get("cycle_spread_stall1")))
51 if case.get("overhead_cycle_median") is not None:
52 parts.append("loop overhead median %s" % case["overhead_cycle_median"])
53 if case.get("stall_required") is None and case.get("cycle_median_stall1") is None and case.get("overhead_cycle_median") is None:
54 return ""
55 return "; ".join(parts)
56
57
58def lookup(results, measure_id):
59 if not measure_id:
60 return None
61 cases = results.get("cases") or {}
62 return cases.get(measure_id)
63
64
65def build_md(cat, results, fake):
66 results = results or {}
67 measured_flag = bool(results.get("measured")) and not fake
68 runs = results.get("runs") or 0
69 driver = results.get("driver") or ""
70 commit = cat["mesa_commit"]
71 lines = []
72 lines.append("# GB10 (sm_121) measured latencies vs NAK")
73 lines.append("")
74 lines.append("Chip: NVIDIA GB10 (DGX Spark), sm_121")
75 if driver:
76 lines.append("Driver: %s. No NVIDIA user-space libraries." % driver)
77 else:
78 lines.append("Driver: NVIDIA open kernel module <version>, no NVIDIA user-space libraries")
79 lines.append("Method: dependent-chain timing kernel. One warp (32 threads); every lane stores, and a stall matches only when every lane matches the oracle.")
80 lines.append("Each fixed-latency producer is issued at a programmed stall. The GB10 column is the smallest stall S such that S and every larger S in the sweep matched the oracle on every run. Cycles are the CS2R clock delta (NAK_SV_CLOCK_LO, 0x50) around that chain, median and max-min.")
81 lines.append("Source: tests/gpu_latmeas_test.c in aien-dev/CUDApp")
82 lines.append("How to rerun: sh tools/latmeas/run_spark.sh OUTPUT_DIR")
83 lines.append("")
84 lines.append("NAK reference: `nak/sm120_instr_latencies.rs` plus `latencies/sm100/*.csv` at Mesa commit %s" % commit)
85 if fake:
86 lines.append("")
87 lines.append("FAKE: this table was rendered from synthetic input. It is not a measurement.")
88 elif not measured_flag:
89 lines.append("")
90 lines.append("NOT RUN: no chip measurement is recorded in this file. Empty cells are empty on purpose.")
91 lines.append("")
92 lines.append("## Priority 1: values CUDA++ currently borrows from NAK (needs independent measurement)")
93 lines.append("")
94 lines.append("| Writer -> reader | NAK value | NAK source line | GB10 measured | Delta | Runs / spread | Kernel |")
95 lines.append("|---|---|---|---|---|---|---|")
96 notes = []
97 for row in cat["rows"]:
98 if row["priority"] != 1:
99 continue
100 case = lookup(results, row["measure_id"]) if measured_flag else None
101 stall = None if fake or not case else case.get("stall_required")
102 delta = ""
103 shown = "FAKE" if fake else cell(stall)
104 if not fake and stall is not None and row["nak_stall"] is not None:
105 delta = str(stall - row["nak_stall"])
106 spread = "FAKE" if fake else runs_text(case, runs)
107 lines.append("| %s | %s | %s | %s | %s | %s | %s |" % (
108 row["pair"], row["nak"], row["nak_where"], shown, delta, spread, row["kernel"]))
109 if case and case.get("note"):
110 notes.append("%s: %s" % (row["id"], case["note"]))
111 lines.append("")
112 lines.append("## Priority 2: instructions where CUDA++ (nvcc-derived) and NAK disagree")
113 lines.append("")
114 lines.append("| Instruction / pair | NAK value | nvcc sm_121 stall | GB10 measured | Agrees with | Kernel |")
115 lines.append("|---|---|---|---|---|---|")
116 for row in cat["rows"]:
117 if row["priority"] != 2:
118 continue
119 case = lookup(results, row["measure_id"]) if measured_flag else None
120 stall = None if fake or not case else case.get("stall_required")
121 shown = "FAKE" if fake else cell(stall)
122 who = "FAKE" if fake else agree(stall, row["nak_stall"], row["encoder_stall"])
123 lines.append("| %s | %s | %s | %s | %s | %s |" % (
124 row["pair"], row["nak"], row["encoder"], shown, who, row["kernel"]))
125 if case and case.get("note"):
126 notes.append("%s: %s" % (row["id"], case["note"]))
127 lines.append("")
128 lines.append("## Notes")
129 lines.append("- Anything not fixed-latency (LDG/LDS, scoreboard waits) is out of scope for this table.")
130 lines.append("- Decoupled ops (BSSY, BSYNC, BRA, EXIT, BAR) are listed because the encoder gives them a fixed stall and NAK does not. They have no dependent-chain kernel.")
131 lines.append("- HMMA -> HMMA in NAK is 20 + 9 = 29, the same total the encoder uses. The HMMA row is the non-HMMA reader (28).")
132 lines.append("- QMMA is not generated here. Its encoder stall is 30 and NAK's IMMA -> ALU total is 26 (IMMA -> IMMA is 27).")
133 err = (results or {}).get("error") or ""
134 if err:
135 notes.append("runner: %s" % err)
136 if notes:
137 for n in notes:
138 lines.append("- %s" % n)
139 else:
140 lines.append("- Confidence notes and anomalies go here.")
141 lines.append("")
142 return "\n".join(lines)
143
144
145def write_or_refuse(results, dest, allow_synthetic):
146 fake = bool(results.get("synthetic"))
147 if fake and not allow_synthetic:
148 print("refusing synthetic input (pass --allow-synthetic to render a FAKE table)", file=sys.stderr)
149 return 2
150 text = build_md(load_catalog(), results, fake)
151 if fake and "FAKE" not in text:
152 print("synthetic render did not stamp FAKE", file=sys.stderr)
153 return 1
154 if dest:
155 with open(dest, "w", encoding="utf-8") as f:
156 f.write(text)
157 else:
158 sys.stdout.write(text)
159 return 0
160
161
162def self_test():
163 cat = load_catalog()
164 synthetic = {
165 "synthetic": True,
166 "measured": True,
167 "runs": 11,
168 "driver": "synthetic",
169 "cases": {"alu_alu": {"stall_required": 99, "stall_spread": 0, "cycle_median": 99, "cycle_spread": 1,
170 "overhead_cycle_median": 1, "note": ""}},
171 }
172 rc = write_or_refuse(synthetic, None, False)
173 if rc != 2:
174 print("FAIL: synthetic input was accepted", file=sys.stderr)
175 return 1
176 fd, path = tempfile.mkstemp(prefix="latmeas-fake-", suffix=".md")
177 os.close(fd)
178 try:
179 rc = write_or_refuse(synthetic, path, True)
180 text = open(path, encoding="utf-8").read()
181 finally:
182 os.unlink(path)
183 if rc != 0 or "FAKE" not in text or "99" in text:
184 print("FAIL: synthetic table leaked a number or missed FAKE", file=sys.stderr)
185 return 1
186 blank = {"synthetic": False, "measured": True, "runs": 11, "cases": {"alu_alu": {"stall_required": None}}}
187 text = build_md(cat, blank, False)
188 # The ALU row's measured cell is between the NAK citation and Delta. It must be empty.
189 alu = [ln for ln in text.splitlines() if ln.startswith("| ALU -> ALU")]
190 if len(alu) != 1 or "99" in text:
191 print("FAIL: blank measured row missing", file=sys.stderr)
192 return 1
193 parts = [p.strip() for p in alu[0].strip("|").split("|")]
194 if parts[3] != "":
195 print("FAIL: null stall rendered as %r" % parts[3], file=sys.stderr)
196 return 1
197 filled = {"synthetic": False, "measured": False, "runs": 11,
198 "cases": {"alu_alu": {"stall_required": 5, "stall_spread": 0}}}
199 text = build_md(cat, filled, False)
200 alu = [ln for ln in text.splitlines() if ln.startswith("| ALU -> ALU")][0]
201 parts = [p.strip() for p in alu.strip("|").split("|")]
202 if parts[3] != "":
203 print("FAIL: measured:false still filled a cell (%r)" % parts[3], file=sys.stderr)
204 return 1
205 timed = {"synthetic": False, "measured": True, "runs": 11, "cases": {
206 "alu_alu": {"stall_required": None, "cycle_median_stall1": 1703, "cycle_spread_stall1": 4,
207 "overhead_cycle_median": 800}}}
208 text = build_md(cat, timed, False)
209 alu = [ln for ln in text.splitlines() if ln.startswith("| ALU -> ALU")][0]
210 parts = [p.strip() for p in alu.strip("|").split("|")]
211 if parts[3] != "" or "1703" not in parts[5]:
212 print("FAIL: stall-1 cycles landed in the measured cell or missed the runs cell: %r" % parts, file=sys.stderr)
213 return 1
214 print("fill_template self-test PASS")
215 return 0
216
217
218def main():
219 p = argparse.ArgumentParser()
220 p.add_argument("--results")
221 p.add_argument("--md")
222 p.add_argument("--allow-synthetic", action="store_true")
223 p.add_argument("--self-test", action="store_true")
224 args = p.parse_args()
225 if args.self_test:
226 return self_test()
227 if not args.results:
228 p.error("--results is required")
229 with open(args.results, encoding="utf-8") as f:
230 results = json.load(f)
231 return write_or_refuse(results, args.md, args.allow_synthetic)
232
233
234if __name__ == "__main__":
235 sys.exit(main())