Files
leleka/scripts/gpu-bringup/compile_assets.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 671be9c786 feat(gpu-bringup): compile_assets/seal_pins toolkit for the Linux nvcc session
compile_assets.py reads docs/cuda-seal-plan*.json (assets and new_sources
formats), an extra plan for assets no plan covers, and the four rope PTX list
of docs/rope-and-memory-plan.md; verifies .cu pins, runs nvcc with the exact
flags (fast-math policy lint, rope flag variants), validates exports and ABI
parameter counts, and writes PTX + build-manifest.json outside the tree.
seal_pins.py installs the PTX in the encoding each consumer expects and patches
every pin form (PtxPin arrays/structs, AssetSpec.sha, Option tuple arrays,
plain len/sha consts, re-pins of regenerated rope PTX, ptx_abi test) with
exactly one replacement per field and a read-back check. fake-nvcc and a
unittest suite exercise the pipeline on macOS; no GPU, no generated PTX.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 16:54:39 +02:00

366 lines
17 KiB
Python
Executable File

#!/usr/bin/env python3
"""Compile every unsealed CUDA asset to PTX with the exact recipe of its seal plan (no GPU needed).
Reads docs/cuda-seal-plan*.json (assets / new_sources formats), scripts/gpu-bringup/extra-seal-plan.json and the
four-PTX rope regeneration list of docs/rope-and-memory-plan.md. For each asset: verify the .cu pin, run nvcc with
the plan's flags, validate the PTX (ASCII, no NUL, sm_120, exported .entry names, ABI parameter counts) and write
it to --out together with build-manifest.json. The tree is NOT modified; scripts/gpu-bringup/seal_pins.py
installs the PTX and patches the Rust pins.
compile_assets.py --list
compile_assets.py --preflight # Mac-safe: pins, includes, policy lint, sealed shas
compile_assets.py --dry-run --rope-flags preserve # prints the nvcc command lines
compile_assets.py --fake-nvcc --out /tmp/x --rope-flags preserve # exercise the pipeline, FAKE PTX
compile_assets.py --toolkit $HOME/cuda-13.0.88 --out DIR --rope-flags preserve
Exit status 0 only if every selected asset compiled and validated.
"""
from __future__ import annotations
import argparse
import concurrent.futures
import datetime as dt
import json
import os
import re
import subprocess
import sys
from pathlib import Path
from typing import Dict, List, Optional
sys.path.insert(0, str(Path(__file__).resolve().parent))
import bringup_lib as L # noqa: E402
FAKE_NVCC = Path(__file__).resolve().parent / "fake-nvcc"
# ------------------------------------------------------------------------------------------ selection
def select_assets(assets: List[L.Asset], args) -> List[L.Asset]:
groups = set(filter(None, (args.group or "").split(",")))
only = set(filter(None, (args.only or "").split(",")))
skip = set(filter(None, (args.skip or "").split(",")))
known = {a.id for a in assets} | {a.group for a in assets}
unknown = (only | skip | groups) - known
if unknown:
raise L.PlanError(f"unknown asset/group: {', '.join(sorted(unknown))}")
out = []
for a in assets:
if only and a.id not in only:
continue
if groups and a.group not in groups:
continue
if a.id in skip:
continue
if a.optional and not (args.include_optional or a.id in only or a.group in groups):
continue
out.append(a)
return out
def nvcc_command(nvcc: str, asset: L.Asset, out_file: Path) -> List[str]:
return [nvcc] + asset.flags + [f"-I{d}" for d in asset.includes] + [asset.cu, "-o", str(out_file)]
# ---------------------------------------------------------------------------------------- toolkit
def locate_nvcc(args, root: Path) -> Optional[str]:
if args.fake_nvcc:
return str(FAKE_NVCC)
if args.nvcc:
return args.nvcc
if args.toolkit:
tk = Path(args.toolkit).resolve()
nvcc = tk / "bin" / "nvcc"
prov = tk / "TOOLKIT-PROVENANCE.json"
if not nvcc.is_file():
raise L.PlanError(f"{nvcc} not found")
if prov.is_file():
lock = root / L.TOOLKIT_LOCK
if json.loads(prov.read_text(encoding="utf-8")).get("lock") != json.loads(lock.read_text(encoding="utf-8")):
raise L.PlanError("toolkit provenance does not match deploy/cuda-toolkit.lock.json")
elif not args.allow_unprovenanced:
raise L.PlanError(f"{tk} has no TOOLKIT-PROVENANCE.json (scripts/bootstrap-cuda-toolkit.py writes it); "
"pass --allow-unprovenanced to use it anyway")
return str(nvcc)
return None
def nvcc_version(nvcc: str) -> Dict[str, str]:
p = subprocess.run([nvcc, "--version"], capture_output=True, text=True, timeout=60)
text = (p.stdout or "") + (p.stderr or "")
if p.returncode != 0:
raise L.PlanError(f"{nvcc} --version failed: {text.strip()[:200]}")
m = re.search(r"release (\d+\.\d+), V(\d+\.\d+\.\d+)", text)
return {"banner": text.strip().splitlines()[-1] if text.strip() else "", "release": m.group(1) if m else "",
"version": m.group(2) if m else ""}
# ------------------------------------------------------------------------------------------ compile
def compile_one(root: Path, nvcc: str, asset: L.Asset, out_dir: Path, args, fake: bool) -> dict:
rec: dict = {"id": asset.id, "group": asset.group, "cu": asset.cu, "ptx": asset.ptx,
"ptx_file": asset.ptx_name, "encoding": asset.encoding, "flags": asset.flags + [f"-I{d}" for d in asset.includes],
"plan": asset.plan, "status": "failed", "problems": []}
status, detail = L.check_cu_pin(root, asset)
rec["cu_pin_status"] = status
if status in ("stale", "missing"):
rec["problems"].append(f"refusing: {detail}")
return rec
cu_bytes = (root / asset.cu).read_bytes()
rec["cu_sha256"] = L.sha256_hex(cu_bytes)
rec["cu_bytes"] = len(cu_bytes)
L.fill_derived_entries(root, asset)
rec["entries_derived"] = asset.entries_derived
lint = L.policy_conflicts(asset)
if lint and not args.ignore_policy_lint:
rec["problems"] += [f"policy lint: {m}" for m in lint]
return rec
rec["policy_lint_ignored"] = lint
tmp = out_dir / (asset.ptx_name + ".tmp")
cmd = nvcc_command(nvcc, asset, tmp)
rec["command"] = cmd
env = dict(os.environ)
if fake:
# an operator/test may pre-set these to simulate a compiler that drops an export
env.setdefault("FAKE_NVCC_ENTRIES", ",".join(
f"{e}:{asset.params[e]}" if e in asset.params else e for e in asset.entries))
env.setdefault("FAKE_NVCC_PREFIX", ",".join(f"{p}:{n}" for p, n in asset.entry_prefix_counts.items()))
log = out_dir / f"{asset.id}.nvcc.log"
try:
proc = subprocess.run(cmd, cwd=str(root), capture_output=True, text=True, env=env, timeout=args.timeout)
except subprocess.TimeoutExpired:
rec["problems"].append(f"nvcc timed out after {args.timeout}s")
return rec
log.write_text(f"$ {' '.join(cmd)}\n--- stdout\n{proc.stdout}\n--- stderr\n{proc.stderr}\n--- exit {proc.returncode}\n",
encoding="utf-8")
rec["log"] = log.name
if proc.returncode != 0:
tail = (proc.stderr or proc.stdout).strip().splitlines()[-3:]
rec["problems"].append(f"nvcc exit {proc.returncode}: {' | '.join(tail)}")
tmp.unlink(missing_ok=True)
return rec
if not tmp.is_file():
rec["problems"].append("nvcc exited 0 but wrote no output")
return rec
raw = tmp.read_bytes()
problems = L.validate_ptx(raw, asset, allow_fake=fake)
final = out_dir / asset.ptx_name
if problems:
rec["problems"] += problems
tmp.replace(out_dir / (asset.ptx_name + ".rejected"))
return rec
tmp.replace(final)
rec.update({"status": "ok", "raw_bytes": len(raw), "raw_sha256": L.sha256_hex(raw),
"stored_bytes": len(L.stored_bytes(raw, asset.encoding)),
"entries_checked": len(asset.entries) + sum(asset.entry_prefix_counts.values()),
"fake": fake})
return rec
# ----------------------------------------------------------------------------------------- reports
def coverage_report(root: Path, planned: List[L.Asset]) -> dict:
ptx_planned = {a.ptx for a in planned}
uncovered = [p for p in L.scan_placeholders(root) if p not in ptx_planned]
return {"uncovered_placeholders": uncovered,
"wiring_gaps_option_none_assets": [f"{f}: {n}" for f, n in L.scan_none_assets(root)]}
def print_list(assets: List[L.Asset], root: Path) -> None:
print(f"{'group':<13} {'id':<38} {'enc':<8} {'pins':<5} {'flags'}")
for a in assets:
flags = " ".join(a.flags + [f"-I{d}" for d in a.includes][:0])
extra = ""
if a.deferred:
extra = " DEFERRED: " + a.deferred[:70]
elif a.optional:
extra = " (optional)"
ev = L.committed_fastmath_evidence(root, a) if a.group == "rope" else None
if ev is not None:
extra += f" [committed PTX has {ev} .ftz tokens]"
n_pins = sum(len(v) for v in a.pin_fields.values())
print(f"{a.group:<13} {a.id:<38} {'NUL' if a.encoding == 'include_bytes' else 'raw':<8} {n_pins:<5} {flags}{extra}")
def preflight(root: Path, assets: List[L.Asset], everything: List[L.Asset]) -> int:
bad = 0
print("== .cu pins and includes")
for a in assets:
if a.deferred:
print(f" skip {a.id}: deferred ({a.deferred[:60]}...)")
continue
status, detail = L.check_cu_pin(root, a)
missing = L.resolve_includes(root, a)
lint = L.policy_conflicts(a)
tag = "ok" if status in ("ok", "unpinned") and not missing and not lint else "PROBLEM"
bad += tag != "ok"
print(f" {tag:<9} {a.id:<38} cu_pin={status}" + (f" includes missing: {missing[:2]}" if missing else "")
+ (f" lint: {lint}" if lint else "") + (f" {detail}" if status in ('stale', 'missing') else ""))
print("== sealed assets bound by the window producers (committed PTX must keep matching)")
for item in L.window_sealed_bound(root):
p = root / item["ptx"]
if not p.is_file():
print(f" PROBLEM {item['ptx']} missing")
bad += 1
continue
got = L.sha256_hex(L.raw_from_stored(p.read_bytes()))
ok = got == item["sha256"]
bad += not ok
print(f" {'ok' if ok else 'MISMATCH':<9} {Path(item['ptx']).name:<40}" + ("" if ok else f" committed {got[:12]}.. plan {item['sha256'][:12]}.."))
print("== coverage")
cov = coverage_report(root, everything)
for p in cov["uncovered_placeholders"]:
print(f" UNCOVERED placeholder PTX (in no plan): {p}")
for g in cov["wiring_gaps_option_none_assets"]:
print(f" note: fail-closed Option<&[u8]> = None needs wiring, not sealing: {g}")
bad += len(cov["uncovered_placeholders"])
exp = L.toolkit_expected_version(root)
print(f"== toolkit lock pins nvcc {exp}")
print("PREFLIGHT " + ("FAILED" if bad else "OK"))
return 1 if bad else 0
# ------------------------------------------------------------------------------------------- main
def git_head(root: Path) -> str:
try:
r = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True, timeout=20)
return r.stdout.strip() if r.returncode == 0 else ""
except OSError:
return ""
def build_parser() -> argparse.ArgumentParser:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--root", default=str(L.REPO), help="repository root (default: this checkout)")
ap.add_argument("--out", help="output directory for PTX + build-manifest.json (must not contain a manifest)")
ap.add_argument("--toolkit", help="pinned toolkit dir from scripts/bootstrap-cuda-toolkit.py")
ap.add_argument("--nvcc", help="explicit nvcc binary (e.g. inside a pinned docker image)")
ap.add_argument("--fake-nvcc", action="store_true", help="use scripts/gpu-bringup/fake-nvcc (FAKE PTX, pipeline test only)")
ap.add_argument("--allow-unprovenanced", action="store_true")
ap.add_argument("--expect-version", help="required nvcc version (default: cuda_nvcc of deploy/cuda-toolkit.lock.json; 'any' skips)")
ap.add_argument("--rope-flags", choices=L.ROPE_VARIANTS,
help="flag variant for the four rope PTX; required when they are selected (see docs/gpu-bringup.md D1)")
ap.add_argument("--no-rope", action="store_true", help="leave the four rope PTX out")
ap.add_argument("--group", help="comma list of groups (additions, experimental, window, kar, rope, mmq_group, ...)")
ap.add_argument("--only", help="comma list of asset ids")
ap.add_argument("--skip", help="comma list of asset ids")
ap.add_argument("--include-optional", action="store_true", help="also compile optional groups (mmq_group)")
ap.add_argument("--list", action="store_true")
ap.add_argument("--preflight", action="store_true", help="no compile: pins, includes, lint, sealed shas, coverage")
ap.add_argument("--dry-run", action="store_true", help="print the nvcc command lines, run nothing")
ap.add_argument("--jobs", type=int, default=2)
ap.add_argument("--timeout", type=int, default=1800, help="seconds per nvcc invocation")
ap.add_argument("--fail-fast", action="store_true")
ap.add_argument("--ignore-policy-lint", action="store_true")
return ap
def main(argv: Optional[List[str]] = None) -> int:
args = build_parser().parse_args(argv)
root = Path(args.root).resolve()
list_only = args.list or args.preflight
if list_only:
args.include_optional = True
rope_variant = None if args.no_rope else (args.rope_flags or ("precise" if list_only else None))
try:
assets, _ = L.load_all_assets(root, rope_variant)
selected = select_assets(assets, args)
except L.PlanError as error:
print(f"error: {error}", file=sys.stderr)
return 2
if args.list:
print_list(selected, root)
return 0
if args.preflight:
return preflight(root, selected, assets)
if not args.no_rope and not args.rope_flags:
print("error: choose --rope-flags precise|preserve (or --no-rope); see docs/gpu-bringup.md decision D1", file=sys.stderr)
return 2
runnable = [a for a in selected if not a.deferred]
deferred = [a for a in selected if a.deferred]
if not runnable:
print("error: nothing selected", file=sys.stderr)
return 2
fake = args.fake_nvcc
nvcc = locate_nvcc(args, root)
if args.dry_run:
out_dir = Path(args.out or "<OUT>")
print(f"# dry run: {len(runnable)} nvcc invocations, cwd={root}")
for a in runnable:
status, detail = L.check_cu_pin(root, a)
print(f"# {a.id} [{a.group}] cu_pin={status}" + (f" !! {detail}" if status in ("stale", "missing") else ""))
print(" ".join(nvcc_command(nvcc or "nvcc", a, out_dir / a.ptx_name)))
for a in deferred:
print(f"# DEFERRED {a.id}: {a.deferred}")
return 0
if nvcc is None:
print("error: need --toolkit DIR, --nvcc PATH or --fake-nvcc", file=sys.stderr)
return 2
if not args.out:
print("error: --out DIR is required", file=sys.stderr)
return 2
out_dir = Path(args.out).resolve()
if (out_dir / "build-manifest.json").exists():
print(f"error: {out_dir}/build-manifest.json already exists; use a fresh --out", file=sys.stderr)
return 2
out_dir.mkdir(parents=True, exist_ok=True)
try:
version = nvcc_version(nvcc)
except (OSError, L.PlanError, subprocess.SubprocessError) as error:
print(f"error: {error}", file=sys.stderr)
return 2
expected = args.expect_version or L.toolkit_expected_version(root)
if not fake and expected and expected != "any" and version["version"] != expected:
print(f"error: nvcc is {version['version'] or version['banner']!r}, the toolkit lock pins {expected}.\n"
f" Use --expect-version {version['version']} (or any) only if the owner accepted that toolchain.", file=sys.stderr)
return 2
print(f"nvcc: {version['banner']} ({nvcc}){' [FAKE]' if fake else ''}")
records: List[dict] = []
failed = False
def run(a: L.Asset) -> dict:
return compile_one(root, nvcc, a, out_dir, args, fake)
with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, args.jobs)) as pool:
futures = {pool.submit(run, a): a for a in runnable}
for fut in concurrent.futures.as_completed(futures):
rec = fut.result()
records.append(rec)
ok = rec["status"] == "ok"
failed |= not ok
print(f" {'ok ' if ok else 'FAIL'} {rec['id']:<38}" + (f" {rec['raw_bytes']:>8} B" if ok else " " + "; ".join(rec["problems"])[:200]))
if failed and args.fail_fast:
for f in futures:
f.cancel()
break
records.sort(key=lambda r: r["id"])
manifest = {
"schema": 1,
"tool": "scripts/gpu-bringup/compile_assets.py",
"created_utc": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
"repo_head": git_head(root),
"repo_root": str(root),
"fake": fake,
"nvcc": {"path": nvcc, **version},
"toolkit_lock_nvcc": L.toolkit_expected_version(root),
"rope_flags": args.rope_flags,
"assets": records,
"deferred": [{"id": a.id, "reason": a.deferred} for a in deferred],
"coverage": coverage_report(root, selected),
}
(out_dir / "build-manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
nfail = sum(r["status"] != "ok" for r in records)
print(f"{len(records) - nfail} ok, {nfail} failed, {len(deferred)} deferred; manifest: {out_dir}/build-manifest.json")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())