The recipe data (sm86-recipes.json, extra-seal-plan.json, rope-regeneration.json), STANDARD_INCLUDES, the sm86 include list and the one test that asserts them
now spell the include directories as strata-41cf05a0/{include,src,third_party/ggml}; prose that named engine/strata/CMakeLists.txt or the retired
build-original-verify-ptx.sh now says Strata 41cf05a0 or the precise flags. UPSTREAM.md records where to place a restored checkout.
No pin covers these files; behaviour of the tools is unchanged (the directories did not exist before either).
673 lines
32 KiB
Python
673 lines
32 KiB
Python
#!/usr/bin/env python3
|
|
"""Per-architecture (sm_86) companion set for the sealed sm_120 PTX of crates/cuda-driver.
|
|
|
|
Design: the sealed sm_120 files and every Rust pin stay untouched and remain the default.
|
|
For each sealed sm_120 PTX this tool builds an sm_86 companion in crates/cuda-driver/ptx-sm86/ and a generated
|
|
Rust table (crates/cuda-driver/src/sm86_table.rs) keyed by the SHA-256 of the sm_120 body. With the cargo feature
|
|
`sm86` the driver swaps the module image at cuModuleLoadData time when the current device is 8.6 <= cc < 12.0.
|
|
|
|
How a companion is made (the method is recorded per asset in crates/cuda-driver/ptx-sm86/MANIFEST.json):
|
|
|
|
retarget (default) the sealed sm_120 text with the minimum edits that make it valid sm_86 PTX: the `.target`
|
|
line, plus two documented rules for sm_90+ instructions (see retarget()). The instruction stream, the
|
|
entry names (including the path-hashed anonymous-namespace names the Rust side looks up), the launch
|
|
bounds and the shared-memory layout are the sealed ones. Accepted only if `ptxas -arch=sm_86` accepts it.
|
|
recompile fallback, only when retarget is rejected: the .cu compiled with its recipe and `-arch=sm_86`. The recipe
|
|
must have been verified by `infer` (a round trip on sm_120 against the sealed file) and the result must
|
|
export the same entry names with the same parameter counts.
|
|
|
|
`infer` is also the evidence for the recompile recipes: it compiles every .cu with the seal-plan recipe (or with the
|
|
two generic candidates) for sm_120 and compares with the sealed file. `compare` builds the native sm_86 compile of
|
|
every verified recipe and reports how it differs structurally from the installed companion.
|
|
|
|
Commands (Linux; infer/build/compare need --toolkit DIR from scripts/bootstrap-cuda-toolkit.py):
|
|
survey inventory of the sealed PTX and companion status; no nvcc
|
|
infer --toolkit D --work W round-trip every recipe candidate on sm_120, write scripts/gpu-bringup/sm86-recipes.json
|
|
build --toolkit D --work W build and install the sm_86 set, MANIFEST.json and the Rust table
|
|
compare --toolkit D --work W native sm_86 compile vs companion (structure only), report to stdout / --report
|
|
check re-verify the installed set against the tree (no nvcc, no GPU)
|
|
|
|
This tool makes only structural claims: a companion is present, ptxas accepts it, it exports the same entries with
|
|
the same parameter counts. It says nothing about numerical agreement.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import concurrent.futures
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
from collections import Counter
|
|
from pathlib import Path
|
|
from typing import Dict, List, Optional, Tuple
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
import bringup_lib as L # noqa: E402
|
|
|
|
ROOT = L.REPO
|
|
CD = "crates/cuda-driver"
|
|
OUT_REL = f"{CD}/ptx-sm86"
|
|
TABLE_REL = f"{CD}/src/sm86_table.rs"
|
|
RECIPES_REL = "scripts/gpu-bringup/sm86-recipes.json"
|
|
MANIFEST_NAME = "MANIFEST.json"
|
|
ARCH = "sm_86"
|
|
SRC_ARCH = "sm_120"
|
|
|
|
# Union of the include sets used by the repo's recipes (the precise-flags original-verify build, the seal plans and the
|
|
# scalar-MTP recipe); a missing directory is dropped, and the round trip proves the choice.
|
|
INCLUDES = L.STANDARD_INCLUDES + ["strata-41cf05a0/src", "strata-41cf05a0/third_party/ggml/src"]
|
|
|
|
# PTX name -> source stem when the .cu does not share the PTX's name. Each mapping is only used if the round trip
|
|
# reproduces the sealed entry set; otherwise the asset has no verified recipe.
|
|
CU_ALIASES = {
|
|
"gdn_fixed": "offline_gdn_kernel",
|
|
"gr_fixed": "offline_gr_kernel",
|
|
"gr_batch_preview": "offline_gr_kernel",
|
|
"moe_fixed": "offline_moe_kernel",
|
|
"mtp_fixed": "offline_mtp_kernel",
|
|
"mtp_attention_fixed": "offline_mtp_attention_kernel",
|
|
"mtp_gr_fixed": "offline_mtp_gr_kernel",
|
|
"mtp_s2_fixed": "offline_mtp_s2_kernel",
|
|
"mtp_s2_full_fixed": "offline_mtp_s2_kernel",
|
|
"ple_fixed": "offline_ple_kernel",
|
|
"ple_value_full_fixed": "offline_ple_value_full_kernel",
|
|
"kar_ple_fixed": "offline_kar_ple_kernel",
|
|
"offline_gdn_fused_t1": "offline_gdn_fused_t1_kernel",
|
|
"offline_gdn_prefill": "offline_gdn_prefill_kernel",
|
|
"offline_moe_prefill": "offline_moe_prefill_kernel",
|
|
"offline_native_dequant_f16": "offline_native_dequant_f16_kernel",
|
|
"mmq-original-formats": "mmq_original_formats",
|
|
"mmq-original-formats-fixup": "mmq_original_formats_fixup",
|
|
}
|
|
|
|
PRECISE = ["-ptx", "-O3", f"-arch={SRC_ARCH}", "-std=c++17", "--fmad=true", "--ftz=false"]
|
|
FAST = ["-ptx", "-O3", f"-arch={SRC_ARCH}", "-std=c++17", "--use_fast_math"]
|
|
CANDIDATES = {"precise": PRECISE, "fast-math": FAST}
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ helpers
|
|
|
|
|
|
def sha256_hex(b: bytes) -> str:
|
|
return hashlib.sha256(b).hexdigest()
|
|
|
|
|
|
def body_of(stored: bytes) -> bytes:
|
|
"""The hashed PTX body: the file without its (at most one) terminal NUL."""
|
|
return stored[:-1] if stored.endswith(b"\0") else stored
|
|
|
|
|
|
_INTERNAL = re.compile(rb"_INTERNAL_[0-9a-f]{8}_")
|
|
|
|
|
|
def normalize(ptx: bytes) -> bytes:
|
|
"""nvcc embeds a hash of the source path in some symbols; mask it before comparing."""
|
|
return _INTERNAL.sub(b"_INTERNAL_xxxxxxxx_", ptx)
|
|
|
|
|
|
_F32_ARITH = re.compile(rb"^\s*(?:@!?%p\d+\s+)?(?:add|sub|mul|fma|mad|div|sqrt|rcp|ex2|lg2|sin|cos|min|max|neg|abs)[a-z0-9_.]*\.f32[^;]*;", re.M)
|
|
|
|
|
|
def ftz_ratio(ptx: bytes) -> Optional[float]:
|
|
"""Fraction of f32 arithmetic instructions that are .ftz: ~1.0 for --use_fast_math code, ~0 for precise code.
|
|
None when the PTX has no f32 arithmetic (the flag then cannot change the output)."""
|
|
lines = [m.group(0) for m in _F32_ARITH.finditer(ptx)]
|
|
if not lines:
|
|
return None
|
|
return sum(1 for l in lines if b".ftz" in l) / len(lines)
|
|
|
|
|
|
def entries_with_params(ptx: bytes) -> Dict[str, int]:
|
|
text = ptx.decode("latin-1")
|
|
out = {}
|
|
for name in L.ptx_entries(text):
|
|
out[name] = L.entry_param_count(text, name) or 0
|
|
return out
|
|
|
|
|
|
_GEOMETRY = re.compile(rb"^\.(?:visible\s+)?entry\s+(\S+?)\(.*?^\)\s*\n((?:\.(?:maxntid|reqntid|minnctapersm|maxnreg)[^\n]*\n)*)", re.M | re.S)
|
|
|
|
|
|
def geometry(ptx: bytes) -> Dict[str, str]:
|
|
"""Per entry: the launch-bound directives (.maxntid/.reqntid/.minnctapersm/.maxnreg) - what a host launch depends on."""
|
|
out = {}
|
|
for m in _GEOMETRY.finditer(ptx):
|
|
out[m.group(1).decode("latin-1")] = " ".join(m.group(2).decode("latin-1").split())
|
|
return out
|
|
|
|
|
|
_STATIC_SHARED = re.compile(rb"^\s*\.shared\s+\.align\s+(\d+)\s+\.b8\s+(\S+?)\[(\d+)\]", re.M)
|
|
|
|
|
|
def static_shared_bytes(ptx: bytes) -> int:
|
|
return sum(int(m.group(3)) for m in _STATIC_SHARED.finditer(ptx))
|
|
|
|
|
|
def header_info(ptx: bytes) -> dict:
|
|
h = ptx[:4096].decode("latin-1")
|
|
ver = re.search(r"Cuda compilation tools, release \S+, V(\d+\.\d+\.\d+)", h)
|
|
isa = re.search(rb"(?m)^\.version (\S+)", ptx)
|
|
tg = re.search(rb"(?m)^\.target (\S+)", ptx)
|
|
return {"nvcc": ver.group(1) if ver else None, "isa": isa.group(1).decode() if isa else None,
|
|
"target": tg.group(1).decode() if tg else None}
|
|
|
|
|
|
def _all_ptx_paths(root: Path) -> List[str]:
|
|
return sorted(str(p.relative_to(root)).replace(os.sep, "/")
|
|
for d in ("src", "assets", "kernels") for p in (root / CD / d).glob("*.ptx"))
|
|
|
|
|
|
def _is_placeholder(root: Path, p: str) -> bool:
|
|
head = (root / p).read_bytes()[:4096]
|
|
return b"UNSEALED" in head or b"PLACEHOLDER" in head
|
|
|
|
|
|
def _target_of(root: Path, p: str) -> Optional[str]:
|
|
return header_info((root / p).read_bytes()).get("target")
|
|
|
|
|
|
def sealed_ptx_paths(root: Path) -> List[str]:
|
|
"""Sealed PTX that need a companion: real PTX whose target is sm_120 (and so cannot load on an sm_86 device)."""
|
|
return [p for p in _all_ptx_paths(root) if not _is_placeholder(root, p) and _target_of(root, p) == SRC_ARCH]
|
|
|
|
|
|
def portable_ptx_paths(root: Path) -> List[str]:
|
|
"""Real PTX with a target below sm_86 (sm_75 / sm_80): loads unchanged on both the 3080 and the 5090."""
|
|
return [p for p in _all_ptx_paths(root) if not _is_placeholder(root, p) and _target_of(root, p) not in (None, SRC_ARCH)]
|
|
|
|
|
|
def unsealed_ptx_paths(root: Path) -> List[str]:
|
|
return [p for p in _all_ptx_paths(root) if _is_placeholder(root, p)]
|
|
|
|
|
|
def existing_includes(root: Path) -> List[str]:
|
|
return [d for d in INCLUDES if (root / d).is_dir()]
|
|
|
|
|
|
def swap_arch(flags: List[str], arch: str) -> List[str]:
|
|
return [f"-arch={arch}" if f.startswith("-arch=") else f for f in flags]
|
|
|
|
|
|
def run(cmd: List[str], cwd: Path, timeout: int) -> Tuple[int, str, str]:
|
|
p = subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True, timeout=timeout)
|
|
return p.returncode, p.stdout, p.stderr
|
|
|
|
|
|
def ptxas_check(toolkit: Path, ptx: Path, arch: str, timeout: int = 1800) -> Tuple[bool, str]:
|
|
rc, out, err = run([str(toolkit / "bin" / "ptxas"), f"-arch={arch}", str(ptx), "-o", os.devnull], ROOT, timeout)
|
|
msg = (err or out).strip().splitlines()
|
|
return rc == 0, " | ".join(msg[-3:])
|
|
|
|
|
|
def find_cu(root: Path, ptx_rel: str) -> Optional[str]:
|
|
p = Path(ptx_rel)
|
|
for cand in (p.with_suffix(".cu"), p.parent / (CU_ALIASES.get(p.stem, "\0") + ".cu")):
|
|
if (root / cand).is_file():
|
|
return str(cand).replace(os.sep, "/")
|
|
return None
|
|
|
|
|
|
def plan_recipes(root: Path) -> Dict[str, L.Asset]:
|
|
assets, _ = L.load_all_assets(root, "preserve")
|
|
return {a.ptx: a for a in assets if not a.deferred}
|
|
|
|
|
|
def nvcc_banner(nvcc: str) -> str:
|
|
rc, so, se = run([nvcc, "--version"], ROOT, 60)
|
|
return (so or se).strip().splitlines()[-2] if rc == 0 else ""
|
|
|
|
|
|
# ----------------------------------------------------------------------------------------------- survey
|
|
|
|
|
|
def cmd_survey(args) -> int:
|
|
root = ROOT
|
|
recipes = json.loads((root / RECIPES_REL).read_text()) if (root / RECIPES_REL).is_file() else {}
|
|
plans = plan_recipes(root)
|
|
sealed = sealed_ptx_paths(root)
|
|
print(f"sealed sm_120 PTX: {len(sealed)}; portable (target < sm_86): {[Path(p).name for p in portable_ptx_paths(root)]}; "
|
|
f"unsealed placeholders: {len(unsealed_ptx_paths(root))}")
|
|
for p in sealed:
|
|
h = header_info((root / p).read_bytes())
|
|
r = recipes.get("assets", {}).get(p, {})
|
|
print(f" {Path(p).name:<44} nvcc={h['nvcc'] or '-':<8} isa={h['isa'] or '-':<4} cu={'y' if find_cu(root, p) else 'n'} "
|
|
f"plan={'y' if p in plans else 'n'} recipe={r.get('confidence', '-')}")
|
|
for p in unsealed_ptx_paths(root):
|
|
print(f" UNSEALED {p}")
|
|
return 0
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ infer
|
|
|
|
|
|
def compile_cu(nvcc: str, root: Path, cu: str, flags: List[str], includes: List[str], out: Path, timeout: int) -> Tuple[bool, str]:
|
|
cmd = [nvcc] + flags + [f"-I{d}" for d in includes] + [cu, "-o", str(out)]
|
|
try:
|
|
rc, so, se = run(cmd, root, timeout)
|
|
except subprocess.TimeoutExpired:
|
|
return False, "timeout"
|
|
if rc != 0 or not out.is_file():
|
|
tail = (se or so).strip().splitlines()[-3:]
|
|
return False, f"nvcc exit {rc}: " + " | ".join(tail)
|
|
return True, ""
|
|
|
|
|
|
def infer_one(nvcc: str, root: Path, work: Path, ptx_rel: str, plan: Optional[L.Asset], timeout: int) -> dict:
|
|
"""Recipe evidence for one sealed PTX. The nvcc-hashed anonymous-namespace entry names depend on the absolute
|
|
path of the source, so 'entries differ' is judged on names with that hash masked (`_GLOBAL__N__xxxxxxxx_`)."""
|
|
committed = body_of((root / ptx_rel).read_bytes())
|
|
head = header_info(committed)
|
|
rec: dict = {"ptx": ptx_rel, "committed_nvcc": head["nvcc"], "committed_isa": head["isa"], "committed_bytes": len(committed)}
|
|
cu = plan.cu if plan else find_cu(root, ptx_rel)
|
|
if cu is None:
|
|
rec.update(method="none", confidence="-", reason="no .cu for this PTX")
|
|
return rec
|
|
rec["cu"] = cu
|
|
cands: Dict[str, Tuple[List[str], List[str]]] = {}
|
|
if plan is not None:
|
|
cands["plan"] = (list(plan.flags), list(plan.includes))
|
|
else:
|
|
for name, flags in CANDIDATES.items():
|
|
cands[name] = (list(flags), existing_includes(root))
|
|
rc = ftz_ratio(committed)
|
|
rec["committed_ftz_ratio"] = None if rc is None else round(rc, 3)
|
|
ce = mask_entries(entries_with_params(committed))
|
|
results, best, best_key = {}, None, None
|
|
for name, (flags, incs) in cands.items():
|
|
out = work / f"{Path(ptx_rel).stem}.{name}.sm120.ptx"
|
|
ok, why = compile_cu(nvcc, root, cu, flags, incs, out, timeout)
|
|
if not ok:
|
|
results[name] = {"ok": False, "why": why}
|
|
continue
|
|
got = body_of(out.read_bytes())
|
|
rg = ftz_ratio(got)
|
|
mode_err = 0.0 if rc is None or rg is None else abs(rg - rc)
|
|
masked_exact = mask_names(normalize(got)) == mask_names(normalize(committed))
|
|
eq = mask_entries(entries_with_params(got)) == ce
|
|
results[name] = {"ok": True, "masked_exact": masked_exact, "entries_equal": eq,
|
|
"ftz_ratio": None if rg is None else round(rg, 3), "mode_error": round(mode_err, 3),
|
|
"flags": flags, "includes": incs}
|
|
key = (eq, masked_exact, -mode_err, name == "precise")
|
|
if eq and (best_key is None or key > best_key):
|
|
best, best_key = name, key
|
|
rec["candidates"] = results
|
|
if best is None:
|
|
rec.update(method="none", confidence="-", reason="no candidate reproduced the sealed entry set: "
|
|
+ "; ".join(f"{k}: {v.get('why') or 'entries differ'}" for k, v in results.items()))
|
|
return rec
|
|
b = results[best]
|
|
confidence = "exact" if b["masked_exact"] else ("entries+flag-mode" if b["mode_error"] <= 0.25 else "weak")
|
|
rec.update(recipe=best, flags=b["flags"], includes=b["includes"], confidence=confidence,
|
|
method="recompile" if confidence != "weak" else "none",
|
|
reason=None if confidence != "weak" else f"flag mode not reproduced (ftz ratio {rec['committed_ftz_ratio']} vs {b['ftz_ratio']})")
|
|
return rec
|
|
|
|
|
|
_NS_HASH = re.compile(r"_GLOBAL__N__[0-9a-f]{8}_")
|
|
|
|
|
|
def mask_names(ptx: bytes) -> bytes:
|
|
return re.sub(rb"_GLOBAL__N__[0-9a-f]{8}_", b"_GLOBAL__N__xxxxxxxx_", ptx)
|
|
|
|
|
|
def mask_entries(e: Dict[str, object]) -> Dict[str, object]:
|
|
return {_NS_HASH.sub("_GLOBAL__N__xxxxxxxx_", k): v for k, v in e.items()}
|
|
|
|
|
|
def cmd_infer(args) -> int:
|
|
tk = Path(args.toolkit).resolve()
|
|
work = Path(args.work).resolve() / "infer"
|
|
work.mkdir(parents=True, exist_ok=True)
|
|
plans = plan_recipes(ROOT)
|
|
todo = [p for p in sealed_ptx_paths(ROOT) if not args.only or Path(p).stem in args.only.split(",")]
|
|
nvcc = str(tk / "bin" / "nvcc")
|
|
out: Dict[str, dict] = {}
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=args.jobs) as pool:
|
|
futs = {pool.submit(infer_one, nvcc, ROOT, work, p, plans.get(p), args.timeout): p for p in todo}
|
|
for f in concurrent.futures.as_completed(futs):
|
|
r = f.result()
|
|
out[r["ptx"]] = r
|
|
print(f" {r['method']:<9} {Path(r['ptx']).name:<44} {r.get('confidence', '-'):<18} {r.get('recipe', '-'):<10} "
|
|
f"{r.get('reason') or ''}"[:220], flush=True)
|
|
doc = {"schema": 1, "tool": "scripts/gpu-bringup/sm86_assets.py infer", "source_arch": SRC_ARCH,
|
|
"nvcc": nvcc_banner(nvcc), "assets": dict(sorted(out.items()))}
|
|
path = ROOT / RECIPES_REL
|
|
if args.only and path.is_file():
|
|
prev = json.loads(path.read_text())
|
|
prev["assets"].update(doc["assets"])
|
|
doc = prev
|
|
path.write_text(json.dumps(doc, indent=1, sort_keys=True) + "\n")
|
|
print(f"wrote {RECIPES_REL}: " + ", ".join(f"{k}={v}" for k, v in Counter(r["confidence"] for r in out.values()).items()))
|
|
return 0
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ build
|
|
|
|
_GRIDDEP = re.compile(rb"^[ \t]*griddepcontrol\.(?:wait|launch_dependents)[ \t]*;[ \t]*\n", re.M)
|
|
_SHARED_CVTA = re.compile(rb"^([ \t]*mov\.u64[ \t]+(%\w+)[ \t]*,[ \t]*(\w+)[ \t]*;[ \t]*\n)[ \t]*cvta\.to\.shared\.u64[ \t]+\2[ \t]*,[ \t]*\2[ \t]*;[ \t]*\n", re.M)
|
|
_SHARED_DECL = re.compile(rb"\.shared\s+(?:\.align\s+\d+\s+)?\.\w+\s+(\w+)")
|
|
_MIN_RELU = re.compile(rb"^([ \t]*)min\.relu\.s32[ \t]+(%\w+)[ \t]*,[ \t]*(%\w+)[ \t]*,[ \t]*(%\w+)[ \t]*;", re.M)
|
|
|
|
|
|
def retarget(committed: bytes) -> Tuple[bytes, List[dict]]:
|
|
"""The sealed sm_120 text with the minimum edits that make it valid sm_86 PTX.
|
|
|
|
rules (each application is recorded in the manifest):
|
|
target the single `.target sm_120` line becomes `.target sm_86`
|
|
griddep `griddepcontrol.wait` / `.launch_dependents` (sm_90+) lines are deleted. The driver never launches with
|
|
the programmatic-stream-serialization attribute (the tree has no cuLaunchKernelEx), so no grid has a
|
|
prerequisite grid and the instruction is a no-op.
|
|
min_relu `min.relu.s32 d,a,b;` (sm_90+) becomes `min.s32 d,a,b;` + `max.s32 d,d,0;` (the same value,
|
|
max(0, min(a,b))), only when d is neither a nor b.
|
|
shared_cvta hand-written PTX (bf16_f32_mmvf, gr_fixed, gr_batch_preview) does `mov.u64 R, shared_sym;` and then
|
|
`cvta.to.shared.u64 R, R;`, i.e. converts an address that is already a shared-window address as if it
|
|
were generic. The cvta line is deleted. Found by running on the 3080: sm_86 faults (illegal address,
|
|
code 700) on it where sm_120 does not.
|
|
Everything else is kept byte for byte."""
|
|
applied: List[dict] = []
|
|
lines = committed.split(b"\n")
|
|
hits = [i for i, l in enumerate(lines) if l.strip() == b".target sm_120"]
|
|
if len(hits) != 1:
|
|
raise ValueError(f"expected exactly one '.target sm_120' line, found {len(hits)}")
|
|
lines[hits[0]] = lines[hits[0]].replace(b"sm_120", b"sm_86")
|
|
applied.append({"rule": "target", "count": 1})
|
|
text = b"\n".join(lines)
|
|
text, n = _GRIDDEP.subn(b"", text)
|
|
if n:
|
|
applied.append({"rule": "griddep", "count": n})
|
|
|
|
shared_symbols = set(_SHARED_DECL.findall(text))
|
|
|
|
def shared(m: "re.Match[bytes]") -> bytes:
|
|
# `mov.u64 R, sym` of a .shared variable already yields a shared-window address; the hand-written PTX then
|
|
# applies cvta.to.shared to it as if it were generic. Keep the mov, drop the cvta (see the module docstring).
|
|
return m.group(1) if m.group(3) in shared_symbols else m.group(0)
|
|
|
|
text = _SHARED_CVTA.sub(shared, text)
|
|
n_removed = sum(1 for m in _SHARED_CVTA.finditer(committed) if m.group(3) in shared_symbols)
|
|
if n_removed:
|
|
applied.append({"rule": "shared_cvta", "count": n_removed})
|
|
|
|
def relu(m: "re.Match[bytes]") -> bytes:
|
|
ind, d, a, b = m.groups()
|
|
if d in (a, b):
|
|
raise ValueError("min.relu with the destination aliasing a source")
|
|
return ind + b"min.s32 " + d + b", " + a + b", " + b + b";\n" + ind + b"max.s32 " + d + b", " + d + b", 0;"
|
|
|
|
text, n = _MIN_RELU.subn(relu, text)
|
|
if n:
|
|
applied.append({"rule": "min_relu", "count": n})
|
|
return text, applied
|
|
|
|
|
|
def structural_problems(committed: bytes, data: bytes) -> List[str]:
|
|
out = []
|
|
targets = [l for l in data.decode("latin-1").splitlines() if l.startswith(".target")]
|
|
if targets != [f".target {ARCH}"]:
|
|
out.append(f"targets {targets}")
|
|
if b"\0" in data or not data.isascii():
|
|
out.append("not NUL-free ASCII")
|
|
ce, ge = entries_with_params(committed), entries_with_params(data)
|
|
if ce != ge:
|
|
miss = sorted(set(ce) - set(ge))
|
|
bad = sorted(k for k in ce if k in ge and ce[k] != ge[k])
|
|
out.append(f"entry mismatch: missing={miss[:3]} param_diff={bad[:3]} extra={sorted(set(ge) - set(ce))[:3]}")
|
|
return out
|
|
|
|
|
|
def build_one(nvcc: str, tk: Path, work: Path, ptx_rel: str, recipe: dict, timeout: int) -> dict:
|
|
committed_stored = (ROOT / ptx_rel).read_bytes()
|
|
committed = body_of(committed_stored)
|
|
rec = {"name": Path(ptx_rel).name, "sm120_path": ptx_rel, "sm120_sha256": sha256_hex(committed),
|
|
"sm120_bytes": len(committed), "sm120_stored_nul": committed_stored.endswith(b"\0"),
|
|
"sm120_nvcc": header_info(committed)["nvcc"], "problems": []}
|
|
out = work / f"{Path(ptx_rel).stem}.sm86.ptx"
|
|
data: Optional[bytes] = None
|
|
try:
|
|
data, applied = retarget(committed)
|
|
out.write_bytes(data)
|
|
ok, msg = ptxas_check(tk, out, ARCH, timeout)
|
|
rec.update(method="retarget", rules=applied)
|
|
if not ok:
|
|
rec["retarget_rejected"] = msg
|
|
data = None
|
|
except ValueError as e:
|
|
rec["retarget_rejected"] = str(e)
|
|
data = None
|
|
if data is None:
|
|
if recipe.get("method") != "recompile":
|
|
rec["problems"].append("retarget rejected and no verified recipe: " + rec["retarget_rejected"])
|
|
return rec
|
|
flags = swap_arch(recipe["flags"], ARCH)
|
|
ok, why = compile_cu(nvcc, ROOT, recipe["cu"], flags, recipe["includes"], out, timeout)
|
|
if not ok:
|
|
rec["problems"].append("recompile failed: " + why)
|
|
return rec
|
|
data = body_of(out.read_bytes())
|
|
rec.update(method="recompile", rules=[], cu=recipe["cu"], cu_sha256=sha256_hex((ROOT / recipe["cu"]).read_bytes()),
|
|
flags=flags + [f"-I{d}" for d in recipe["includes"]], recipe=recipe.get("recipe"),
|
|
recipe_confidence=recipe.get("confidence"))
|
|
ok, msg = ptxas_check(tk, out, ARCH, timeout)
|
|
if not ok:
|
|
rec["problems"].append("ptxas -arch=sm_86 rejected the recompile: " + msg)
|
|
rec["problems"] += structural_problems(committed, data)
|
|
rec.update(ptxas="ok" if not rec["problems"] else "see problems", sm86_bytes=len(data), sm86_sha256=sha256_hex(data),
|
|
isa=header_info(data)["isa"], entries=len(entries_with_params(data)))
|
|
rec["_data"] = data
|
|
return rec
|
|
|
|
|
|
def cmd_build(args) -> int:
|
|
tk = Path(args.toolkit).resolve()
|
|
work = Path(args.work).resolve() / "build"
|
|
work.mkdir(parents=True, exist_ok=True)
|
|
recipes = json.loads((ROOT / RECIPES_REL).read_text())["assets"] if (ROOT / RECIPES_REL).is_file() else {}
|
|
nvcc = str(tk / "bin" / "nvcc")
|
|
todo = [p for p in sealed_ptx_paths(ROOT) if not args.only or Path(p).stem in args.only.split(",")]
|
|
out_dir = ROOT / OUT_REL
|
|
results: Dict[str, dict] = {}
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=args.jobs) as pool:
|
|
futs = {pool.submit(build_one, nvcc, tk, work, p, recipes.get(p, {}), args.timeout): p for p in todo}
|
|
for f in concurrent.futures.as_completed(futs):
|
|
r = f.result()
|
|
results[r["sm120_path"]] = r
|
|
rules = ",".join(f"{x['rule']}x{x['count']}" for x in r.get("rules", []) if x["rule"] != "target")
|
|
print(f" {'ok ' if not r['problems'] else 'FAIL'} {r.get('method', '-'):<9} {r['name']:<44} "
|
|
f"{r.get('sm86_bytes', '-'):>8} B {rules} {'; '.join(r['problems'])[:150]}", flush=True)
|
|
failed = {k: v for k, v in results.items() if v["problems"]}
|
|
out_dir.mkdir(parents=True, exist_ok=True)
|
|
installed = {}
|
|
for p, r in sorted(results.items()):
|
|
if r["problems"]:
|
|
continue
|
|
(out_dir / r["name"]).write_bytes(r.pop("_data"))
|
|
installed[p] = r
|
|
for r in results.values():
|
|
r.pop("_data", None)
|
|
write_manifest(nvcc, tk, installed, failed)
|
|
write_table(installed)
|
|
print(f"installed {len(installed)} ({dict(Counter(r['method'] for r in installed.values()))}), "
|
|
f"failed {len(failed)}: {sorted(Path(k).name for k in failed)}")
|
|
return 1 if failed and not args.allow_failures else 0
|
|
|
|
|
|
def write_manifest(nvcc: str, tk: Path, installed: Dict[str, dict], failed: Dict[str, dict]) -> None:
|
|
doc = {
|
|
"schema": 1,
|
|
"tool": "scripts/gpu-bringup/sm86_assets.py build",
|
|
"target_arch": ARCH, "source_arch": SRC_ARCH,
|
|
"nvcc": nvcc_banner(nvcc),
|
|
"toolkit_lock_sha256": sha256_hex((ROOT / L.TOOLKIT_LOCK).read_bytes()),
|
|
"toolkit_provenance_present": (tk / "TOOLKIT-PROVENANCE.json").is_file(),
|
|
"claims": "structural only: ptxas -arch=sm_86 accepts each file and it exports the same .entry names with the "
|
|
"same parameter counts as its sm_120 original; no numerical or performance claim",
|
|
"assets": [{k: v for k, v in sorted(r.items()) if k != "problems"} for _, r in sorted(installed.items())],
|
|
"not_built": [{"name": r["name"], "sm120_path": p, "problems": r["problems"]} for p, r in sorted(failed.items())],
|
|
"portable_no_companion_needed": [{"path": p, "target": _target_of(ROOT, p)} for p in portable_ptx_paths(ROOT)],
|
|
"unsealed_sm120_placeholders": unsealed_ptx_paths(ROOT),
|
|
}
|
|
(ROOT / OUT_REL / MANIFEST_NAME).write_text(json.dumps(doc, indent=1) + "\n")
|
|
|
|
|
|
def rust_bytes(hex_digest: str) -> str:
|
|
return "[" + ", ".join(f"0x{x:02x}" for x in bytes.fromhex(hex_digest)) + "]"
|
|
|
|
|
|
def write_table(installed: Dict[str, dict]) -> None:
|
|
by_key: Dict[str, dict] = {}
|
|
for r in installed.values():
|
|
k = r["sm120_sha256"]
|
|
if k in by_key:
|
|
if by_key[k]["sm86_sha256"] != r["sm86_sha256"]:
|
|
raise SystemExit(f"{r['name']} and {by_key[k]['name']} share an sm_120 body but differ for sm_86")
|
|
continue
|
|
by_key[k] = r
|
|
lines = [
|
|
"// @generated by scripts/gpu-bringup/sm86_assets.py build -- do not edit.",
|
|
"// Table of the sm_86 companions of the sealed sm_120 PTX (see spec node sm86-assets.md).",
|
|
"// `key` = SHA-256 of the sealed sm_120 body (file without its terminal NUL); `len` = companion length",
|
|
"// including the terminal NUL that is appended here; `sha` = SHA-256 of the companion body.",
|
|
"",
|
|
"pub(crate) struct Companion {",
|
|
" pub name: &'static str,",
|
|
" pub key: [u8; 32],",
|
|
" pub len: usize,",
|
|
" pub sha: [u8; 32],",
|
|
" pub ptx: &'static [u8],",
|
|
"}",
|
|
"",
|
|
"/// Sorted by `key`.",
|
|
"pub(crate) static COMPANIONS: &[Companion] = &[",
|
|
]
|
|
for k in sorted(by_key):
|
|
r = by_key[k]
|
|
lines += [
|
|
" Companion {",
|
|
f' name: "{r["name"]}",',
|
|
f" key: {rust_bytes(k)},",
|
|
f" len: {r['sm86_bytes'] + 1},",
|
|
f" sha: {rust_bytes(r['sm86_sha256'])},",
|
|
f' ptx: concat!(include_str!("../ptx-sm86/{r["name"]}"), "\\0").as_bytes(),',
|
|
" },",
|
|
]
|
|
lines += ["];", ""]
|
|
(ROOT / TABLE_REL).write_bytes("\n".join(lines).encode())
|
|
|
|
|
|
# ----------------------------------------------------------------------------------------------- compare
|
|
|
|
|
|
def compare_one(nvcc: str, tk: Path, work: Path, ptx_rel: str, recipe: dict, installed: dict, timeout: int) -> dict:
|
|
rec = {"name": Path(ptx_rel).name, "method_installed": installed["method"]}
|
|
if recipe.get("method") != "recompile":
|
|
rec["native"] = "no verified recipe"
|
|
return rec
|
|
out = work / f"{Path(ptx_rel).stem}.native86.ptx"
|
|
ok, why = compile_cu(nvcc, ROOT, recipe["cu"], swap_arch(recipe["flags"], ARCH), recipe["includes"], out, timeout)
|
|
if not ok:
|
|
rec["native"] = "compile failed: " + why
|
|
return rec
|
|
nat = body_of(out.read_bytes())
|
|
comp = body_of((ROOT / OUT_REL / installed["name"]).read_bytes())
|
|
pok, pmsg = ptxas_check(tk, out, ARCH, timeout)
|
|
ne, ce = mask_entries(entries_with_params(nat)), mask_entries(entries_with_params(comp))
|
|
gn, gc = mask_entries(geometry(nat)), mask_entries(geometry(comp))
|
|
rec.update(native="compiled", ptxas_ok=pok, native_bytes=len(nat), entries_equal=ne == ce,
|
|
only_native=sorted(set(ne) - set(ce))[:3], only_companion=sorted(set(ce) - set(ne))[:3],
|
|
geometry_equal=gn == gc, static_shared_native=static_shared_bytes(nat), static_shared_companion=static_shared_bytes(comp),
|
|
identical_to_companion=mask_names(normalize(nat)) == mask_names(normalize(comp)))
|
|
if not pok:
|
|
rec["ptxas"] = pmsg
|
|
return rec
|
|
|
|
|
|
def cmd_compare(args) -> int:
|
|
tk = Path(args.toolkit).resolve()
|
|
work = Path(args.work).resolve() / "compare"
|
|
work.mkdir(parents=True, exist_ok=True)
|
|
recipes = json.loads((ROOT / RECIPES_REL).read_text())["assets"]
|
|
man = json.loads((ROOT / OUT_REL / MANIFEST_NAME).read_text())
|
|
by_path = {a["sm120_path"]: a for a in man["assets"]}
|
|
nvcc = str(tk / "bin" / "nvcc")
|
|
rows = []
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=args.jobs) as pool:
|
|
futs = [pool.submit(compare_one, nvcc, tk, work, p, recipes.get(p, {}), a, args.timeout) for p, a in sorted(by_path.items())]
|
|
for f in concurrent.futures.as_completed(futs):
|
|
r = f.result()
|
|
rows.append(r)
|
|
print(" " + json.dumps(r, sort_keys=True)[:230], flush=True)
|
|
rows.sort(key=lambda r: r["name"])
|
|
if args.report:
|
|
Path(args.report).write_text(json.dumps({"nvcc": nvcc_banner(nvcc), "rows": rows}, indent=1) + "\n")
|
|
c = Counter(("identical" if r.get("identical_to_companion") else
|
|
"differs" if r.get("native") == "compiled" else r.get("native", "?").split(":")[0]) for r in rows)
|
|
print("native sm_86 compile vs installed companion:", dict(c))
|
|
return 0
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------------ check
|
|
|
|
|
|
def cmd_check(args) -> int:
|
|
man = json.loads((ROOT / OUT_REL / MANIFEST_NAME).read_text())
|
|
bad, names = 0, set()
|
|
for a in man["assets"]:
|
|
names.add(a["name"])
|
|
f = ROOT / OUT_REL / a["name"]
|
|
s120 = body_of((ROOT / a["sm120_path"]).read_bytes())
|
|
problems = []
|
|
d = f.read_bytes() if f.is_file() else None
|
|
if d is None:
|
|
problems.append("companion missing")
|
|
else:
|
|
if sha256_hex(d) != a["sm86_sha256"] or len(d) != a["sm86_bytes"]:
|
|
problems.append("companion differs from manifest")
|
|
problems += structural_problems(s120, d)
|
|
if a["method"] == "retarget":
|
|
again, _ = retarget(s120)
|
|
if again != d:
|
|
problems.append("retarget companion is not the rule output for the current sm_120 original")
|
|
if sha256_hex(s120) != a["sm120_sha256"]:
|
|
problems.append("sealed sm_120 original changed since the companion was built (re-run build)")
|
|
if problems:
|
|
bad += 1
|
|
print(f" FAIL {a['name']}: {'; '.join(problems)}")
|
|
extra = sorted(p.name for p in (ROOT / OUT_REL).glob("*.ptx") if p.name not in names)
|
|
if extra:
|
|
bad += 1
|
|
print(f" FAIL companions not in the manifest: {extra}")
|
|
sealed = {Path(p).name for p in sealed_ptx_paths(ROOT)}
|
|
uncovered = sorted(sealed - names - {n["name"] for n in man["not_built"]})
|
|
if uncovered:
|
|
bad += 1
|
|
print(f" FAIL sealed sm_120 PTX with no companion and no not_built record: {uncovered}")
|
|
print(f"checked {len(man['assets'])} companions, {len(man['not_built'])} documented as not built: " + ("FAILED" if bad else "OK"))
|
|
return 1 if bad else 0
|
|
|
|
|
|
def main(argv=None) -> int:
|
|
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
sub.add_parser("survey")
|
|
sub.add_parser("check")
|
|
for name in ("infer", "build", "compare"):
|
|
p = sub.add_parser(name)
|
|
p.add_argument("--toolkit", required=True)
|
|
p.add_argument("--work", required=True, help="scratch directory for intermediate PTX")
|
|
p.add_argument("--jobs", type=int, default=6)
|
|
p.add_argument("--timeout", type=int, default=3600)
|
|
p.add_argument("--only", help="comma list of PTX stems")
|
|
if name == "build":
|
|
p.add_argument("--allow-failures", action="store_true")
|
|
if name == "compare":
|
|
p.add_argument("--report")
|
|
args = ap.parse_args(argv)
|
|
return {"survey": cmd_survey, "infer": cmd_infer, "build": cmd_build, "compare": cmd_compare, "check": cmd_check}[args.cmd](args)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|