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).
668 lines
27 KiB
Python
668 lines
27 KiB
Python
"""Shared helpers for the GPU bring-up toolkit (plan loading, PTX checks, hashing).
|
|
|
|
Pure standard library, Python >= 3.9. Nothing here touches a GPU, the network or nvcc.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import re
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import Dict, List, Optional, Tuple
|
|
|
|
HERE = Path(__file__).resolve().parent
|
|
REPO = HERE.parents[1]
|
|
|
|
MAX_PTX_BYTES = 16 * 1024 * 1024
|
|
TOOLKIT_LOCK = "deploy/cuda-toolkit.lock.json"
|
|
EXTRA_PLAN = "scripts/gpu-bringup/extra-seal-plan.json"
|
|
SEAL_PLAN_DIR = "crates/cuda-driver/seal-plans"
|
|
ROPE_DOC = "scripts/gpu-bringup/rope-regeneration.json"
|
|
ABI_SOURCE = "crates/context/src/ptx_abi.rs"
|
|
|
|
# -I set the sealed PTX were built with (repo-root relative). The two strata-41cf05a0 directories are an upstream checkout (third_party/strata/UPSTREAM.md);
|
|
# an asset whose source includes a strata/ header needs that checkout placed at strata-41cf05a0/ to compile.
|
|
STANDARD_INCLUDES = [
|
|
"strata-41cf05a0/include",
|
|
"strata-41cf05a0/third_party/ggml",
|
|
"crates/cuda-driver/src/third_party/llamacpp/ggml-cuda",
|
|
"crates/cuda-driver/src/third_party/llamacpp/ggml-include",
|
|
"crates/cuda-driver/src/third_party/llamacpp/ggml-src",
|
|
]
|
|
|
|
# Encoding of the stored .ptx file, as the Rust consumer reads it.
|
|
# include_bytes file = raw PTX + exactly one terminal NUL (include_bytes!)
|
|
# concat_include_str file = raw PTX, no NUL (concat!(include_str!(..), "\0"))
|
|
ENCODINGS = ("include_bytes", "concat_include_str")
|
|
|
|
# Rust consumer tables for plan entries that do not carry rust_fields_to_fill themselves.
|
|
# (Window plan "new_sources" name the AssetSpec only in prose.)
|
|
WINDOW_PIN_TARGETS = {
|
|
"original_verify_window_moe_experts": {"original_verify_window_moe.rs": ["EXPERTS.sha"]},
|
|
"original_verify_window_qsa_gate": {"original_verify_window_qsa.rs": ["GATE.sha"]},
|
|
}
|
|
|
|
|
|
class PlanError(ValueError):
|
|
pass
|
|
|
|
|
|
def sha256_hex(data: bytes) -> str:
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def sha256_digest(data: bytes) -> bytes:
|
|
return hashlib.sha256(data).digest()
|
|
|
|
|
|
# ----------------------------------------------------------------------------------------------- model
|
|
|
|
|
|
@dataclass
|
|
class Asset:
|
|
id: str # ptx basename without ".ptx"
|
|
cu: str # repo-relative
|
|
ptx: str # repo-relative installation path
|
|
flags: List[str]
|
|
includes: List[str] = field(default_factory=list)
|
|
cu_pin: Optional[dict] = None # {"sha256", "bytes"}; None = no pin in the plan (recorded only)
|
|
entries: List[str] = field(default_factory=list)
|
|
entry_prefix_counts: Dict[str, int] = field(default_factory=dict)
|
|
entries_derived: bool = False
|
|
encoding: str = "include_bytes"
|
|
pin_fields: Dict[str, List[str]] = field(default_factory=dict) # consumer file name -> field specs
|
|
plan: str = ""
|
|
group: str = ""
|
|
policy: str = ""
|
|
params: Dict[str, int] = field(default_factory=dict) # entry -> expected .param count
|
|
repin_expect: Dict[str, int] = field(default_factory=dict) # repo file -> expected decimal-pin hits
|
|
deferred: Optional[str] = None
|
|
optional: bool = False
|
|
atomic_group: Optional[str] = None # all members must be sealed together
|
|
notes: List[str] = field(default_factory=list)
|
|
seal_fields: bool = False # the plan entry carries seal_sha256/seal_length slots to fill
|
|
entries_from_symbols: bool = False # entry names live in crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/full_forward/symbols.rs
|
|
flag_overrides: List[str] = field(default_factory=list) # operator overrides applied (recorded in the manifest)
|
|
|
|
@property
|
|
def ptx_name(self) -> str:
|
|
return Path(self.ptx).name
|
|
|
|
|
|
# ------------------------------------------------------------------------------------------ plan files
|
|
|
|
|
|
def _group_from_plan_name(name: str) -> str:
|
|
stem = Path(name).stem
|
|
stem = stem.replace("cuda-seal-plan-additions", "additions").replace("cuda-seal-plan", "plan")
|
|
return stem.replace("additions-", "")
|
|
|
|
|
|
def split_nvcc_flags(tokens: List[str]) -> Tuple[List[str], List[str]]:
|
|
"""Separate -I<dir> tokens (and '-I dir' pairs) from the other flags; order is preserved per list."""
|
|
flags: List[str] = []
|
|
includes: List[str] = []
|
|
i = 0
|
|
while i < len(tokens):
|
|
t = tokens[i]
|
|
if t == "-I" and i + 1 < len(tokens):
|
|
includes.append(tokens[i + 1])
|
|
i += 2
|
|
continue
|
|
if t.startswith("-I") and len(t) > 2:
|
|
includes.append(t[2:])
|
|
else:
|
|
flags.append(t)
|
|
i += 1
|
|
return flags, includes
|
|
|
|
|
|
def _clean_pin(pin) -> Optional[dict]:
|
|
if pin is None:
|
|
return None
|
|
if not isinstance(pin, dict) or "sha256" not in pin:
|
|
raise PlanError(f"bad cu_pin {pin!r}")
|
|
return {"sha256": str(pin["sha256"]).lower(), "bytes": pin.get("bytes")}
|
|
|
|
|
|
def asset_from_assets_entry(entry: dict, plan: str, group: str) -> Asset:
|
|
for key in ("cu", "ptx", "flags"):
|
|
if key not in entry:
|
|
raise PlanError(f"{plan}: asset without '{key}': {entry.get('cu') or entry}")
|
|
enc = entry.get("encoding", "include_bytes")
|
|
if enc == "mixed":
|
|
# stra169 'mixed' (gdn_native_batch + qsa_native_batch): the file is read through concat_include_str.
|
|
enc = "concat_include_str"
|
|
if enc not in ENCODINGS:
|
|
raise PlanError(f"{plan}: unknown encoding {enc!r} for {entry['cu']}")
|
|
flags, includes = split_nvcc_flags(list(entry["flags"]))
|
|
a = Asset(
|
|
id=Path(entry["ptx"]).stem,
|
|
cu=entry["cu"],
|
|
ptx=entry["ptx"],
|
|
flags=flags,
|
|
includes=includes,
|
|
cu_pin=_clean_pin(entry.get("cu_pin")),
|
|
entries=list(entry.get("entries") or entry.get("exports") or []),
|
|
entry_prefix_counts=dict(entry.get("entry_prefix_counts") or {}),
|
|
encoding=enc,
|
|
pin_fields={k: list(v) for k, v in (entry.get("rust_fields_to_fill") or {}).items()},
|
|
plan=plan,
|
|
group=entry.get("group", group),
|
|
policy=entry.get("policy", ""),
|
|
params={k: int(v) for k, v in (entry.get("params") or {}).items()},
|
|
deferred=entry.get("deferred"),
|
|
optional=bool(entry.get("optional", False)),
|
|
atomic_group=entry.get("atomic_group"),
|
|
seal_fields="seal_sha256" in entry and "seal_length" in entry,
|
|
entries_from_symbols=bool(entry.get("entries_from_symbols", False)),
|
|
repin_expect={k: int(v) for k, v in (entry.get("repin_expect") or {}).items()},
|
|
)
|
|
if "include_profile" in entry:
|
|
if entry["include_profile"] != "standard":
|
|
raise PlanError(f"{plan}: unknown include_profile {entry['include_profile']!r}")
|
|
a.includes = list(STANDARD_INCLUDES) + a.includes
|
|
if entry.get("note"):
|
|
a.notes.append(str(entry["note"]))
|
|
return a
|
|
|
|
|
|
def asset_from_window_source(entry: dict, plan: str, group: str) -> Asset:
|
|
for key in ("source", "ptx", "nvcc"):
|
|
if key not in entry:
|
|
raise PlanError(f"{plan}: new_sources item without '{key}'")
|
|
flags, includes = split_nvcc_flags(list(entry["nvcc"]))
|
|
ident = Path(entry["ptx"]).stem
|
|
if ident not in WINDOW_PIN_TARGETS:
|
|
raise PlanError(f"{plan}: no pin target registered for window asset {ident!r} (bringup_lib.WINDOW_PIN_TARGETS)")
|
|
a = Asset(
|
|
id=ident,
|
|
cu=entry["source"],
|
|
ptx=entry["ptx"],
|
|
flags=flags,
|
|
includes=includes,
|
|
cu_pin=None, # the window plan does not pin the new sources; the compile manifest does
|
|
entries=list(entry.get("exports") or []),
|
|
encoding="include_bytes", # "append exactly ONE terminal NUL byte"
|
|
pin_fields={k: list(v) for k, v in WINDOW_PIN_TARGETS[ident].items()},
|
|
plan=plan,
|
|
group=group,
|
|
policy=str(entry.get("nvcc_note") or entry.get("derived_from") or ""),
|
|
)
|
|
for key in ("notes", "install"):
|
|
if entry.get(key):
|
|
a.notes.append(str(entry[key]))
|
|
return a
|
|
|
|
|
|
def load_plan_file(path: Path) -> List[Asset]:
|
|
try:
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
except (OSError, ValueError) as error:
|
|
raise PlanError(f"{path}: {error}") from error
|
|
group = _group_from_plan_name(path.name)
|
|
out: List[Asset] = []
|
|
known = False
|
|
if "assets" in data:
|
|
known = True
|
|
out += [asset_from_assets_entry(a, path.name, group) for a in data["assets"]]
|
|
if "new_sources" in data:
|
|
known = True
|
|
out += [asset_from_window_source(a, path.name, group) for a in data["new_sources"]]
|
|
if not known:
|
|
raise PlanError(f"{path.name}: neither 'assets' nor 'new_sources' present; unrecognised plan format")
|
|
return out
|
|
|
|
|
|
def window_sealed_bound(root: Path) -> List[dict]:
|
|
"""sealed_assets_bound of the window plan: committed PTX the producers pin by sha256 (not to be rebuilt)."""
|
|
path = root / SEAL_PLAN_DIR / "cuda-seal-plan-additions-window.json"
|
|
if not path.is_file():
|
|
return []
|
|
return list(json.loads(path.read_text(encoding="utf-8")).get("sealed_assets_bound", []))
|
|
|
|
|
|
# ----------------------------------------------------------------------------------- rope doc / ABI
|
|
|
|
|
|
def parse_rope_recipe(text: str) -> Tuple[List[str], List[str], List[str]]:
|
|
"""Return (nvcc flags, include dirs repo-relative, source basenames) from rope-regeneration.json."""
|
|
try:
|
|
data = json.loads(text)
|
|
except ValueError as exc:
|
|
raise PlanError(f"rope recipe: not JSON: {exc}")
|
|
for key in ("flags", "includes", "sources"):
|
|
if not isinstance(data.get(key), list) or not data[key]:
|
|
raise PlanError(f"rope recipe: '{key}' must be a non-empty list")
|
|
return list(data["flags"]), list(data["includes"]), list(data["sources"])
|
|
|
|
|
|
def parse_abi_tuples(text: str) -> Dict[str, Dict[str, Tuple[int, int]]]:
|
|
"""('file.ptx', 'entry', frozen, extra) tuples of ptx_abi.rs -> {file: {entry: (frozen, extra)}}."""
|
|
out: Dict[str, Dict[str, Tuple[int, int]]] = {}
|
|
for f, e, a, b in re.findall(r'\(\s*"([\w.\-]+\.ptx)"\s*,\s*"(\w+)"\s*,\s*(\d+)\s*,\s*(\d+)\s*\)', text):
|
|
out.setdefault(f, {})[e] = (int(a), int(b))
|
|
return out
|
|
|
|
|
|
ROPE_VARIANTS = ("precise", "preserve")
|
|
# Sources that the Original compiles with --use_fast_math (Strata 41cf05a0, CMakeLists.txt native_* list); the
|
|
# committed PTX of these two contain .ftz instructions, i.e. they were built fast-math (stra169 plan).
|
|
ROPE_FASTMATH_SOURCES = ("qsa_prompt_indexer", "qsa_decode_postops")
|
|
# decimal-pin hits expected in the Rust tree for the committed digests (found by scanning, see seal_pins)
|
|
ROPE_REPIN_EXPECT = {
|
|
"qsa_prompt_indexer": {},
|
|
"qsa_prompt_postops": {"crates/cuda-driver/src/original_verify/qsa.rs": 1},
|
|
"qsa_decode_postops": {"crates/cuda-driver/src/original_verify/qsa.rs": 1},
|
|
"qsa_prompt_resolver": {"crates/cuda-driver/src/original_verify/qsa.rs": 1},
|
|
}
|
|
# hex pins in the window plan (sealed_assets_bound)
|
|
ROPE_HEX_DOC = SEAL_PLAN_DIR + "/cuda-seal-plan-additions-window.json"
|
|
|
|
|
|
def rope_assets(root: Path, variant: str) -> List[Asset]:
|
|
"""The four QSA PTX that rope-regeneration.json lists for regeneration.
|
|
|
|
variant 'precise' : the recipe's flags verbatim (--fmad=true --ftz=false) for all four.
|
|
variant 'preserve' : same, except qsa_prompt_indexer / qsa_decode_postops keep --use_fast_math (how the
|
|
committed PTX were built; the Original compiles native_qsa_indexer/native_rope fast-math).
|
|
"""
|
|
if variant not in ROPE_VARIANTS:
|
|
raise PlanError(f"rope variant must be one of {ROPE_VARIANTS}")
|
|
doc = root / ROPE_DOC
|
|
abi = root / ABI_SOURCE
|
|
flags, includes, sources = parse_rope_recipe(doc.read_text(encoding="utf-8"))
|
|
tuples = parse_abi_tuples(abi.read_text(encoding="utf-8"))
|
|
out: List[Asset] = []
|
|
for src in sources:
|
|
f = list(flags)
|
|
if variant == "preserve" and src in ROPE_FASTMATH_SOURCES:
|
|
f = [t for t in f if t not in ("--fmad=true", "--ftz=false")] + ["--use_fast_math"]
|
|
cu = f"crates/cuda-driver/src/{src}.cu"
|
|
ptx = f"crates/cuda-driver/src/{src}.ptx"
|
|
entries = tuples.get(f"{src}.ptx", {})
|
|
a = Asset(
|
|
id=src,
|
|
cu=cu,
|
|
ptx=ptx,
|
|
flags=f,
|
|
includes=list(includes),
|
|
cu_pin=None,
|
|
entries=sorted(entries),
|
|
encoding="include_bytes",
|
|
plan=Path(ROPE_DOC).name,
|
|
group="rope",
|
|
policy=f"rope regeneration, variant {variant}",
|
|
params={e: fr + ex for e, (fr, ex) in entries.items()},
|
|
repin_expect=dict(ROPE_REPIN_EXPECT.get(src, {})),
|
|
atomic_group="rope",
|
|
)
|
|
out.append(a)
|
|
return out
|
|
|
|
|
|
# ------------------------------------------------------------------------------------- all assets
|
|
|
|
|
|
def load_all_assets(root: Path, rope_variant: Optional[str]) -> Tuple[List[Asset], List[str]]:
|
|
"""Every crates/cuda-driver/seal-plans/cuda-seal-plan*.json, the extra plan and (if rope_variant) the rope recipe.
|
|
|
|
Returns (assets, warnings). Duplicate asset ids across plans are an error."""
|
|
assets: List[Asset] = []
|
|
warnings: List[str] = []
|
|
plans = sorted((root / SEAL_PLAN_DIR).glob("cuda-seal-plan*.json"))
|
|
if not plans:
|
|
raise PlanError(f"no {SEAL_PLAN_DIR}/cuda-seal-plan*.json under {root}")
|
|
for p in plans:
|
|
assets += load_plan_file(p)
|
|
extra = root / EXTRA_PLAN
|
|
if extra.is_file():
|
|
assets += load_plan_file(extra)
|
|
if rope_variant:
|
|
assets += rope_assets(root, rope_variant)
|
|
seen: Dict[str, str] = {}
|
|
for a in assets:
|
|
if a.id in seen:
|
|
raise PlanError(f"asset {a.id!r} appears in both {seen[a.id]} and {a.plan}")
|
|
seen[a.id] = a.plan
|
|
return assets, warnings
|
|
|
|
|
|
# ------------------------------------------------------------------------------ source / pin checks
|
|
|
|
|
|
def check_cu_pin(root: Path, asset: Asset) -> Tuple[str, str]:
|
|
"""('ok'|'unpinned'|'stale'|'missing', detail). Reads the .cu from root."""
|
|
path = root / asset.cu
|
|
if not path.is_file():
|
|
return "missing", f"{asset.cu} does not exist"
|
|
data = path.read_bytes()
|
|
if asset.cu_pin is None:
|
|
return "unpinned", sha256_hex(data)
|
|
got, want = sha256_hex(data), asset.cu_pin["sha256"]
|
|
if got != want:
|
|
return "stale", f"{asset.cu}: sha256 {got[:16]}.. != plan pin {want[:16]}.. (source edited since the plan)"
|
|
want_bytes = asset.cu_pin.get("bytes")
|
|
if want_bytes is not None and want_bytes != len(data):
|
|
return "stale", f"{asset.cu}: {len(data)} bytes != plan pin {want_bytes}"
|
|
return "ok", got
|
|
|
|
|
|
_INCLUDE_RE = re.compile(r'^\s*#\s*include\s+"([^"]+)"', re.M)
|
|
|
|
|
|
def resolve_includes(root: Path, asset: Asset) -> List[str]:
|
|
"""Quoted #include targets of the .cu (recursively) that resolve nowhere; [] if all resolve."""
|
|
dirs = [root / d for d in asset.includes]
|
|
missing: List[str] = []
|
|
seen = set()
|
|
|
|
def visit(path: Path) -> None:
|
|
if path in seen:
|
|
return
|
|
seen.add(path)
|
|
text = path.read_text(encoding="utf-8", errors="replace")
|
|
for inc in _INCLUDE_RE.findall(text):
|
|
for base in [path.parent] + dirs:
|
|
cand = base / inc
|
|
if cand.is_file():
|
|
visit(cand.resolve())
|
|
break
|
|
else:
|
|
missing.append(f"{inc} (from {path.name})")
|
|
|
|
src = root / asset.cu
|
|
if src.is_file():
|
|
visit(src.resolve())
|
|
return missing
|
|
|
|
|
|
def policy_conflicts(asset: Asset) -> List[str]:
|
|
"""Lint the fast-math policy notes against the flags (see window plan 'nvcc_note')."""
|
|
msgs = []
|
|
flags = set(asset.flags)
|
|
fast = "--use_fast_math" in flags or "-use_fast_math" in flags
|
|
if fast and ({"--ftz=false", "--prec-div=true", "--prec-sqrt=true"} & flags):
|
|
msgs.append("--use_fast_math together with --ftz=false/--prec-div=true/--prec-sqrt=true contradicts itself")
|
|
p = asset.policy.lower()
|
|
# "not in the CMake fast-math list" / "no fast-math" are negations, not claims of fast-math
|
|
p = re.sub(r"\b(?:not in|no|without)\s+(?:the\s+)?(?:cmake\s+)?(?:--use_)?fast-?math(?:\s+list)?", "", p)
|
|
says_precise = "precise" in p
|
|
says_fast = bool(re.search(r"fast-?math", p)) and not says_precise
|
|
if says_precise and fast:
|
|
msgs.append("policy says precise but flags contain --use_fast_math")
|
|
if says_fast and not fast:
|
|
msgs.append("policy says fast-math but flags lack --use_fast_math")
|
|
return msgs
|
|
|
|
|
|
# ----------------------------------------------------------------------------------------- PTX utils
|
|
|
|
_ENTRY_RE = re.compile(r"^\s*(?:\.visible\s+|\.weak\s+|\.extern\s+)?\.entry\s+([^\s(]+)", re.M)
|
|
|
|
|
|
def ptx_entries(text: str) -> List[str]:
|
|
return _ENTRY_RE.findall(text)
|
|
|
|
|
|
def entry_param_count(text: str, entry: str) -> Optional[int]:
|
|
"""Mirror of leleka-context ptx_abi::entry_param_count."""
|
|
needle = f".entry {entry}("
|
|
i = text.find(needle)
|
|
if i < 0:
|
|
return None
|
|
start = i + len(needle)
|
|
end = text.find(")", start)
|
|
if end < 0:
|
|
return None
|
|
return text[start:end].count(".param")
|
|
|
|
|
|
# CUDA 13.2.0 and 13.2.1 (nvcc 13.2.51) miscompile some sm_120 kernels (IQ2_S / IQ3_S products wrong, relative error 0.5-1.0;
|
|
# upstream Strata 41cf05a0, docs/TROUBLESHOOTING.md, #892, #968); 13.2.2 (nvcc 13.2.86) is right. Their PTX names the build in its header.
|
|
BAD_NVCC_BUILDS = ("13.2.0", "13.2.1", "13.2.51")
|
|
_NVCC_HEADER = re.compile(r"Cuda compilation tools, release [0-9.]+, V([0-9]+\.[0-9]+\.[0-9]+)")
|
|
|
|
|
|
def nvcc_build_of(ptx_head: str) -> Optional[str]:
|
|
"""The `V<major>.<minor>.<patch>` that the header of a PTX names, or None when it names none."""
|
|
m = _NVCC_HEADER.search(ptx_head[:4096])
|
|
return m.group(1) if m else None
|
|
|
|
|
|
def validate_ptx(raw: bytes, asset: Asset, allow_fake: bool = False) -> List[str]:
|
|
"""Problems with a freshly produced raw (NUL-free) PTX body; [] if acceptable."""
|
|
bad: List[str] = []
|
|
if not 0 < len(raw) <= MAX_PTX_BYTES:
|
|
return [f"size {len(raw)} outside 1..{MAX_PTX_BYTES}"]
|
|
if b"\0" in raw:
|
|
bad.append("contains a NUL byte")
|
|
if not raw.isascii():
|
|
bad.append("not ASCII")
|
|
if bad:
|
|
return bad
|
|
text = raw.decode("ascii")
|
|
if ".version" not in text:
|
|
bad.append("no .version directive")
|
|
if ".target sm_120" not in text:
|
|
bad.append("no '.target sm_120'")
|
|
for marker in ("UNSEALED", "PLACEHOLDER"):
|
|
if marker in text:
|
|
bad.append(f"contains the {marker} marker")
|
|
if not allow_fake and "FAKE-NVCC" in text:
|
|
bad.append("fake-nvcc output")
|
|
build = nvcc_build_of(text)
|
|
if build in BAD_NVCC_BUILDS:
|
|
bad.append(f"built by nvcc V{build}, which miscompiles some sm_120 kernels (CUDA 13.2.0/13.2.1); use 13.2.2 (V13.2.86)")
|
|
found = ptx_entries(text)
|
|
foundset = set(found)
|
|
missing = [e for e in asset.entries if e not in foundset]
|
|
if missing:
|
|
shown = ", ".join(missing[:8]) + (" ..." if len(missing) > 8 else "")
|
|
bad.append(f"missing {len(missing)} exported .entry: {shown}")
|
|
for prefix, count in asset.entry_prefix_counts.items():
|
|
n = sum(1 for e in foundset if e.startswith(prefix))
|
|
if n != count:
|
|
bad.append(f"{n} entries start with {prefix!r}, expected {count}")
|
|
for entry, want in asset.params.items():
|
|
got = entry_param_count(text, entry)
|
|
if got != want:
|
|
bad.append(f"entry {entry} has {got} params, expected {want}")
|
|
return bad
|
|
|
|
|
|
def stored_bytes(raw: bytes, encoding: str) -> bytes:
|
|
if encoding == "include_bytes":
|
|
return raw + b"\0"
|
|
if encoding == "concat_include_str":
|
|
return raw
|
|
raise PlanError(f"unknown encoding {encoding!r}")
|
|
|
|
|
|
def raw_from_stored(data: bytes) -> bytes:
|
|
"""The hashed PTX body of an installed file (strip at most one terminal NUL)."""
|
|
return data[:-1] if data.endswith(b"\0") else data
|
|
|
|
|
|
def committed_fastmath_evidence(root: Path, asset: Asset) -> Optional[int]:
|
|
"""Number of '.ftz' occurrences in the currently committed PTX (None if the file is absent/placeholder)."""
|
|
p = root / asset.ptx
|
|
if not p.is_file():
|
|
return None
|
|
text = p.read_bytes().decode("latin-1")
|
|
if "UNSEALED" in text or "PLACEHOLDER" in text:
|
|
return None
|
|
return text.count(".ftz")
|
|
|
|
|
|
# --------------------------------------------------------------------------------- placeholder scan
|
|
|
|
|
|
def scan_placeholders(root: Path) -> List[str]:
|
|
"""Repo-relative paths of every crates/cuda-driver/src/*.ptx that is an unsealed placeholder."""
|
|
out = []
|
|
for p in sorted((root / "crates/cuda-driver/src").glob("*.ptx")):
|
|
head = p.read_bytes()[:4096].decode("latin-1")
|
|
if "UNSEALED" in head or "PLACEHOLDER" in head:
|
|
out.append(str(p.relative_to(root)))
|
|
return out
|
|
|
|
|
|
_NONE_ASSET_RE = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?const\s+(\w+)\s*:\s*Option<&\[u8\]>\s*=\s*None;", re.M)
|
|
|
|
|
|
def scan_none_assets(root: Path) -> List[Tuple[str, str]]:
|
|
"""const X: Option<&[u8]> = None; -- fail-closed assets that need *wiring*, not just a seal."""
|
|
out = []
|
|
for p in sorted((root / "crates").rglob("*.rs")):
|
|
text = p.read_text(encoding="utf-8", errors="replace")
|
|
for name in _NONE_ASSET_RE.findall(text):
|
|
out.append((str(p.relative_to(root)), name))
|
|
return out
|
|
|
|
|
|
def toolkit_expected_version(root: Path) -> Optional[str]:
|
|
p = root / TOOLKIT_LOCK
|
|
if not p.is_file():
|
|
return None
|
|
for c in json.loads(p.read_text(encoding="utf-8")).get("components", []):
|
|
if c.get("component") == "cuda_nvcc":
|
|
return c.get("version")
|
|
return None
|
|
|
|
|
|
# ------------------------------------------------------------------------------- entry derivation
|
|
|
|
_KERNEL_RE = re.compile(
|
|
r'extern\s+"C"\s+__global__\s+(?:__launch_bounds__\([^)]*\)\s*)?void\s+(?:__launch_bounds__\([^)]*\)\s*)?([A-Za-z_]\w*)\s*\('
|
|
)
|
|
|
|
|
|
def derive_entries(root: Path, asset: Asset) -> List[str]:
|
|
"""extern "C" __global__ names in the .cu (as the stra169 seal script derived them).
|
|
|
|
Macro parameters (all-uppercase names) and compiler keywords are dropped; this is a lower bound, so a
|
|
derived list only proves 'these exist', never that nothing else is expected."""
|
|
src = root / asset.cu
|
|
names = _KERNEL_RE.findall(src.read_text(encoding="utf-8", errors="replace"))
|
|
keep = []
|
|
for n in names:
|
|
if n.startswith("__") or n.isupper() or n in keep:
|
|
continue
|
|
keep.append(n)
|
|
return keep
|
|
|
|
|
|
def fill_derived_entries(root: Path, asset: Asset) -> None:
|
|
if asset.deferred or asset.entries or asset.entry_prefix_counts:
|
|
return
|
|
asset.entries = derive_entries(root, asset)
|
|
asset.entries_derived = True
|
|
|
|
|
|
SYMBOLS_FILE = "crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/full_forward/symbols.rs"
|
|
|
|
|
|
def _symbols_text(root: Path) -> str:
|
|
"""The symbols table source: the module file and the child modules S12 split it into."""
|
|
base = root / SYMBOLS_FILE
|
|
parts = [base] + sorted((base.parent / base.stem).glob("*.rs"))
|
|
return chr(10).join(p.read_text(encoding="utf-8") for p in parts if p.is_file())
|
|
|
|
|
|
def symbols_entries(root: Path, ptx_name: str) -> List[str]:
|
|
"""Entry names the Rust side loads from `ptx_name` (mtp_original_full_symbols.rs table)."""
|
|
text = _symbols_text(root)
|
|
pattern = r'include_bytes!\("(?:\.\./)?' + re.escape(ptx_name) + r'"\)\s*,\s*&\[([^\]]*)\]'
|
|
m = re.search(pattern, text)
|
|
if not m:
|
|
raise PlanError(f"{ptx_name}: no entry table in {SYMBOLS_FILE}")
|
|
names = re.findall(r'c"([^"]+)"', m.group(1))
|
|
if not names:
|
|
raise PlanError(f"{ptx_name}: empty entry table in {SYMBOLS_FILE}")
|
|
return names
|
|
|
|
|
|
def fill_derived_entries(root: Path, asset: Asset) -> None: # noqa: F811 - supersedes the earlier definition
|
|
if asset.deferred or asset.entries or asset.entry_prefix_counts:
|
|
return
|
|
if asset.entries_from_symbols:
|
|
asset.entries = symbols_entries(root, asset.ptx_name)
|
|
return
|
|
asset.entries = derive_entries(root, asset)
|
|
asset.entries_derived = True
|
|
|
|
|
|
def apply_flag_overrides(assets: List[Asset], specs: List[str]) -> None:
|
|
"""Operator flag overrides, `ID:+FLAG` (add) / `ID:-FLAG` (remove); recorded on the asset.
|
|
|
|
The policy note is replaced because the plan's own note no longer describes the build; the fast-math lint
|
|
still rejects contradictory flag sets (--use_fast_math with --ftz=false/--prec-div=true/--prec-sqrt=true)."""
|
|
by_id = {a.id: a for a in assets}
|
|
for spec in specs:
|
|
m = re.fullmatch(r"([\w.\-]+):([+-])(-.+)", spec)
|
|
if not m:
|
|
raise PlanError(f"bad --flag-override {spec!r}; expected ID:+--flag or ID:---flag")
|
|
a = by_id.get(m.group(1))
|
|
if a is None:
|
|
raise PlanError(f"--flag-override: unknown asset {m.group(1)!r}")
|
|
flag = m.group(3)
|
|
if m.group(2) == "+":
|
|
if flag not in a.flags:
|
|
a.flags.append(flag)
|
|
else:
|
|
if flag not in a.flags:
|
|
raise PlanError(f"--flag-override {spec}: {a.id} does not have {flag}")
|
|
a.flags.remove(flag)
|
|
a.flag_overrides.append(spec)
|
|
a.policy = "operator flag override"
|
|
|
|
|
|
# ---------------------------------------------------------------------------------- PTX ISA / driver
|
|
|
|
# PTX ISA version -> minimum NVIDIA driver able to JIT it. 8.7 is CUDA 12.8 (R570); 9.0 is CUDA 13.0 (R580,
|
|
# GA 580.65.06, deploy/README.md). An unknown version is an error: extend this table, do not guess.
|
|
# 9.1/9.2: CUDA 13.1/13.2 minimum Linux drivers per the CUDA release notes (to be confirmed by a real module load on the host).
|
|
ISA_MIN_DRIVER = {"7.0": "450.80", "8.0": "525.60", "8.7": "570.26", "9.0": "580.65.06", "9.1": "590.44.01", "9.2": "595.45.04"}
|
|
|
|
|
|
def ptx_isa_version(data: bytes) -> Optional[str]:
|
|
m = re.search(rb"(?m)^\.version\s+(\d+\.\d+)", data[:8192])
|
|
return m.group(1).decode() if m else None
|
|
|
|
|
|
def isa_inventory(root: Path) -> Dict[str, List[str]]:
|
|
"""{ISA version: [ptx names]} over the real (non-placeholder) PTX in crates/cuda-driver/src."""
|
|
out: Dict[str, List[str]] = {}
|
|
for p in sorted((root / "crates/cuda-driver/src").glob("*.ptx")):
|
|
data = p.read_bytes()
|
|
if b"UNSEALED" in data[:4096] or b"PLACEHOLDER" in data[:4096]:
|
|
continue
|
|
v = ptx_isa_version(data)
|
|
if v:
|
|
out.setdefault(v, []).append(p.name)
|
|
return out
|
|
|
|
|
|
def version_tuple(v: str) -> Tuple[int, ...]:
|
|
return tuple(int(x) for x in re.findall(r"\d+", v))
|
|
|
|
|
|
def min_driver_for(isa_versions) -> Tuple[str, str]:
|
|
"""(highest ISA, minimum driver) for a set of ISA versions."""
|
|
versions = sorted(set(isa_versions), key=version_tuple)
|
|
if not versions:
|
|
raise PlanError("no PTX ISA versions given")
|
|
for v in versions:
|
|
if v not in ISA_MIN_DRIVER:
|
|
raise PlanError(f"unknown PTX ISA version {v}: add it to ISA_MIN_DRIVER with its minimum driver")
|
|
top = max(versions, key=lambda v: version_tuple(ISA_MIN_DRIVER[v]))
|
|
return top, ISA_MIN_DRIVER[top]
|
|
|
|
|
|
def driver_ok(driver: str, isa_versions) -> Tuple[bool, str]:
|
|
top, need = min_driver_for(isa_versions)
|
|
ok = version_tuple(driver) >= version_tuple(need)
|
|
return ok, (f"driver {driver} {'supports' if ok else 'is too old for'} PTX ISA {top} (needs >= {need})")
|