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
CUDApp / tests / codegen_rest_check.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 3 | """CPU-only legacy/native-Omega differential and recompiled semantic controls.""" |
| 4 | import argparse |
| 5 | import concurrent.futures |
| 6 | import hashlib |
| 7 | import gzip |
| 8 | import json |
| 9 | import os |
| 10 | from pathlib import Path |
| 11 | import subprocess |
| 12 | import sys |
| 13 | import tempfile |
| 14 | |
| 15 | ROOT = Path(__file__).resolve().parents[1] |
| 16 | FAMILIES = ("attn256", "pattn256", "router", "gemm", "bf16", "qg") |
| 17 | EXPORTS = {'attn256': ['omega_dattn256_shape', 'omega_blackwell_codegen_decode_attn256_prog', 'omega_decode_attn256_prog_stats'], 'pattn256': ['omega_pattn256_shape', 'omega_pattn256_spec_ok', 'omega_blackwell_codegen_prefill_attn256_prog', 'omega_prefill_attn256_prog_stats'], 'router': ['omega_router_smem', 'omega_blackwell_codegen_router_prog', 'omega_router_prog_stats'], 'gemm': ['omega_fp8gemm_steps', 'omega_fp8gemm_shared_bytes', 'omega_blackwell_codegen_fp8gemm_prog', 'omega_fp8gemm_prog_stats'], 'bf16': ['omega_bf16_gemv_steps', 'omega_bf16_gemv_shared_bytes', 'omega_blackwell_codegen_bf16_gemv_prog', 'omega_bf16_gemv_prog_stats'], 'qg': ['omega_pq_spec_ok', 'omega_blackwell_codegen_pq_prog', 'omega_qg_spec_ok', 'omega_qg_shared_bytes', 'omega_qg_span', 'omega_blackwell_codegen_qgemm_prog']} |
| 18 | PIN = "2c82480596bbdc50cda9626866209ef662d5834f278f839ff4ce0250c495029f" |
| 19 | |
| 20 | |
| 21 | def main(): |
| 22 | parser = argparse.ArgumentParser(description=__doc__) |
| 23 | parser.add_argument("--smoke", action="store_true") |
| 24 | parser.add_argument("--mutants", action="store_true") |
| 25 | parser.add_argument("--coverage", action="store_true", help="instrument retained C oracles with -O0 --coverage and report gcov arcs") |
| 26 | parser.add_argument("--family", choices=FAMILIES, action="append") |
| 27 | parser.add_argument("--build-dir", type=Path) |
| 28 | args = parser.parse_args() |
| 29 | families = args.family or FAMILIES |
| 30 | omc = Path(os.environ.get("OMEGA_OMC", Path.home()/"work/cudastack/omega-mv/seed/out/omc")) |
| 31 | # Refuse when a node that reaches a GPU is visible: NVIDIA, aien-gpu, or a VFIO-bound group. The |
| 32 | # /dev/cuse and /dev/vfio/vfio control nodes of a hosted runner reach no device. |
| 33 | if (list(Path("/dev").glob("nvidia*")) or list(Path("/dev").glob("aien-gpu*")) |
| 34 | or [p for p in Path("/dev/vfio").glob("*") if p.name != "vfio"]): |
| 35 | raise SystemExit("FAIL run inside bwrap --dev-bind / / --dev /dev --proc /proc --") |
| 36 | bridge = Path(os.environ.get("OMEGA_BRIDGE", Path.home()/"work/cudastack/omega-bridge")) |
| 37 | # Only the Omega mutants execute the seeded compiler; the differential does not. |
| 38 | if args.mutants and hashlib.sha256(omc.read_bytes()).hexdigest() != PIN: |
| 39 | raise SystemExit("FAIL pinned seeded compiler SHA256") |
| 40 | scratch = tempfile.TemporaryDirectory(prefix="cudapp-codegen-rest-") |
| 41 | out = (args.build_dir or Path(scratch.name)).resolve() |
| 42 | out.mkdir(parents=True, exist_ok=True) |
| 43 | cc = os.environ.get("CC", "cc") |
| 44 | # Keep the independent allocator/matmul prerequisites without selecting the |
| 45 | # separate native NO_POSIX encoder ABI; this gate links the portable encoder. |
| 46 | flags = ["-D_GNU_SOURCE", "-DCUDAPP_MIGRATION_PENDING_C_REGALLOC=1", "-DCUDAPP_MIGRATION_PENDING_C_CODEGEN_MATMUL=1", "-DCUDAPP_MIGRATION_PENDING_C_PACK=1", "-std=gnu11", "-O1", "-ffp-contract=off", "-ffunction-sections", "-fdata-sections", "-I"+str(ROOT/"src")] |
| 47 | |
| 48 | def run(cmd, expected=0, stdout=None, cwd=ROOT): |
| 49 | r = subprocess.run([str(x) for x in cmd], cwd=cwd, text=True, stdout=stdout or subprocess.PIPE, stderr=subprocess.PIPE) |
| 50 | text = (r.stdout or "") + (r.stderr or "") |
| 51 | if r.returncode != expected: |
| 52 | print(text, file=sys.stderr) |
| 53 | raise RuntimeError("rc=%d command=%r" % (r.returncode, cmd)) |
| 54 | return text |
| 55 | |
| 56 | jobs = [] |
| 57 | for family in FAMILIES: |
| 58 | src = ROOT/"src"/("omega_blackwell_codegen_"+family+".c") |
| 59 | jobs.append((src, out/(family+".o"), [])) |
| 60 | defines = ["-DCUDAPP_MIGRATION_PENDING_C_CODEGEN_"+family.upper()+"=1"] |
| 61 | defines += ["-D"+name+"=legacy_"+name for name in EXPORTS[family]] |
| 62 | if family == "bf16": |
| 63 | defines.append("-Domega_blackwell_codegen_bf16_gemv=legacy_omega_blackwell_codegen_bf16_gemv") |
| 64 | jobs.append((src, out/(family+"-legacy.o"), defines)) |
| 65 | jobs.append((ROOT/"src"/("cudapp_om_cg_"+family+".c"), out/("cg_"+family+".o"), [])) |
| 66 | for name in ("omega_gpu_om_ir", "omega_blackwell_codegen", "cudapp_om_prefill_shape", "cudapp_om_prefill_order", "cudapp_om_bw_enc_sm121"): |
| 67 | jobs.append((ROOT/"src"/(name+".c"), out/(name+".o"), [])) |
| 68 | for source in os.environ["CODEGEN_REST_BINDING"].split(): |
| 69 | source = ROOT / source |
| 70 | jobs.append((source, out / (source.stem + ".o"), [])) |
| 71 | jobs.append((ROOT/"tests/gpu_codegen_rest_test.c", out/"test.o", [])) |
| 72 | |
| 73 | def compile(job): |
| 74 | source, obj, defines = job |
| 75 | if args.coverage and obj.name.endswith("-legacy.o"): |
| 76 | obj.with_suffix(".gcda").unlink(missing_ok=True) |
| 77 | defines = [*defines, "-O0", "--coverage"] |
| 78 | run([cc, *flags, *defines, "-c", source, "-o", obj]) |
| 79 | |
| 80 | with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool: |
| 81 | list(pool.map(compile, jobs)) |
| 82 | objects = [job[1] for job in jobs] |
| 83 | binary = out/"differential" |
| 84 | def link(target, override=None): |
| 85 | objs = [override[1] if override and obj.name==override[0] else obj for obj in objects] |
| 86 | run([cc, *objs, *(["--coverage"] if args.coverage else []), "-Wl,--gc-sections", "-o", target]) |
| 87 | link(binary) |
| 88 | for family in families: |
| 89 | print(run([binary, family, "--smoke" if args.smoke else "--full"]), end="", flush=True) |
| 90 | r = subprocess.run([str(binary), family, "--smoke", "--record-flip"], text=True, capture_output=True) |
| 91 | if r.returncode != 1 or "IR mismatch" not in r.stderr: |
| 92 | raise RuntimeError("FAIL record flip not detected: "+family+" "+r.stdout+r.stderr) |
| 93 | print("PASS record-flip caught "+family, flush=True) |
| 94 | if args.mutants: |
| 95 | common = (ROOT/"om/codegen/cg_rest_emit.om").read_text() |
| 96 | for family in families: |
| 97 | parts = [common] |
| 98 | if family=="qg": |
| 99 | parts += [(ROOT/"om/prefill-shape/admit.om").read_text(), (ROOT/"om/prefill-shape/order.om").read_text()] |
| 100 | parts += [(ROOT/"om/codegen"/("cg_"+family+".om")).read_text()] |
| 101 | source = "\n".join(parts) |
| 102 | mutants = [("fixed-stall", "cc = cw 6 7 7 wt", "cc = cw 5 7 7 wt")] |
| 103 | if family=="qg": |
| 104 | mutants.append(("ignore-meta6", "put m 6 ulong 246", "put m 6 ulong 0")) |
| 105 | for name, old, new in mutants: |
| 106 | if source.count(old)!=1: |
| 107 | raise RuntimeError("ambiguous mutant "+family+" "+name) |
| 108 | mutated = out/(family+"-"+name+".om") |
| 109 | mutated.write_text(source.replace(old,new)) |
| 110 | generated = out/(family+"-"+name+".c") |
| 111 | env = dict(os.environ, OMEGA_SEEDED_OMC=str(omc)) |
| 112 | with generated.open("w") as stream: |
| 113 | r = subprocess.run(["sh",str(bridge/"tools/bridge-seeded"),"c",str(mutated)], env=env, stdout=stream, stderr=subprocess.PIPE, text=True) |
| 114 | if r.returncode: |
| 115 | raise RuntimeError("mutant did not compile: "+r.stderr) |
| 116 | obj = generated.with_suffix(".o") |
| 117 | compile((generated,obj,[])) |
| 118 | mutantbin=out/(family+"-"+name) |
| 119 | link(mutantbin,("cg_"+family+".o",obj)) |
| 120 | r=subprocess.run([str(mutantbin),family,"--smoke"],text=True,capture_output=True) |
| 121 | if r.returncode!=1 or "mismatch" not in r.stderr: |
| 122 | raise RuntimeError("mutant survived: "+family+" "+name+" "+r.stdout+r.stderr) |
| 123 | print("PASS recompiled Omega mutant killed "+family+"/"+name+": "+r.stderr.splitlines()[0],flush=True) |
| 124 | if args.coverage: |
| 125 | reports = [] |
| 126 | for family in families: |
| 127 | obj = out/(family+"-legacy.gcno") |
| 128 | run(["gcov", "--json-format", "--branch-counts", "--branch-probabilities", obj], cwd=out) |
| 129 | packed = out/(family+"-legacy.gcov.json.gz") |
| 130 | report = json.loads(gzip.decompress(packed.read_bytes())) |
| 131 | source = ROOT/"src"/("omega_blackwell_codegen_"+family+".c") |
| 132 | data = next(item for item in report["files"] if Path(item["file"]).resolve()==source) |
| 133 | lines = data["lines"] |
| 134 | arcs = [arc for line in lines for arc in line.get("branches",[])] |
| 135 | entry = {"file":str(source.relative_to(ROOT)), "compiler":report["gcc_version"], |
| 136 | "lines_covered":sum(line["count"]>0 for line in lines), "lines_total":len(lines), |
| 137 | "branches_covered":sum(arc["count"]>0 for arc in arcs), "branches_total":len(arcs), |
| 138 | "uncovered":[{"line":line["line_number"], "function":line.get("function_name"), |
| 139 | "branches":[index for index,arc in enumerate(line.get("branches",[])) if not arc["count"]], |
| 140 | "line_covered":bool(line["count"])} |
| 141 | for line in lines if not line["count"] or any(not arc["count"] for arc in line.get("branches",[]))], |
| 142 | "data":data} |
| 143 | reports.append(entry) |
| 144 | print("COVERAGE %s lines=%d/%d branches=%d/%d" % (family,entry["lines_covered"],entry["lines_total"],entry["branches_covered"],entry["branches_total"]),flush=True) |
| 145 | (out/"coverage.json").write_text(json.dumps(reports,indent=2)+"\n") |
| 146 | print("PASS codegen-rest CPU-only differential controls") |
| 147 | |
| 148 | |
| 149 | if __name__ == "__main__": |
| 150 | try: |
| 151 | main() |
| 152 | except (RuntimeError, OSError) as error: |
| 153 | print(str(error), file=sys.stderr) |
| 154 | sys.exit(1) |