Files
leleka/scripts/gpu-bringup/reseal_own.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 f5a9b3bcf3 experimental ports: re-sync kv_q4, kv_q8, kv_stream and qsa_attn to Strata 41cf05a0, literal_port guard with named exclusions, stale-PTX gate
The 2026-10-25 upstream sync moved the Original kernels and the four experimental CUDA ports were not re-synced
(literal_port failed 4 of 6: 1, 5, 20 and 197 Original kernel-body lines missing).

* kv_stream: guarded shared atomicAdd; kv_q4: step_stride / planes; kv_q8: template <bool MULTI>; qsa_attn: attn_chunk_body with
  reduce12_gfx906 / reduce12_head_of_lane. Bodies are copied verbatim; the entries keep their ABI and instantiate the Original's
  single-token launch, so the sealed entry tables and the Rust facade are unchanged. The thread-emulation harness gives bitwise
  identical results on the previous and the re-synced sources (fwht, q4, q8, route, cvec, attention m2/m3/m4).
* tests/literal_port.rs: per-function bodies; a device function of the Original that the port does not carry (SM60-only gather,
  pre75 / merge_v2 / v3 / slot / row variants of the same arithmetic) is listed with its reason; the list is checked both ways, an
  unlisted new function or a stale entry fails; self-test of the guard.
* experimental.rs: the PTX is not rebuilt (no nvcc on this host), so PINS[..].source_sha256 of the four programs still names the
  previous source. admit() gains a source-seal gate (source_is_sealed) and PENDING_RESEAL lists the four programs: they refuse to
  open until the server reseals them, and a unit test keeps the list exact. The sealed PTX and their PTX digests are untouched.
* docs/cuda-seal-plan-additions-experimental.json: new cu_pin of the four sources. reseal_own.py: --plan, refreshes seal_sha256 /
  seal_length when the plan entry has them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 01:55:58 +01:00

84 lines
4.6 KiB
Python

#!/usr/bin/env python3
"""Re-seal one of OUR OWN already-sealed PTX assets (prefill_stage, qsa_late, ...) after its .cu changed.
seal_pins.py fills the pins of an unsealed placeholder and refuses an asset whose PTX is already pinned ("expected nowhere"), which is
the right default for the Original's assets. The assets that this repository compiles itself (extra-seal-plan.json, encoding
concat_include_str, a `PtxPin { source_sha256, ptx_sha256 }` in the Rust owner) are re-sealed by this tool: it takes the PTX that
`compile_assets.py --group G --out DIR` produced for the CURRENT .cu, writes it over the committed PTX, and patches the two pin fields
the plan names (`rust_fields_to_fill`) with the SHA-256 of the .cu bytes and of the PTX body. Nothing else changes.
reseal_own.py --ptx-dir DIR ASSET_ID [ASSET_ID ...] # dry run: prints what would change
reseal_own.py --ptx-dir DIR --write ASSET_ID [ASSET_ID ...]
`--plan docs/cuda-seal-plan-additions-experimental.json` names another plan file (default: extra-seal-plan.json). The six
experimental programs (`experimental_{kv_q4,kv_q8,kv_stream,keyless,qsa_attn,cvec}`, group `experimental`) live there; when the
plan entry has `seal_sha256` / `seal_length` slots they are refreshed too (text-level, formatting untouched).
The sm_86 companions and the generated table are rebuilt afterwards with `scripts/gpu-bringup/sm86_assets.py build` (docs/sm86-assets.md).
"""
import argparse
import json
import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import bringup_lib as L # noqa: E402
import rustpins as R # noqa: E402
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ptx-dir", required=True, type=Path)
ap.add_argument("--write", action="store_true")
ap.add_argument("--plan", default="scripts/gpu-bringup/extra-seal-plan.json", help="repo-relative seal plan holding the assets (default: extra-seal-plan.json)")
ap.add_argument("ids", nargs="+")
args = ap.parse_args()
root = L.REPO
plan_path = root / args.plan
plan = json.loads(plan_path.read_text(encoding="utf-8"))
by_id = {Path(a["cu"]).stem: a for a in plan["assets"]}
manifest = json.loads((args.ptx_dir / "build-manifest.json").read_text())
for asset_id in args.ids:
a = by_id[asset_id]
rec = next(r for r in manifest["assets"] if r["id"] == asset_id)
if rec["status"] != "ok" or rec.get("fake"):
sys.exit(f"{asset_id}: manifest status {rec['status']}")
raw = (args.ptx_dir / rec["ptx_file"]).read_bytes()
cu = (root / a["cu"]).read_bytes()
if L.sha256_hex(cu) != rec["cu_sha256"]:
sys.exit(f"{asset_id}: the .cu changed after the compile; compile again")
v = R.PinValues(len(raw), L.sha256_digest(raw), L.sha256_digest(cu))
for consumer, specs in a["rust_fields_to_fill"].items():
path = next(root.glob(f"crates/*/src/{consumer}"))
with open(path, encoding="utf-8", newline="") as fh: # (Path.read_text has no newline= before Python 3.13)
text = fh.read()
new = text
for spec in specs:
new = R.apply_field(new, spec, v)
print(f"{asset_id}: {path.relative_to(root)} {'patched' if new != text else 'unchanged'} (ptx {len(raw)} B sha {v.ptx_sha256.hex()[:16]}, cu sha {v.source_sha256.hex()[:16]})")
if args.write:
with open(path, "w", encoding="utf-8", newline="") as fh:
fh.write(new)
if "seal_sha256" in a and "seal_length" in a:
with open(plan_path, encoding="utf-8", newline="") as fh:
text = fh.read()
pat = re.compile(r'("ptx"\s*:\s*"' + re.escape(a["ptx"]) + r'"(?:(?!"cu"\s*:).)*?"seal_sha256"\s*:\s*)(null|"[0-9a-f]{64}")'
r'(\s*,\s*"seal_length"\s*:\s*)(null|\d+)', re.S)
ms = list(pat.finditer(text))
if len(ms) != 1:
sys.exit(f"{args.plan}: expected one seal_sha256/seal_length slot for {a['ptx']}, found {len(ms)}")
m = ms[0]
patched = text[: m.start(2)] + f'"{L.sha256_hex(raw)}"' + m.group(3) + str(len(raw)) + text[m.end(4):]
print(f"{asset_id}: {args.plan} seal_sha256/seal_length {'patched' if patched != text else 'unchanged'}")
if args.write:
with open(plan_path, "w", encoding="utf-8", newline="") as fh:
fh.write(patched)
if args.write:
(root / a["ptx"]).write_bytes(raw)
print(f"{asset_id}: wrote {a['ptx']}")
if __name__ == "__main__":
main()