Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/patches/54e2fe69f81908ef # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/omega-mv#303 (code only) closed derived `54e2fe69f81908ef` #303 Imported from GitHub aien-dev/omega-mv#303 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `97ee27584cda0d8eaca136f31a44293cd36c9b02` · Head `787306d14cc91fc3115644c337cf9569f1cc5b19` ### Apply it ``` git checkout -b patch-54e2fe69f81908ef 97ee27584cda0d8eaca136f31a44293cd36c9b02 curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/54e2fe69f81908ef.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/omega-mv 303 787306d14cc91fc3115644c337cf9569f1cc5b19 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":303,"url":"https://github.com/aien-dev/omega-mv/pull/303","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:13Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index db35b28c6..a0d37e6d1 100644 --- a/.crumb +++ b/.crumb @@ -63,8 +63,8 @@ "purpose": "Directory doctrine. Purpose not yet described by a human." }, { - "digest": "7a280ae41e1051f14529ab2c8b2749f4712ea37df87254fd90bfbc3e1bba2048", - "last_commit": "38a6a56", + "digest": "bf8aa4246cf9b4a9d21e0a57856079a75bced3f53adefae2584b428f8afbd07a", + "last_commit": "48776cf", "name": "mk", "purpose": "Directory mk. Purpose not yet described by a human." }, @@ -82,13 +82,13 @@ }, { "digest": "eb9a304f3faddcdf298e4699bc99abc7fac1d6e2fc17f65a4472441e0ecf913d", - "last_commit": "f816473", + "last_commit": "97ee275", "name": "spec", "purpose": "Directory spec. Purpose not yet described by a human." }, { - "digest": "bf667679bc7c3494f148e83e9d8f56193a3768c2f7145a614a21e701e3bddabd", - "last_commit": "f816473", + "digest": "c4d0989f06c0bcfd0bd58edabdf147c0894d0882fa12ed69c55c0440302f46dd", + "last_commit": "0501183", "name": "src", "purpose": "Directory src. Purpose not yet described by a human." }, @@ -105,15 +105,15 @@ "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:ac4a3e4ceb344024aed3480e4850211366c39bbeb3687b15f87b21027045b9af", - "compiled_at": "2026-10-06T01:00:05Z", + "children_root": "sha256:c17c99ce3ffcc7e46c9b1a73693858ddfbc3f9ee7698a1a0094a93e6d55464b4", + "compiled_at": "2026-10-06T01:31:06Z", "compiler": "crumb-compile/1", - "digest": "sha256:2b2cc0d72983d8d22422970f56f16a04d4d14e6051570c765b63a485dd7687e0", + "digest": "sha256:4fb72698e3eaab51a105949921e75146a9ca8461a497c2c8af38c256942899f5", "evidence_files": 3304, "evidence_root": "sha256:9594e3e2a05603747e60ab08376dcf98a6857a89e43720f33126d5b68e41f4d1", - "files": 5115, - "generated_at_commit": "f816473df391bc4fbcf99df722edd70ed26ebef1", - "source_tree": "sha256:b272e31506181af78fdabadee7bed216ecc81e6665d0f49a67684eee9b60fbbc" + "files": 5127, + "generated_at_commit": "39f93e5e6dbb405fcbaa276f4fc41fd9700d683d", + "source_tree": "sha256:e29691d0c0196d99a8951ffccf0e69a27caf4d1c9bb158ce90ef35725d4847c0" }, "owner_lane": "", "provenance": { diff --git a/bench/prime_race/.crumb b/bench/prime_race/.crumb new file mode 100644 index 000000000..06b88e751 --- /dev/null +++ b/bench/prime_race/.crumb @@ -0,0 +1,22 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-10-05T18:58:51Z", + "compiler": "crumb-compile/1", + "digest": "sha256:e6b80bc9b9e80320eb4e25bd113c090767e5d28c2313a306f71baddf3ca856e0", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 10, + "generated_at_commit": "dc7a3d7a8c1997a0821c098fb862107d3fd54b9d", + "source_tree": "sha256:51cf8e4ff02a60a62394389bff2fe8d91cb2c936c5d2f5f418f7d91e28a10064" + } + }, + "invariants": [ + "canonical bitmap format is the contract; never reuse previous pass results; no CUDA symbols in AIEN binaries" + ], + "name": "bench/prime_race", + "purpose": "AIEN Prime Drag Race implementation side: the shared protocol helper (command line, timed loop, report, canonical bitmap export) and the conventional CPU baseline sieve that other entries are checked and compared against", + "schema_version": "1.0.0" +} diff --git a/bench/prime_race/README.md b/bench/prime_race/README.md new file mode 100644 index 000000000..b5fe80388 --- /dev/null +++ b/bench/prime_race/README.md @@ -0,0 +1,47 @@ +# AIEN Prime Drag Race: implementation side + +This folder holds the code every Prime Drag Race entry is built on. The Drag Race is a benchmark where +each entry sieves for prime numbers as many times as it can in a fixed time, and the runner checks every +answer before any speed is believed. + +What is here: + +- `prime_race_impl.h` and `prime_race_impl.c`: the shared protocol. It reads the command line, runs the + timed loop, writes the report file and the one-line result. Every entry uses this one copy. +- `cpu_base.c`: the plain, conventional CPU sieve (one thread, one bit per odd number, built the way the + upstream "base" rules describe). It is the yardstick the faster entries are compared to. +- `tests/prime_race_host_test.c`: checks cpu_base against a slow, independent trial-division oracle for + every limit from 0 to 3000, the design limit list up to 2,000,000, and known prime counts. + +## Build and run + +From the repository root: + + make prime-race-cpu + ./bench/prime_race/build/cpu_base --limit 1000000 --min-seconds 5 + + make prime-race-host-test + +Options: `--limit N` (default 1000000, at most 2^40), `--min-seconds S` (default 5), `--bitmap-out PATH`, +`--report-out PATH`, `--audit-passes K`. Exit code 0 is success, 2 is an execution failure (no result +line is printed), 64 is a usage mistake. Audit mode runs K passes and saves each pass's answer so the +runner can prove every pass really recomputed; it prints no result line because it makes no timing claim. + +## The result line and the labels + +On success the program prints one line in the upstream format: + + aien-;;;;algorithm=..,faithful=..,bits=.. + +The labels say honestly what the entry does. `cpu_base` is `algorithm=base`, `faithful=yes` (it builds a +fresh sieve each pass, like upstream), `bits=1`, one thread. + +The line is upstream compatible, but the entry is NONCONFORMING for upstream submission (different +license and not an upstream language), so results are kept as AIEN receipts, not submitted upstream. + +## The answer format + +The canonical answer is the contract: bit k of the output is set exactly when 2k+1 is prime. The number 2 +is implied. Unused bits at the end are zero. A previous pass's result is never reused. + +The full contract will live in the aien-dev/benchmarks repository once it exists (link to be added). diff --git a/bench/prime_race/cpu_base.c b/bench/prime_race/cpu_base.c new file mode 100644 index 000000000..605cd3a4e --- /dev/null +++ b/bench/prime_race/cpu_base.c @@ -0,0 +1,112 @@ +/* aien-cpu-c-base: conventional single-thread CPU sieve following the upstream "base" rules. + * Faithful: a struct holds the whole state, one calloc per pass sized to the limit, odd factors searched + * sequentially from 3 up to sqrt(limit), every multiple cleared individually starting at factor*factor. + * Storage: 1 bit per odd number, bit k <-> number 2k+1, inverted (set = composite). Stepping 2*factor in + * number space is stepping `factor` in odd-index space. */ +#include "prime_race_impl.h" + +#include +#include + +typedef struct cpu_sieve { + uint64_t limit; + uint64_t *composite; /* set bit = composite, indexed by (n-1)/2 */ + size_t nwords; +} cpu_sieve; + +static uint64_t isqrt_u64(uint64_t n) { + uint64_t r = 0; + uint64_t lo = 0, hi = 1ULL << 21; /* sqrt(2^40) = 2^20 < hi */ + while (lo <= hi) { + uint64_t mid = lo + (hi - lo) / 2; + if (mid * mid <= n) { r = mid; lo = mid + 1; } + else hi = mid - 1; + } + return r; +} + +static inline int is_comp(const cpu_sieve *s, uint64_t n) { return (int)((s->composite[(n - 1) / 2 / 64] >> (((n - 1) / 2) % 64)) & 1u); } +static inline void mark_comp(cpu_sieve *s, uint64_t n) { s->composite[(n - 1) / 2 / 64] |= 1ULL << (((n - 1) / 2) % 64); } + +static void sieve_destroy(cpu_sieve *s) { + free(s->composite); + s->composite = NULL; + s->nwords = 0; +} + +static int sieve_create(cpu_sieve *s, uint64_t limit) { + s->limit = limit; + s->nwords = pr_words64(limit); + s->composite = (uint64_t *)calloc(s->nwords ? s->nwords : 1, sizeof(uint64_t)); + return s->composite ? 0 : -1; +} + +static void sieve_run(cpu_sieve *s) { + const uint64_t limit = s->limit; + const uint64_t q = isqrt_u64(limit); + uint64_t factor = 3; + while (factor <= q) { + /* next unmarked odd number at or above factor */ + for (uint64_t n = factor; n <= limit; n += 2) { + if (!is_comp(s, n)) { factor = n; break; } + } + for (uint64_t num = factor * factor; num <= limit; num += factor * 2) mark_comp(s, num); + factor += 2; + } +} + +static int cpu_setup(void **state, uint64_t limit) { + (void)limit; + cpu_sieve *s = (cpu_sieve *)calloc(1, sizeof *s); + if (!s) return -1; + *state = s; + return 0; +} + +static int cpu_pass(void *state, uint64_t limit) { + cpu_sieve *s = (cpu_sieve *)state; + sieve_destroy(s); /* previous pass's sieve is destroyed inside the timed pass */ + if (sieve_create(s, limit) != 0) return -1; + sieve_run(s); + return 0; +} + +static int cpu_export(void *state, uint64_t limit, uint64_t *out) { + cpu_sieve *s = (cpu_sieve *)state; + if (!s->composite || s->limit != limit) return -1; + const size_t nw = pr_words64(limit); + const uint64_t odd = pr_odd_count(limit); + for (size_t w = 0; w < nw; w++) out[w] = ~s->composite[w]; + if (nw) { + out[0] &= ~1ULL; /* number 1 is not prime */ + if (odd % 64) out[nw - 1] &= (1ULL << (odd % 64)) - 1; /* tail bits zero */ + } + return 0; +} + +static uint64_t cpu_threads(void *state) { (void)state; return 1; } + +static void cpu_teardown(void *state) { + cpu_sieve *s = (cpu_sieve *)state; + if (!s) return; + sieve_destroy(s); + free(s); +} + +const pr_impl pr_cpu_base_impl = { + .name = "cpu-c-base", + .algorithm = "base", + .faithful = "yes", + .bits = 1, + .environment = "linux-host-cpu", + .setup = cpu_setup, + .pass = cpu_pass, + .export_bitmap = cpu_export, + .threads = cpu_threads, + .detail_json = NULL, + .teardown = cpu_teardown, +}; + +#ifndef PR_NO_MAIN +int main(int argc, char **argv) { return pr_main(argc, argv, &pr_cpu_base_impl); } +#endif diff --git a/bench/prime_race/gb10_native.c b/bench/prime_race/gb10_native.c new file mode 100644 index 000000000..a54484f78 --- /dev/null +++ b/bench/prime_race/gb10_native.c @@ -0,0 +1,201 @@ +/* AIEN Prime Drag Race: native GB10 implementation (no CUDA). + * + * Kernel: gen_prime_sieve in src/omega_gpu_elementwise_api.c (Omega's own Blackwell + * codegen; word-parallel odd-only sieve, one writer per 32-bit word, no atomics). + * Launch: the process-wide session (src/omega_gpu_session.h): shader-cache invalidate, + * constant bank, QMD, marker 1, L2_FLUSH_DIRTY, marker 2 on uncached memory; every + * buffer here is GPU-uncached (session rule), so host writes and host reads need no + * extra flush beyond the dsb before the launch. + * + * One-time setup (untimed): session lock + open, kernel codegen + upload, persistent + * output / prime-table buffers sized for the limit. + * Pass (timed): reset the output words (poison), host sieve of the odd base primes + * <= isqrt(limit) with their division magics written straight into the device-visible + * table, one launch (<= OMEGA_GPU_EW_MAX_CTAS CTAs, grid-stride over words), wait for + * both markers. Persistent buffers => faithful=no. + * + * Labels (handoff 2026-10-05 DESIGN): algorithm=other, faithful=no, bits=1, + * environment linux-hosted-gb10-native. Build with -DPR_GB10_MUTANT=1 only for the chip + * test's negative control (the r == 0 fix is dropped; the oracle must catch it). + */ +#include "prime_race_impl.h" +#include "omega_gpu_elementwise_api.h" +#include "omega_gpu_session.h" +#include "omega_blackwell_qmd.h" /* OMEGA_BW_CBANK_MATMUL_ARGS_WORDS */ +#include +#include +#include +#include + +#ifndef PR_GB10_MUTANT +#define PR_GB10_MUTANT 0 +#endif + +#define GB_THREADS OMEGA_GPU_EW_THREADS +#define GB_MAX_CTAS OMEGA_GPU_EW_MAX_CTAS +#define GB_GPR 64u /* the QMD register count the elementwise launcher uses */ +#define GB_WAIT_MS 600000ull /* same marker wait as the elementwise launcher (omega#198) */ +#define GB_POISON 0xffbadbadu +#define GB_MAX_LIMIT 0xffffffffull /* kernel range: base, k0 < 2^31 */ + +typedef struct { + uint64_t limit, odd; + uint32_t nwords, ctas, stride, lastw, tailinv; + uint32_t root; /* isqrt(limit) */ + uint32_t nprimes; /* odd primes in the table of the last pass (sentinel excluded) */ + size_t table_cap; /* entries, sentinel included */ + OmegaBlackwellKernel k; + NvrmMem code, out, table; + uint64_t diag_ns, launches; + int locked, opened; +} gb_state; + +/* floor(sqrt(n)). The root of any u64 is below 2^32, so the top trial bit is 2^31: with that start + * (r + bit) <= 2^32 - 1 and its square cannot wrap. (A 2^32 start squared to 2^64 = 0 on the first + * step and returned 0 for every n, so no base primes were ever sieved; caught on chip at limit 9.) */ +static uint32_t isqrt_u64(uint64_t n) { + uint64_t r = 0; + for (uint64_t bit = 1ull << 31; bit; bit >>= 1) + if ((r + bit) * (r + bit) <= n) r += bit; + return (uint32_t)r; +} + +static void gb_release(gb_state *s) { + if (s->locked) { + omega_gpu_session_free(&s->table); + omega_gpu_session_free(&s->out); + omega_gpu_session_free(&s->code); + omega_gpu_session_unlock(); + s->locked = 0; + } + if (s->opened) { omega_gpu_session_close(); s->opened = 0; } /* refused (no-op) after a latch */ + free(s->k.code); s->k.code = NULL; +} + +static int gb_setup(void **state, uint64_t limit) { + if (limit > GB_MAX_LIMIT) { fprintf(stderr, "gb10-native: limit %" PRIu64 " above %llu\n", limit, GB_MAX_LIMIT); return -1; } + gb_state *s = calloc(1, sizeof *s); + if (!s) return -1; + *state = s; + s->limit = limit; + s->odd = pr_odd_count(limit); + s->nwords = (uint32_t)((s->odd + 31) / 32); + uint32_t blocks = (s->nwords + GB_THREADS - 1) / GB_THREADS; + s->ctas = blocks == 0 ? 1 : (blocks > GB_MAX_CTAS ? GB_MAX_CTAS : blocks); + s->stride = s->ctas * GB_THREADS; + s->lastw = s->nwords ? s->nwords - 1 : 0; + uint32_t valid = s->nwords ? (uint32_t)(s->odd - 32ull * s->lastw) : 32; /* 1..32 */ + uint32_t tailmask = valid >= 32 ? 0xffffffffu : ((1u << valid) - 1u); + s->tailinv = ~tailmask; + s->root = isqrt_u64(limit); + if ((uint64_t)s->root * s->root > limit || ((uint64_t)s->root + 1) * ((uint64_t)s->root + 1) <= limit) { + fprintf(stderr, "gb10-native: isqrt(%" PRIu64 ") = %u is wrong\n", limit, s->root); return -1; /* fail closed */ + } + s->table_cap = (size_t)s->root / 2 + 2; /* every odd number <= root, plus the sentinel */ + + if (omega_gpu_elementwise_codegen_ir(OMEGA_GPU_EW_PRIME_SIEVE, PR_GB10_MUTANT, NULL, &s->k) != OMEGA_GPU_EW_OK) { + fprintf(stderr, "gb10-native: kernel codegen failed\n"); return -1; + } + omega_gpu_session_lock(); + s->locked = 1; + if (!omega_gpu_session_open()) { fprintf(stderr, "gb10-native: session open failed: %s\n", omega_gpu_session_last_error()); return -1; } + s->opened = 1; + size_t out_bytes = (size_t)(s->nwords ? s->nwords : 1) * 4; + if (omega_gpu_session_alloc(s->k.code_size, &s->code) != 0 || + omega_gpu_session_alloc(out_bytes, &s->out) != 0 || + omega_gpu_session_alloc(s->table_cap * 12, &s->table) != 0) { + fprintf(stderr, "gb10-native: alloc failed: %s\n", omega_gpu_session_last_error()); return -1; + } + memcpy(s->code.cpu, s->k.code, s->k.code_size); + __asm__ volatile("dsb sy" ::: "memory"); + return 0; +} + +static int gb_pass(void *state, uint64_t limit) { + gb_state *s = state; + if (!s || limit != s->limit || omega_gpu_session_is_blocked()) return -1; + /* reset the sieve state: every output word poisoned, the kernel must overwrite all */ + uint32_t *out = s->out.cpu; + for (uint32_t i = 0; i < s->nwords; i++) out[i] = GB_POISON; + /* odd base primes <= isqrt(limit): flags[i] marks 2i+1 composite */ + uint32_t half = s->root / 2 + 1; + uint8_t *flags = calloc(half, 1); + if (!flags) return -1; + uint32_t *tab = s->table.cpu, n = 0; + for (uint32_t i = 1; i < half; i++) { + uint32_t p = 2 * i + 1; + if (p > s->root) break; + if (flags[i]) continue; + for (uint64_t c = (uint64_t)p * p; c <= s->root; c += 2ull * p) flags[c / 2] = 1; + tab[3 * n + 0] = p; + tab[3 * n + 1] = (uint32_t)(((1ull << 32) + p - 1) / p); /* ceil(2^32 / p) */ + tab[3 * n + 2] = (uint32_t)(((uint64_t)p * p - 1) / 2); + n++; + } + free(flags); + tab[3 * n + 0] = 1; tab[3 * n + 1] = 0; tab[3 * n + 2] = 0xffffffffu; /* sentinel: ends every scan */ + s->nprimes = n; + __asm__ volatile("dsb sy" ::: "memory"); + + uint32_t args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS] = {0}; + args[0] = (uint32_t)s->table.va; args[1] = (uint32_t)(s->table.va >> 32); + args[4] = (uint32_t)s->out.va; args[5] = (uint32_t)(s->out.va >> 32); + args[6] = s->nwords; args[7] = s->stride; args[8] = s->lastw; args[9] = s->tailinv; + OmegaGpuLaunch L = { + .code_va = s->code.va, .gpr_count = GB_GPR, .threads_x = GB_THREADS, .threads_y = 1, + .grid_x = s->ctas, .grid_y = 1, .num_elements = s->nwords ? s->nwords : 1, + .args = args, .n_args = OMEGA_BW_CBANK_MATMUL_ARGS_WORDS, .timeout_ms = GB_WAIT_MS, + }; + uint64_t ns = 0; uint32_t marker = 0; + if (omega_gpu_session_launch(&L, &ns, &marker) != 0) { + fprintf(stderr, "gb10-native: launch failed: %s\n", omega_gpu_session_last_error()); + return -1; + } + s->diag_ns += ns; + s->launches++; + return 0; +} + +static int gb_export(void *state, uint64_t limit, uint64_t *words) { + gb_state *s = state; + if (!s || limit != s->limit) return -1; + size_t bytes64 = pr_words64(limit) * 8, bytes32 = (size_t)s->nwords * 4; + if (bytes32 > bytes64) return -1; + memcpy(words, s->out.cpu, bytes32); + memset((uint8_t *)words + bytes32, 0, bytes64 - bytes32); + return 0; +} + +static uint64_t gb_threads(void *state) { gb_state *s = state; return s ? s->stride : 0; } + +static int gb_detail(void *state, FILE *f) { + gb_state *s = state; + if (!s) return -1; + fprintf(f, "{\"grid\": %u, \"block\": %u, \"words\": %u, \"nprimes\": %u, \"kernel_code_sha256\": \"", + s->ctas, GB_THREADS, s->nwords, s->nprimes); + for (int i = 0; i < 32; i++) fprintf(f, "%02x", s->k.code_digest[i]); + fprintf(f, "\", \"kernel_insns\": %zu, \"kernel_gpr\": %u, \"mutant\": %d, \"launches\": %" PRIu64 + ", \"diag_kernel_ns_total\": %" PRIu64 + ", \"diag_note\": \"sum of session elapsed_ns (submit to second marker), diagnostic only\"}", + s->k.insn_count, s->k.gpr_count, PR_GB10_MUTANT, s->launches, s->diag_ns); + return ferror(f) ? -1 : 0; +} + +static void gb_teardown(void *state) { + gb_state *s = state; + if (!s) return; + gb_release(s); + free(s); +} + +static const pr_impl GB10_NATIVE = { + .name = PR_GB10_MUTANT ? "gb10-native-mutant" : "gb10-native", + .algorithm = "other", .faithful = "no", .bits = 1, + .environment = "linux-hosted-gb10-native", + .setup = gb_setup, .pass = gb_pass, .export_bitmap = gb_export, + .threads = gb_threads, .detail_json = gb_detail, .teardown = gb_teardown, +}; + +#ifndef PR_NO_MAIN +int main(int argc, char **argv) { return pr_main(argc, argv, &GB10_NATIVE); } +#endif diff --git a/bench/prime_race/prime_race_impl.c b/bench/prime_race/prime_race_impl.c new file mode 100644 index 000000000..34e94765a --- /dev/null +++ b/bench/prime_race/prime_race_impl.c @@ -0,0 +1,276 @@ +/* AIEN Prime Drag Race: implementation-side protocol. See prime_race_impl.h and bench/prime_race/README.md. */ +#include "prime_race_impl.h" + +#include +#include +#include +#include +#include + +#ifndef PR_SOURCE_COMMIT +#define PR_SOURCE_COMMIT "unknown" +#endif +#ifndef PR_CC +#define PR_CC "unknown" +#endif +#ifndef PR_CFLAGS +#define PR_CFLAGS "unknown" +#endif + +static void set_err(char *err, size_t n, const char *fmt, const char *a) { + if (err && n) snprintf(err, n, fmt, a ? a : ""); +} + +static int parse_u64(const char *s, uint64_t *out) { + char *end = NULL; + if (!s || s[0] < '0' || s[0] > '9') return -1; /* rejects empty, sign, space */ + errno = 0; + unsigned long long v = strtoull(s, &end, 10); + if (errno != 0 || end == s || *end != '\0') return -1; + *out = (uint64_t)v; + return 0; +} + +static int parse_seconds(const char *s, double *out) { + char *end = NULL; + if (!s || !((s[0] >= '0' && s[0] <= '9') || s[0] == '.')) return -1; /* rejects nan/inf/sign */ + errno = 0; + double v = strtod(s, &end); + if (errno != 0 || end == s || *end != '\0' || !isfinite(v) || v < 0.0) return -1; + *out = v; + return 0; +} + +int pr_parse_args(int argc, char **argv, pr_args *a, char *err, size_t errn) { + a->limit = 1000000; + a->min_seconds = 5.0; + a->bitmap_out = NULL; + a->report_out = NULL; + a->audit_passes = 0; + int audit_given = 0; + for (int i = 1; i < argc; i++) { + const char *opt = argv[i]; + const char *val = (i + 1 < argc) ? argv[i + 1] : NULL; + if (strcmp(opt, "--limit") == 0 || strcmp(opt, "--min-seconds") == 0 || strcmp(opt, "--bitmap-out") == 0 || + strcmp(opt, "--report-out") == 0 || strcmp(opt, "--audit-passes") == 0) { + if (!val) { set_err(err, errn, "missing value for %s", opt); return -1; } + i++; + if (strcmp(opt, "--limit") == 0) { + if (parse_u64(val, &a->limit) != 0) { set_err(err, errn, "invalid --limit '%s'", val); return -1; } + if (a->limit > PR_MAX_LIMIT) { set_err(err, errn, "--limit '%s' exceeds 2^40", val); return -1; } + } else if (strcmp(opt, "--min-seconds") == 0) { + if (parse_seconds(val, &a->min_seconds) != 0) { set_err(err, errn, "invalid --min-seconds '%s'", val); return -1; } + } else if (strcmp(opt, "--audit-passes") == 0) { + if (parse_u64(val, &a->audit_passes) != 0 || a->audit_passes == 0) { + set_err(err, errn, "invalid --audit-passes '%s' (need integer >= 1)", val); + return -1; + } + audit_given = 1; + } else if (strcmp(opt, "--bitmap-out") == 0) { + if (val[0] == '\0') { set_err(err, errn, "empty %s", opt); return -1; } + a->bitmap_out = val; + } else { + if (val[0] == '\0') { set_err(err, errn, "empty %s", opt); return -1; } + a->report_out = val; + } + } else { + set_err(err, errn, "unknown argument '%s'", opt); + return -1; + } + } + if (audit_given && !a->bitmap_out) { + set_err(err, errn, "%s", "--audit-passes requires --bitmap-out"); + return -1; + } + return 0; +} + +int pr_format_line(char *buf, size_t n, const pr_impl *impl, uint64_t passes, double elapsed_s, uint64_t threads) { + int w = snprintf(buf, n, "aien-%s;%llu;%.6f;%llu;algorithm=%s,faithful=%s,bits=%d", impl->name, + (unsigned long long)passes, elapsed_s, (unsigned long long)threads, impl->algorithm, + impl->faithful, impl->bits); + if (w < 0 || (size_t)w >= n) return -1; + return w; +} + +int pr_line_allowed(int failed, uint64_t passes, double elapsed_s, double min_seconds) { + if (failed) return 0; + if (passes == 0) return 0; + if (!isfinite(elapsed_s) || elapsed_s < min_seconds) return 0; + return 1; +} + +void pr_json_string(FILE *f, const char *s) { + fputc('"', f); + for (const unsigned char *p = (const unsigned char *)(s ? s : ""); *p; p++) { + switch (*p) { + case '"': fputs("\\\"", f); break; + case '\\': fputs("\\\\", f); break; + case '\n': fputs("\\n", f); break; + case '\r': fputs("\\r", f); break; + case '\t': fputs("\\t", f); break; + default: + if (*p < 0x20) fprintf(f, "\\u%04x", (unsigned)*p); + else fputc(*p, f); + } + } + fputc('"', f); +} + +int pr_write_report(FILE *f, const pr_report *r) { + const pr_impl *im = r->impl; + char label[256]; + snprintf(label, sizeof label, "aien-%s", im->name); + fputs("{\n \"schema\": \"aien-prime-race/impl-report/v1\",\n \"impl\": ", f); + pr_json_string(f, im->name); + fputs(",\n \"label\": ", f); + pr_json_string(f, label); + fputs(",\n \"algorithm\": ", f); + pr_json_string(f, im->algorithm); + fputs(",\n \"faithful\": ", f); + pr_json_string(f, im->faithful); + fprintf(f, ",\n \"bits\": %d,\n \"threads\": %llu,\n \"environment\": ", im->bits, (unsigned long long)r->threads); + pr_json_string(f, im->environment); + fprintf(f, ",\n \"limit\": %llu,\n \"min_seconds\": %.6f,\n \"mode\": ", (unsigned long long)r->limit, r->min_seconds); + pr_json_string(f, r->mode); + fprintf(f, ",\n \"passes\": %llu,\n \"elapsed_s\": %.6f,\n \"status\": ", (unsigned long long)r->passes, r->elapsed_s); + pr_json_string(f, r->status); + fputs(",\n \"error\": ", f); + if (r->error) pr_json_string(f, r->error); else fputs("null", f); + fputs(",\n \"build\": {\"source_commit\": ", f); + pr_json_string(f, PR_SOURCE_COMMIT); + fputs(", \"cc\": ", f); + pr_json_string(f, PR_CC); + fputs(", \"cflags\": ", f); + pr_json_string(f, PR_CFLAGS); + fputs("},\n \"detail\": ", f); + if (im->detail_json && r->state) { + if (im->detail_json(r->state, f) != 0) fputs("null", f); + } else { + fputs("{}", f); + } + fputs("\n}\n", f); + fflush(f); + return ferror(f) ? -1 : 0; +} + +static int64_t now_ns(void) { + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return -1; + return (int64_t)ts.tv_sec * 1000000000LL + (int64_t)ts.tv_nsec; +} + +static int write_words(FILE *f, const uint64_t *w, size_t n) { + return (n == 0 || fwrite(w, sizeof(uint64_t), n, f) == n) ? 0 : -1; +} + +int pr_main(int argc, char **argv, const pr_impl *impl) { + pr_args a; + char err[256] = ""; + if (pr_parse_args(argc, argv, &a, err, sizeof err) != 0) { + fprintf(stderr, "usage error: %s\n", err); + fprintf(stderr, "usage: %s [--limit N=1000000] [--min-seconds S=5] [--bitmap-out PATH] " + "[--report-out PATH] [--audit-passes K]\n", argc > 0 ? argv[0] : "impl"); + return 64; + } + + const int audit = a.audit_passes > 0; + char error[256] = ""; + int failed = 0; + uint64_t passes = 0; + double elapsed = 0.0; + void *st = NULL; + int have_state = 0; + uint64_t *words = NULL; + FILE *bf = NULL; + const size_t nw = pr_words64(a.limit); + + words = (uint64_t *)calloc(nw ? nw : 1, sizeof(uint64_t)); + if (!words) { failed = 1; snprintf(error, sizeof error, "cannot allocate export buffer"); goto report; } + if (impl->setup(&st, a.limit) != 0) { failed = 1; snprintf(error, sizeof error, "setup failed"); goto report; } + have_state = 1; + if (a.bitmap_out && audit) { + bf = fopen(a.bitmap_out, "wb"); + if (!bf) { failed = 1; snprintf(error, sizeof error, "cannot open bitmap-out"); goto report; } + } + + if (audit) { + for (uint64_t k = 0; k < a.audit_passes; k++) { + if (impl->pass(st, a.limit) != 0) { failed = 1; snprintf(error, sizeof error, "pass %llu failed", (unsigned long long)k); break; } + passes++; + if (impl->export_bitmap(st, a.limit, words) != 0) { failed = 1; snprintf(error, sizeof error, "export failed on pass %llu", (unsigned long long)k); break; } + if (write_words(bf, words, nw) != 0 || fflush(bf) != 0) { failed = 1; snprintf(error, sizeof error, "bitmap write failed"); break; } + } + } else { + int64_t t0 = now_ns(), t1 = t0; + if (t0 < 0) { failed = 1; snprintf(error, sizeof error, "clock failure"); goto report; } + for (;;) { + if (impl->pass(st, a.limit) != 0) { failed = 1; snprintf(error, sizeof error, "pass %llu failed", (unsigned long long)passes); break; } + passes++; + t1 = now_ns(); + if (t1 < 0) { failed = 1; snprintf(error, sizeof error, "clock failure"); break; } + if ((double)(t1 - t0) / 1e9 >= a.min_seconds) break; + } + elapsed = (double)(t1 - t0) / 1e9; + if (!failed && a.bitmap_out) { + /* untimed export of the final pass */ + FILE *of = fopen(a.bitmap_out, "wb"); + if (!of) { failed = 1; snprintf(error, sizeof error, "cannot open bitmap-out"); } + else { + if (impl->export_bitmap(st, a.limit, words) != 0) { failed = 1; snprintf(error, sizeof error, "export failed"); } + else if (write_words(of, words, nw) != 0) { failed = 1; snprintf(error, sizeof error, "bitmap write failed"); } + if (fclose(of) != 0 && !failed) { failed = 1; snprintf(error, sizeof error, "bitmap close failed"); } + } + } + } + if (bf) { + if (fclose(bf) != 0 && !failed) { failed = 1; snprintf(error, sizeof error, "bitmap close failed"); } + bf = NULL; + } + if (!failed && !audit && !pr_line_allowed(0, passes, elapsed, a.min_seconds)) { + failed = 1; + snprintf(error, sizeof error, "timed run did not satisfy passes>0 and elapsed>=min_seconds"); + } + if (!failed && audit && passes != a.audit_passes) { failed = 1; snprintf(error, sizeof error, "audit pass count mismatch"); } + +report:; + if (bf) fclose(bf); + pr_report rep; + memset(&rep, 0, sizeof rep); + rep.impl = impl; + rep.state = have_state ? st : NULL; + rep.threads = have_state && impl->threads ? impl->threads(st) : 0; + rep.limit = a.limit; + rep.min_seconds = a.min_seconds; + rep.mode = audit ? "audit" : "timed"; + rep.passes = passes; + rep.elapsed_s = elapsed; + rep.status = failed ? "EXEC_FAILED" : "COMPLETE"; + rep.error = failed ? error : NULL; + + if (a.report_out) { + FILE *rf = fopen(a.report_out, "w"); + if (!rf || pr_write_report(rf, &rep) != 0 || fclose(rf) != 0) { + fprintf(stderr, "cannot write report to %s\n", a.report_out); + if (!failed) { failed = 1; snprintf(error, sizeof error, "report write failed"); } + } + } + uint64_t threads = rep.threads; + if (have_state && impl->teardown) impl->teardown(st); + free(words); + + if (failed) { + fprintf(stderr, "EXEC_FAILED: %s\n", error); + return 2; + } + if (!audit) { /* audit mode makes no timing claims: no upstream line */ + char line[512]; + if (pr_format_line(line, sizeof line, impl, passes, elapsed, threads) < 0) { + fprintf(stderr, "EXEC_FAILED: line too long\n"); + return 2; + } + printf("%s\n", line); + fflush(stdout); + } + return 0; +} diff --git a/bench/prime_race/prime_race_impl.h b/bench/prime_race/prime_race_impl.h new file mode 100644 index 000000000..110d66737 --- /dev/null +++ b/bench/prime_race/prime_race_impl.h @@ -0,0 +1,72 @@ +/* AIEN Prime Drag Race: implementation-side protocol (one copy for every C/CUDA implementation). + * Contract: canonical bitmap, bit k (u64 word k/64, bit k%64) set iff 2k+1 is prime, 0 <= k < (limit+1)/2, + * tail bits zero; prime 2 is implicit when limit >= 2. */ +#ifndef PRIME_RACE_IMPL_H +#define PRIME_RACE_IMPL_H + +#include +#include +#include + +typedef struct pr_impl { + const char *name; /* e.g. "cpu-c-base"; label printed as "aien-" */ + const char *algorithm; /* base|wheel|other */ + const char *faithful; /* yes|no */ + int bits; /* storage bits per flag */ + const char *environment; /* linux-host-cpu | linux-hosted-gb10-native | linux-hosted-gb10-cuda */ + int (*setup)(void **state, uint64_t limit); /* untimed one-time setup, 0 = ok */ + int (*pass)(void *state, uint64_t limit); /* timed: fresh sieve from scratch, complete, host-readable; 0 = ok */ + int (*export_bitmap)(void *state, uint64_t limit, uint64_t *out); /* canonical words of last pass, 0 = ok */ + uint64_t (*threads)(void *state); /* threads that ran the sieve in last pass */ + int (*detail_json)(void *state, FILE *f); /* optional (may be NULL): writes one JSON object */ + void (*teardown)(void *state); +} pr_impl; + +static inline uint64_t pr_odd_count(uint64_t limit) { return (limit + 1) / 2; } +static inline size_t pr_words64(uint64_t limit) { return (size_t)((pr_odd_count(limit) + 63) / 64); } + +#define PR_MAX_LIMIT (1ULL << 40) + +/* Full CLI: [--limit N=1000000] [--min-seconds S=5] [--bitmap-out PATH] [--report-out PATH] + * [--audit-passes K]. Exit 0 ok, 2 execution failure (no stdout line), 64 usage error. */ +int pr_main(int argc, char **argv, const pr_impl *impl); + +/* ---- hooks exposed for host tests (pure functions, no process state) ---- */ +typedef struct pr_args { + uint64_t limit; + double min_seconds; + const char *bitmap_out; + const char *report_out; + uint64_t audit_passes; /* 0 = timed mode */ +} pr_args; + +/* 0 = ok; -1 = usage error with a message in err. */ +int pr_parse_args(int argc, char **argv, pr_args *a, char *err, size_t errn); + +/* Upstream line "aien-;;;;algorithm=..,faithful=..,bits=..". + * Returns length written, or -1 if it does not fit. */ +int pr_format_line(char *buf, size_t n, const pr_impl *impl, uint64_t passes, double elapsed_s, uint64_t threads); + +/* 1 only if the stdout line may be printed: no failure, passes > 0, elapsed >= min_seconds. */ +int pr_line_allowed(int failed, uint64_t passes, double elapsed_s, double min_seconds); + +/* JSON string literal with hand-written escaping (quotes included). */ +void pr_json_string(FILE *f, const char *s); + +typedef struct pr_report { + const pr_impl *impl; + void *state; /* for threads()/detail_json(); may be NULL */ + uint64_t threads; + uint64_t limit; + double min_seconds; + const char *mode; /* "timed" | "audit" */ + uint64_t passes; + double elapsed_s; + const char *status; /* "COMPLETE" | "EXEC_FAILED" */ + const char *error; /* NULL when ok */ +} pr_report; + +/* Writes the "aien-prime-race/impl-report/v1" JSON object. Returns 0 if the stream had no error. */ +int pr_write_report(FILE *f, const pr_report *r); + +#endif diff --git a/bench/prime_race/tests/encoding_oracle.md b/bench/prime_race/tests/encoding_oracle.md new file mode 100644 index 000000000..e89567337 --- /dev/null +++ b/bench/prime_race/tests/encoding_oracle.md @@ -0,0 +1,38 @@ +# Encoding oracle for BW_IR_LOP3_LUT, BW_IR_SHF_L_U32, BW_IR_IMAD_HI_U32 + +Offline oracle only (nothing here is linked into AIEN). Recorded 2026-10-05 on the Spark with +`Cuda compilation tools, release 13.0, V13.0.88`: + +```sh +nvcc -arch=sm_121 -cubin -O3 -o ops.cubin ops.cu +cuobjdump -sass ops.cubin +``` + +Source (`ops.cu`, scratch dir outside omega): + +```cuda +// Offline encoding oracle for omega BW_IR_LOP3_LUT / SHF_L_U32 / IMAD_HI_U32. Never linked into AIEN. +extern "C" __global__ void k_or(unsigned *o, const unsigned *a) { unsigned x=a[threadIdx.x], y=a[threadIdx.x+64], z=a[threadIdx.x+128]; o[threadIdx.x] = x | y; o[threadIdx.x+64] = ~(x | y); o[threadIdx.x+128] = (x & y) ^ z; o[threadIdx.x+192] = ~(x|y) & z; } +extern "C" __global__ void k_shl(unsigned *o, const unsigned *a) { unsigned x=a[threadIdx.x], n=a[threadIdx.x+64]; o[threadIdx.x] = x << n; } +extern "C" __global__ void k_shl1(unsigned *o, const unsigned *a) { unsigned n=a[threadIdx.x]; o[threadIdx.x] = 1u << n; } +extern "C" __global__ void k_hi(unsigned *o, const unsigned *a) { unsigned x=a[threadIdx.x], y=a[threadIdx.x+64]; o[threadIdx.x] = __umulhi(x, y); } +extern "C" __global__ void k_hi2(unsigned *o, const unsigned *a) { unsigned x=a[threadIdx.x], y=a[threadIdx.x+64], z=a[threadIdx.x+128]; o[threadIdx.x] = __umulhi(x, y) + z; } +``` + +Instructions used as golden words in `omega_blackwell_verify_codegen_fixtures_intops` +(src/omega_blackwell_codegen.c). Low word, then high word; the high word's top 23 bits are +the control word, which our scheduler writes and the fixtures do not compare. + +``` +/*00b0*/ IMAD.HI.U32 R9, R9, R0, R6 ; /* 0x0000000009097227 */ /* 0x008fca00078e0006 */ +/*0090*/ IMAD.HI.U32 R7, R0, R7, RZ ; /* 0x0000000700077227 */ /* 0x008fca00078e00ff */ +/*0090*/ SHF.L.U32 R7, R9, R2, RZ ; /* 0x0000000209077219 */ /* 0x008fca00000006ff */ +/*0090*/ SHF.L.U32 R7, R0, R7, RZ ; /* 0x0000000700077219 */ /* 0x008fca00000006ff */ +/*00a0*/ LOP3.LUT R9, R7, R0, RZ, 0xfc, !PT ; /* 0x0000000007097212 */ /* 0x008fc400078efcff */ +/*00b0*/ LOP3.LUT R11, R6, R7, R0, 0x78, !PT ; /* 0x00000007060b7212 */ /* 0x010fc600078e7800 */ +/*00d0*/ LOP3.LUT R13, R6, R7, R0, 0x10, !PT ; /* 0x00000007060d7212 */ /* 0x000fe400078e1000 */ +/*00e0*/ LOP3.LUT R7, RZ, R9, RZ, 0x33, !PT ; /* 0x00000009ff077212 */ /* 0x000fe200078e33ff */ +``` + +The whole sieve kernel is also decoded by `nvdisasm -b SM121` in gb10_sieve_host_test +(every word decodes; every BRA target equals the IR target). diff --git a/bench/prime_race/tests/gb10_launch_cost.c b/bench/prime_race/tests/gb10_launch_cost.c new file mode 100644 index 000000000..018900862 --- /dev/null +++ b/bench/prime_race/tests/gb10_launch_cost.c @@ -0,0 +1,120 @@ +/* DIAGNOSTIC, not a benchmark result: where does a GB10 native launch spend its time? + * + * gb10_launch_cost empty N GRID BLOCK EXIT-only kernel, N launches + * gb10_launch_cost sieve N GRID BLOCK LIMIT prime sieve kernel at LIMIT, N launches + * + * Uses the session API exactly as bench/prime_race/gb10_native.c does (lock, open, uncached + * allocations, omega_gpu_session_launch with gpr 64 and a 600 s marker wait). Per launch it + * records the session's submit->marker2 time and the host wall time of the launch call, then + * prints median/min/max of each. The sieve kernel family assumes 128-thread CTAs (OMEGA_GPU_EW_THREADS), so + * BLOCK must be 128 for sieve; only the grid varies. The sieve run is checked: the bitmap of the last launch must + * hold pi(LIMIT) - 1 set bits (odd primes; bit i is 2i+1). Needs GB10_CHIP_RUN=1 and the GPU + * lock (/tmp/aien-gb10.lock) held by the caller. No CUDA. */ +#include "omega_gpu_elementwise_api.h" +#include "omega_gpu_session.h" +#include "omega_blackwell_codegen.h" +#include "omega_blackwell_qmd.h" /* OMEGA_BW_CBANK_MATMUL_ARGS_WORDS */ +#include +#include +#include +#include +#include + +#define MAXN 100000 + +static uint64_t now_ns(void) { + struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); + return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; +} +static int cmp_u64(const void *a, const void *b) { + uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; +} +static void stats(const char *what, uint64_t *v, int n) { + qsort(v, (size_t)n, sizeof *v, cmp_u64); + uint64_t med = n % 2 ? v[n / 2] : (v[n / 2 - 1] + v[n / 2]) / 2; + printf(" %-22s median=%8.1f us min=%8.1f us max=%8.1f us\n", what, med / 1e3, v[0] / 1e3, v[n - 1] / 1e3); +} + +/* EXIT plus the self-branch every kernel here ends with; nothing else. */ +static int build_empty(OmegaBlackwellKernel *k) { + static BlackwellIRProgram prog; + omega_bw_ir_init(&prog); + BlackwellIRInsn x; memset(&x, 0, sizeof x); + x.dst_vreg = x.src1_vreg = x.src2_vreg = x.src3_vreg = x.ureg = -1; + x.op = BW_IR_EXIT; + if (omega_bw_ir_append(&prog, &x) < 0) return -1; /* returns the index */ + x.op = BW_IR_BRA; x.imm = 0; + if (omega_bw_ir_append(&prog, &x) < 0) return -1; /* returns the index */ + if (omega_bw_regalloc_solve(&prog) != 0) return -1; + enum { CAP = 32 * 16 }; /* the encoder pads every program to at least 32 instructions */ + k->code = malloc(CAP); + size_t len = 0; + if (!k->code || omega_bw_encode_program(&prog, k->code, CAP, &len) != 0) return -1; + k->code_size = len; k->insn_count = prog.count; k->gpr_count = 1; + return 0; +} + +int main(int argc, char **argv) { + if (argc < 5 || (strcmp(argv[1], "empty") && strcmp(argv[1], "sieve")) || (!strcmp(argv[1], "sieve") && argc < 6)) { + fprintf(stderr, "usage: %s empty N GRID BLOCK | sieve N GRID BLOCK LIMIT\n", argv[0]); return 64; + } + const int sieve = !strcmp(argv[1], "sieve"); + int n = atoi(argv[2]); uint32_t grid = (uint32_t)atoi(argv[3]), block = (uint32_t)atoi(argv[4]); + uint64_t limit = sieve ? strtoull(argv[5], NULL, 10) : 0; + if (n < 1 || n > MAXN || grid < 1 || grid > OMEGA_GPU_EW_MAX_CTAS || block < 32 || block > 1024 || block % 32 || + limit > 0xffffffffull || (sieve && block != OMEGA_GPU_EW_THREADS)) { fprintf(stderr, "argument out of range\n"); return 64; } + + OmegaBlackwellKernel k; memset(&k, 0, sizeof k); + if (sieve ? omega_gpu_elementwise_codegen_ir(OMEGA_GPU_EW_PRIME_SIEVE, 0, NULL, &k) != OMEGA_GPU_EW_OK + : build_empty(&k) != 0) { fprintf(stderr, "codegen failed\n"); return 2; } + + if (!getenv("GB10_CHIP_RUN")) { fprintf(stderr, "codegen ok (%zu insns, %zu bytes); refused: set GB10_CHIP_RUN=1 (chip launch)\n", k.insn_count, k.code_size); return 2; } + + /* sieve geometry as gb10_native computes it, with the grid and block taken from the caller */ + uint64_t odd = (limit + 1) / 2; + uint32_t nwords = (uint32_t)((odd + 31) / 32), lastw = nwords ? nwords - 1 : 0; + uint32_t valid = nwords ? (uint32_t)(odd - 32ull * lastw) : 32; + uint32_t tailinv = ~(valid >= 32 ? 0xffffffffu : ((1u << valid) - 1u)); + uint32_t root = 0; while ((uint64_t)(root + 1) * (root + 1) <= limit) root++; + + omega_gpu_session_lock(); + if (!omega_gpu_session_open()) { fprintf(stderr, "open failed: %s\n", omega_gpu_session_last_error()); return 2; } + NvrmMem code, out, tab; + if (omega_gpu_session_alloc(k.code_size, &code) || omega_gpu_session_alloc((size_t)(nwords ? nwords : 1) * 4, &out) || + omega_gpu_session_alloc(((size_t)root / 2 + 2) * 12, &tab)) { fprintf(stderr, "alloc failed\n"); return 2; } + memcpy(code.cpu, k.code, k.code_size); + uint32_t *t = tab.cpu, np = 0; + for (uint32_t p = 3; p <= root; p += 2) { + int pr = 1; for (uint32_t d = 3; d * d <= p; d += 2) if (p % d == 0) { pr = 0; break; } + if (!pr) continue; + t[3 * np] = p; t[3 * np + 1] = (uint32_t)(((1ull << 32) + p - 1) / p); t[3 * np + 2] = (uint32_t)(((uint64_t)p * p - 1) / 2); np++; + } + t[3 * np] = 1; t[3 * np + 1] = 0; t[3 * np + 2] = 0xffffffffu; + __asm__ volatile("dsb sy" ::: "memory"); + + uint32_t args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS] = {0}; + args[0] = (uint32_t)tab.va; args[1] = (uint32_t)(tab.va >> 32); + args[4] = (uint32_t)out.va; args[5] = (uint32_t)(out.va >> 32); + args[6] = nwords; args[7] = grid * block; args[8] = lastw; args[9] = tailinv; + OmegaGpuLaunch L = { + .code_va = code.va, .gpr_count = 64, .threads_x = block, .threads_y = 1, .grid_x = grid, .grid_y = 1, + .num_elements = nwords ? nwords : 1, .args = args, .n_args = OMEGA_BW_CBANK_MATMUL_ARGS_WORDS, .timeout_ms = 600000, + }; + static uint64_t dev[MAXN], wall[MAXN]; + for (int i = 0; i < n; i++) { + uint64_t ns = 0; uint32_t marker = 0; /* elapsed_ns is added to, so reset per launch */ + uint64_t t0 = now_ns(); + if (omega_gpu_session_launch(&L, &ns, &marker) != 0) { fprintf(stderr, "launch %d failed: %s\n", i, omega_gpu_session_last_error()); return 2; } + wall[i] = now_ns() - t0; dev[i] = ns; + } + long bits = 0; + if (sieve) { uint32_t *o = out.cpu; for (uint32_t i = 0; i < nwords; i++) bits += __builtin_popcount(o[i]); } + printf("DIAGNOSTIC %s launches=%d grid=%u block=%u insns=%zu limit=%" PRIu64 " words=%u base_primes=%u odd_primes_found=%ld\n", + argv[1], n, grid, block, k.insn_count, limit, nwords, np, bits); + stats("submit->marker2", dev, n); + stats("host wall per launch", wall, n); + omega_gpu_session_free(&tab); omega_gpu_session_free(&out); omega_gpu_session_free(&code); + omega_gpu_session_unlock(); omega_gpu_session_close(); + free(k.code); + return 0; +} diff --git a/bench/prime_race/tests/gb10_sieve_host_test.c b/bench/prime_race/tests/gb10_sieve_host_test.c new file mode 100644 index 000000000..4973d579a --- /dev/null +++ b/bench/prime_race/tests/gb10_sieve_host_test.c @@ -0,0 +1,339 @@ +/* Host tests for the native GB10 prime sieve (no device is opened). + * + * gb10_sieve_host_test golden words of the three new ops, codegen budget, nvdisasm + * listing + every branch target, then the allocated IR program + * run by a host IR simulator over the limits sweep against an + * independent Eratosthenes oracle; the mutant must be caught + * gb10_sieve_host_test --big also 1e7 through the simulator (exercises the magic correction) + * gb10_sieve_host_test --limits print the DESIGN limits sweep, one per line (chip script input) + * gb10_sieve_host_test --oracle LIMIT PATH [K] + * write the canonical bitmap of LIMIT (K copies, default 1) + * + * Simulator: executes the post-allocation IR (physical registers, so the loop liveness + * fix of the register allocator is under test), one thread at a time (the kernel has no + * barrier or shuffle), host pointers as addresses with a bounds check on every access. + * It models the ISA as the IR documents it; it is not chip evidence. + */ +#include "prime_race_impl.h" +#include "omega_blackwell_codegen.h" +#include "omega_gpu_elementwise_api.h" +#include +#include +#include +#include +#include + +static int g_checks, g_failed; +#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) + +/* ------------------------------------------------------------- oracle */ +/* canonical words for limit: bit k set iff 2k+1 prime (plain Eratosthenes on odd numbers) */ +static uint64_t *oracle_bitmap(uint64_t limit) { + uint64_t odd = pr_odd_count(limit); + size_t nw = pr_words64(limit); + uint64_t *w = calloc(nw ? nw : 1, 8); + uint8_t *comp = calloc(odd ? odd : 1, 1); + if (!w || !comp) { free(w); free(comp); return NULL; } + if (odd) comp[0] = 1; /* 1 */ + for (uint64_t i = 1; i < odd; i++) { + uint64_t p = 2 * i + 1; + if (comp[i]) continue; + if (p * p > 2 * odd) continue; + for (uint64_t c = p * p; (c - 1) / 2 < odd; c += 2 * p) comp[(c - 1) / 2] = 1; + } + for (uint64_t k = 0; k < odd; k++) if (!comp[k]) w[k / 64] |= 1ull << (k % 64); + free(comp); + return w; +} + +static uint64_t count_primes(const uint64_t *w, uint64_t limit) { + uint64_t n = limit >= 2; + for (size_t i = 0; i < pr_words64(limit); i++) n += (uint64_t)__builtin_popcountll(w[i]); + return n; +} + +/* ------------------------------------------------------------- limits sweep */ +static int cmp_u64(const void *a, const void *b) { uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; return x < y ? -1 : x > y; } +static size_t sweep_limits(uint64_t *out, size_t cap, int full) { + static const uint64_t fixed[] = { 0, 1, 2, 3, 4, 5, 8, 9, 15, 25, 31, 32, 33, 34, 49, 63, 64, 65, 66, 95, 96, 97, + 121, 127, 128, 129, 130, 169, 255, 256, 257, 258, 289, 361, 961, 1023, 1024, 1025, 1999, 2000, 2001, 4095, 4096, 4097 }; + /* words of 32 odd numbers: limit 64k has exactly 32k odd numbers. k = 128 is one CTA of + * words, k = 8192 one full grid-stride round (64 CTAs x 128 threads). */ + static const uint64_t ks[] = { 1, 2, 3, 4, 127, 128, 129, 256, 8191, 8192, 8193, 16384 }; + size_t n = 0; +#define ADD(x) do { if (n < cap) out[n++] = (x); } while (0) + for (size_t i = 0; i < sizeof fixed / sizeof fixed[0]; i++) ADD(fixed[i]); + for (size_t i = 0; i < sizeof ks / sizeof ks[0]; i++) { ADD(64 * ks[i] - 1); ADD(64 * ks[i]); ADD(64 * ks[i] + 1); } + uint64_t pmax = full ? 997 : 113; + for (uint64_t p = 3; p <= pmax; p += 2) { + int prime = 1; + for (uint64_t d = 3; d * d <= p; d += 2) if (p % d == 0) { prime = 0; break; } + if (prime) { ADD(p * p - 1); ADD(p * p); ADD(p * p + 1); } + } + if (!full) { ADD(994009 - 1); ADD(994009); ADD(994009 + 1); } /* 997^2 */ + for (uint64_t l = 999983; l <= 1000003; l++) if (full || l == 999983 || l == 1000000 || l == 1000003) ADD(l); +#undef ADD + qsort(out, n, sizeof *out, cmp_u64); + size_t m = 0; + for (size_t i = 0; i < n; i++) if (m == 0 || out[i] != out[m - 1]) out[m++] = out[i]; + return m; +} + +/* ------------------------------------------------------------- simulator */ +typedef struct { uint32_t r[256]; int pc, p0, done; } Thr; +static uint32_t g_cb[256]; /* constant bank 0 words 0..255 (byte offset / 4) */ +typedef struct { uintptr_t lo, hi; } Range; +static Range g_ranges[2]; +static int g_sim_err; + +static uint32_t rd(const Thr *t, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; return t->r[p->regalloc.vreg_to_phys[v] & 0xff]; } +static uint64_t rd64(const Thr *t, int v, const BlackwellIRProgram *p) { if (v < 0) return 0; int ph = p->regalloc.vreg_to_phys[v] & 0xff; return (uint64_t)t->r[ph] | ((uint64_t)t->r[ph + 1] << 32); } +static void wr(Thr *t, int v, uint32_t x, const BlackwellIRProgram *p) { if (v >= 0) t->r[p->regalloc.vreg_to_phys[v] & 0xff] = x; } +static void wr64(Thr *t, int v, uint64_t x, const BlackwellIRProgram *p) { if (v < 0) return; int ph = p->regalloc.vreg_to_phys[v] & 0xff; t->r[ph] = (uint32_t)x; t->r[ph + 1] = (uint32_t)(x >> 32); } +static uint32_t *mem_at(uint64_t a) { + for (int i = 0; i < 2; i++) if (a >= g_ranges[i].lo && a + 4 <= g_ranges[i].hi && (a & 3) == 0) return (uint32_t *)(uintptr_t)a; + g_sim_err = 3; return NULL; +} +static uint32_t lut3(uint32_t lut, uint32_t a, uint32_t b, uint32_t c) { + uint32_t r = 0; + for (int i = 0; i < 8; i++) if (lut >> i & 1) r |= ((i & 4) ? a : ~a) & ((i & 2) ? b : ~b) & ((i & 1) ? c : ~c); + return r; +} + +static uint64_t g_steps; +static void sim_thread(const BlackwellIRProgram *p, uint32_t tid, uint32_t cta) { + Thr t; memset(&t, 0, sizeof t); + for (uint64_t guard = 0; guard < 400000000ull; guard++) { + if (t.pc < 0 || (size_t)t.pc >= p->count) { g_sim_err = 1; return; } + const BlackwellIRInsn *in = &p->insns[t.pc]; + uint32_t a = rd(&t, in->src1_vreg, p), b = rd(&t, in->src2_vreg, p), c = rd(&t, in->src3_vreg, p); + g_steps++; + switch (in->op) { + case BW_IR_EXIT: if (!in->predicate_p0 || t.p0) return; break; + case BW_IR_BRA: { + int take = !in->predicate_p0 || (in->predicate_not ? !t.p0 : t.p0); + if (take) { if ((int32_t)in->imm == 0) { g_sim_err = 2; return; } t.pc += (int32_t)in->imm; continue; } + break; } + case BW_IR_S2R: wr(&t, in->dst_vreg, in->imm == BW_SR_TID_X ? tid : in->imm == BW_SR_CTAID_X ? cta : 0, p); break; + case BW_IR_LDC: wr(&t, in->dst_vreg, g_cb[(in->imm / 4) & 0xff], p); break; + case BW_IR_LDC64: wr64(&t, in->dst_vreg, (uint64_t)g_cb[(in->imm / 4) & 0xff] | ((uint64_t)g_cb[(in->imm / 4 + 1) & 0xff] << 32), p); break; + case BW_IR_LDCU64: break; /* memory descriptor: not modelled */ + case BW_IR_MOV_IMM: wr(&t, in->dst_vreg, in->imm, p); break; + case BW_IR_MOV_RZ: wr(&t, in->dst_vreg, 0, p); break; + case BW_IR_IMAD: wr(&t, in->dst_vreg, in->src2_vreg >= 0 ? a * b + c : a * in->imm + c, p); break; + case BW_IR_IMAD_WIDE: wr64(&t, in->dst_vreg, (uint64_t)a * in->imm + rd64(&t, in->src3_vreg, p), p); break; + case BW_IR_IMAD_HI_U32: wr(&t, in->dst_vreg, (uint32_t)(((uint64_t)a * b) >> 32) + c, p); break; + case BW_IR_IADD3: wr(&t, in->dst_vreg, a + b, p); break; /* the encoder's IADD3 has Rc = RZ */ + case BW_IR_SHF_R: wr(&t, in->dst_vreg, a >> (in->imm & 31), p); break; + case BW_IR_SHF_L_U32: if (b >= 32) { g_sim_err = 8; return; } wr(&t, in->dst_vreg, a << b, p); break; + case BW_IR_LOP3_XOR: wr(&t, in->dst_vreg, a ^ b, p); break; + case BW_IR_LOP3_LUT: wr(&t, in->dst_vreg, lut3(in->imm & 0xff, a, b, c), p); break; + case BW_IR_ISETP_GE_U32: t.p0 = a >= b; break; + case BW_IR_LDG_E: { uint32_t *m = mem_at(rd64(&t, in->src1_vreg, p)); if (!m) return; wr(&t, in->dst_vreg, *m, p); break; } + case BW_IR_STG_E: { uint32_t *m = mem_at(rd64(&t, in->src1_vreg, p)); if (!m) return; *m = b; break; } + default: g_sim_err = 100 + (int)in->op; return; + } + t.pc++; + } + g_sim_err = 4; +} + +/* Mirrors gb10_native.c's pass on the host: same table, same argument words. */ +static int sim_sieve(const BlackwellIRProgram *p, uint64_t limit, uint64_t *words) { + uint64_t odd = pr_odd_count(limit); + uint32_t nwords = (uint32_t)((odd + 31) / 32); + uint32_t blocks = (nwords + OMEGA_GPU_EW_THREADS - 1) / OMEGA_GPU_EW_THREADS; + uint32_t ctas = blocks == 0 ? 1 : (blocks > OMEGA_GPU_EW_MAX_CTAS ? OMEGA_GPU_EW_MAX_CTAS : blocks); + uint32_t stride = ctas * OMEGA_GPU_EW_THREADS, lastw = nwords ? nwords - 1 : 0; + uint32_t valid = nwords ? (uint32_t)(odd - 32ull * lastw) : 32; + uint32_t tailinv = ~(valid >= 32 ? 0xffffffffu : ((1u << valid) - 1u)); + uint32_t root = 0; while ((uint64_t)(root + 1) * (root + 1) <= limit) root++; + size_t cap = root / 2 + 2; + uint32_t *tab = calloc(cap * 3, 4), *out = calloc(nwords ? nwords : 1, 4); + if (!tab || !out) { free(tab); free(out); return -1; } + uint32_t n = 0; + for (uint32_t q = 3; q <= root; q += 2) { + int prime = 1; + for (uint32_t d = 3; d * d <= q; d += 2) if (q % d == 0) { prime = 0; break; } + if (!prime) continue; + tab[3 * n] = q; tab[3 * n + 1] = (uint32_t)(((1ull << 32) + q - 1) / q); tab[3 * n + 2] = (uint32_t)(((uint64_t)q * q - 1) / 2); n++; + } + tab[3 * n] = 1; tab[3 * n + 1] = 0; tab[3 * n + 2] = 0xffffffffu; + for (uint32_t i = 0; i < nwords; i++) out[i] = 0xffbadbadu; + memset(g_cb, 0, sizeof g_cb); + uint64_t ta = (uintptr_t)tab, oa = (uintptr_t)out; + g_cb[0x380 / 4] = (uint32_t)ta; g_cb[0x380 / 4 + 1] = (uint32_t)(ta >> 32); + g_cb[0x390 / 4] = (uint32_t)oa; g_cb[0x390 / 4 + 1] = (uint32_t)(oa >> 32); + g_cb[0x398 / 4] = nwords; g_cb[0x39c / 4] = stride; g_cb[0x3a0 / 4] = lastw; g_cb[0x3a4 / 4] = tailinv; + g_ranges[0] = (Range){ (uintptr_t)tab, (uintptr_t)tab + cap * 12 }; + g_ranges[1] = (Range){ (uintptr_t)out, (uintptr_t)out + (size_t)nwords * 4 }; + g_sim_err = 0; + for (uint32_t cta = 0; cta < ctas && !g_sim_err; cta++) + for (uint32_t tid = 0; tid < OMEGA_GPU_EW_THREADS && !g_sim_err; tid++) sim_thread(p, tid, cta); + size_t nw64 = pr_words64(limit); + memset(words, 0, nw64 * 8); + memcpy(words, out, (size_t)nwords * 4); + free(tab); free(out); + return g_sim_err ? -1 : 0; +} + +/* ------------------------------------------------------------- nvdisasm */ +/* every word decodes, the new ops appear, and every BRA lands where the IR says */ +static void nvdisasm_check(const OmegaBlackwellKernel *k, const BlackwellIRProgram *p) { + const char *nv = "/usr/local/cuda/bin/nvdisasm"; + if (access(nv, X_OK) != 0) { printf("nvdisasm: not present, listing check SKIPPED\n"); return; } + char bin[64], lst[64], cmd[256]; + snprintf(bin, sizeof bin, "/tmp/pr_gb10_sieve_%d.bin", (int)getpid()); + snprintf(lst, sizeof lst, "/tmp/pr_gb10_sieve_%d.sass", (int)getpid()); + FILE *f = fopen(bin, "wb"); + if (!f) { CHECK(0, "cannot write %s", bin); return; } + fwrite(k->code, 1, k->code_size, f); fclose(f); + snprintf(cmd, sizeof cmd, "%s -b SM121 %s > %s 2>&1", nv, bin, lst); + int rc = system(cmd); + unlink(bin); + CHECK(rc == 0, "nvdisasm rc %d", rc); + FILE *l = fopen(lst, "r"); + if (!l) { CHECK(0, "cannot read %s", lst); return; } + static const char *must[] = { "LOP3.LUT", "SHF.L.U32", "IMAD.HI.U32", "@P0 BRA", "@!P0 BRA", "@P0 EXIT", "STG.E", "LDG.E" }; + int seen[8] = {0}, insns = 0, bad = 0, bra_ok = 0, bra_bad = 0; + char line[512]; + while (fgets(line, sizeof line, l)) { + char *s = strstr(line, "/*"); + if (!s) continue; + unsigned addr; + if (sscanf(s, "/*%x*/", &addr) != 1 || s[6] != '*') continue; + insns++; + if (strchr(line, '?') || strstr(line, "error")) bad++; + for (int i = 0; i < 8; i++) if (strstr(line, must[i])) seen[i] = 1; + char *br = strstr(line, "BRA "); + if (br && addr / 16 < p->count) { + const BlackwellIRInsn *in = &p->insns[addr / 16]; + unsigned long target = strtoul(br + 4, NULL, 16); + unsigned long want = (unsigned long)((int)(addr / 16) + (int32_t)in->imm) * 16; + if (in->op == BW_IR_BRA && target == want) bra_ok++; + else { bra_bad++; printf(" branch at 0x%04x: nvdisasm target 0x%lx, IR target 0x%lx\n", addr, target, want); } + } + } + fclose(l); + for (int i = 0; i < 8; i++) CHECK(seen[i], "nvdisasm listing lacks %s (%s)", must[i], lst); + CHECK(bad == 0, "%d undecodable words (%s)", bad, lst); + CHECK(bra_bad == 0 && bra_ok >= 6, "branch targets: %d match, %d differ", bra_ok, bra_bad); + printf("nvdisasm: %d words, %d undecodable, %d branch targets checked (%s)\n", insns, bad, bra_ok, lst); + if (g_failed == 0) unlink(lst); +} + +/* ------------------------------------------------------------- magic model */ +/* The kernel's offset step as plain C: counts how often q = hi32(d * ceil(2^32/p)) is one + * too big (r wraps) over the workload, so the --big run is known to exercise that case, and + * checks the kernel's j = (p - r) - p*((r-1)>>31) against (p - d % p) % p on every pair. */ +static void magic_model(uint64_t limit) { + uint64_t odd = pr_odd_count(limit), nwords = (odd + 31) / 32, over = 0, wrong = 0, pairs = 0; + uint32_t root = 0; while ((uint64_t)(root + 1) * (root + 1) <= limit) root++; + for (uint32_t p = 3; p <= root; p += 2) { + int prime = 1; + for (uint32_t d = 3; d * d <= p; d += 2) if (p % d == 0) { prime = 0; break; } + if (!prime) continue; + uint32_t magic = (uint32_t)(((1ull << 32) + p - 1) / p), k0 = (uint32_t)(((uint64_t)p * p - 1) / 2); + for (uint64_t w = 0; w < nwords; w++) { + uint32_t base = (uint32_t)(32 * w); + if (k0 >= base + 32 || k0 > base) continue; + uint32_t d = base - k0, q = (uint32_t)(((uint64_t)d * magic) >> 32), r = d - q * p; + pairs++; + if (r >> 31) over++; + uint32_t j = p - r; + j -= p * ((r - 1) >> 31); /* the kernel's single fix */ + if (j != (p - d % p) % p) wrong++; + } + } + printf("magic model limit %" PRIu64 ": %" PRIu64 " word/prime pairs, %" PRIu64 " needed the correction, %" PRIu64 " wrong\n", limit, pairs, over, wrong); + CHECK(wrong == 0, "magic division wrong on %" PRIu64 " pairs", wrong); + if (limit >= 10000000ull) CHECK(over > 0, "the 1e7 workload never needs the correction (test would not exercise it)"); +} + +static int write_oracle(uint64_t limit, const char *path, unsigned k) { + uint64_t *w = oracle_bitmap(limit); + FILE *f = fopen(path, "wb"); + if (!w || !f) { free(w); if (f) fclose(f); return 2; } + size_t nw = pr_words64(limit); + for (unsigned i = 0; i < k; i++) if (nw && fwrite(w, 8, nw, f) != nw) { fclose(f); free(w); return 2; } + free(w); + return fclose(f) == 0 ? 0 : 2; +} + +int main(int argc, char **argv) { + int big = 0; + if (argc >= 2 && strcmp(argv[1], "--limits") == 0) { + static uint64_t l[4096]; + size_t n = sweep_limits(l, 4096, 1); + for (size_t i = 0; i < n; i++) printf("%" PRIu64 "\n", l[i]); + return 0; + } + if (argc >= 4 && strcmp(argv[1], "--oracle") == 0) + return write_oracle(strtoull(argv[2], NULL, 10), argv[3], argc >= 5 ? (unsigned)atoi(argv[4]) : 1u); + if (argc >= 2 && strcmp(argv[1], "--big") == 0) big = 1; + + /* 1. golden words */ + int fx = omega_blackwell_verify_codegen_fixtures_intops(); + CHECK(fx == 0, "golden words LOP3_LUT / SHF_L_U32 / IMAD_HI_U32 (rc %d)", fx); + + /* 2. oracle self-check against pi(x) */ + static const struct { uint64_t x, pi; } pis[] = { {10, 4}, {100, 25}, {1000, 168}, {10000, 1229}, {100000, 9592}, {1000000, 78498} }; + for (size_t i = 0; i < sizeof pis / sizeof pis[0]; i++) { + uint64_t *w = oracle_bitmap(pis[i].x); + CHECK(w && count_primes(w, pis[i].x) == pis[i].pi, "oracle pi(%" PRIu64 ")", pis[i].x); + free(w); + } + + /* 3. codegen */ + BlackwellIRProgram *prog = calloc(1, sizeof *prog), *mprog = calloc(1, sizeof *mprog); + OmegaBlackwellKernel k, mk; + memset(&k, 0, sizeof k); memset(&mk, 0, sizeof mk); + int rc = omega_gpu_elementwise_codegen_ir(OMEGA_GPU_EW_PRIME_SIEVE, 0, prog, &k); + int mrc = omega_gpu_elementwise_codegen_ir(OMEGA_GPU_EW_PRIME_SIEVE, 1, mprog, &mk); + CHECK(rc == OMEGA_GPU_EW_OK && mrc == OMEGA_GPU_EW_OK, "codegen rc %d mutant rc %d", rc, mrc); + if (rc != OMEGA_GPU_EW_OK || mrc != OMEGA_GPU_EW_OK) { printf("VERDICT FAIL (codegen)\n"); return 1; } + printf("kernel: %zu IR insns, %zu encoded words, %u GPRs, sha256 ", prog->count, k.insn_count, k.gpr_count); + for (int i = 0; i < 32; i++) printf("%02x", k.code_digest[i]); + printf("\n"); + CHECK(k.gpr_count <= 64, "GPR budget %u > 64", k.gpr_count); + CHECK(memcmp(k.code_digest, mk.code_digest, 32) != 0, "mutant kernel differs from production"); + nvdisasm_check(&k, prog); + + /* 4. simulator sweep */ + static uint64_t lims[4096]; + size_t nl = sweep_limits(lims, 4096, 0); + int sim_fail = 0; uint64_t first_bad = 0; + for (size_t i = 0; i < nl + (size_t)big; i++) { + uint64_t L = i < nl ? lims[i] : 10000000ull; + uint64_t *want = oracle_bitmap(L), *got = calloc(pr_words64(L) + 1, 8); + if (!want || !got) { CHECK(0, "alloc"); break; } + int src = sim_sieve(prog, L, got); + size_t nw = pr_words64(L), bad = nw; + for (size_t j = 0; j < nw; j++) if (got[j] != want[j]) { bad = j; break; } + if (src != 0 || bad != nw) { + if (!sim_fail++) first_bad = L; + printf(" sim limit %" PRIu64 ": sim rc %d err %d, first differing u64 word %zu (got %016" PRIx64 " want %016" PRIx64 ")\n", + L, src, g_sim_err, bad, bad < nw ? got[bad] : 0, bad < nw ? want[bad] : 0); + } + if (L == 1000000) CHECK(count_primes(got, L) == 78498, "sim pi(1e6) = %" PRIu64, count_primes(got, L)); + free(want); free(got); + } + CHECK(sim_fail == 0, "simulator differs from the oracle at %d limits (first %" PRIu64 ")", sim_fail, first_bad); + printf("simulator: %zu limits%s, %d differ, %" PRIu64 " IR steps\n", nl + (size_t)big, big ? " (+1e7)" : "", sim_fail, g_steps); + + /* 5. mutant must be caught */ + { + uint64_t L = 100000, *want = oracle_bitmap(L), *got = calloc(pr_words64(L) + 1, 8); + int src = want && got ? sim_sieve(mprog, L, got) : -1; + CHECK(src == 0 && want && memcmp(got, want, pr_words64(L) * 8) != 0, "mutant kernel not caught at 1e5 (sim rc %d)", src); + free(want); free(got); + } + + /* 6. division model */ + magic_model(1000000); + if (big) magic_model(10000000); + + free(k.code); free(mk.code); free(prog); free(mprog); + printf("checks=%d failed=%d\nVERDICT %s\n", g_checks, g_failed, g_failed ? "FAIL" : "PASS"); + return g_failed ? 1 : 0; +} diff --git a/bench/prime_race/tests/prime_race_host_test.c b/bench/prime_race/tests/prime_race_host_test.c new file mode 100644 index 000000000..cdfa95ec8 --- /dev/null +++ b/bench/prime_race/tests/prime_race_host_test.c @@ -0,0 +1,232 @@ +/* Host test for the prime race protocol helper and the cpu_base baseline. + * Oracle: independent trial division (no sieve). Compares canonical bitmaps word for word. */ +#include "../prime_race_impl.h" + +#include +#include + +extern const pr_impl pr_cpu_base_impl; + +static int g_fail = 0, g_checks = 0; +#define CHECK(c, ...) do { g_checks++; if (!(c)) { g_fail++; fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__); fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); } } while (0) + +/* ---- independent oracle: canonical bitmap by trial division ---- */ +static int is_prime_td(uint64_t n) { + if (n < 2) return 0; + if (n % 2 == 0) return n == 2; + for (uint64_t d = 3; d * d <= n; d += 2) if (n % d == 0) return 0; + return 1; +} +static void oracle(uint64_t limit, uint64_t *out) { + size_t nw = pr_words64(limit); + memset(out, 0, (nw ? nw : 1) * 8); + for (uint64_t k = 0; k < pr_odd_count(limit); k++) + if (is_prime_td(2 * k + 1)) out[k / 64] |= 1ULL << (k % 64); +} +static uint64_t count_primes(const uint64_t *bm, uint64_t limit) { + uint64_t c = (limit >= 2); + for (size_t w = 0; w < pr_words64(limit); w++) c += (uint64_t)__builtin_popcountll(bm[w]); + return c; +} +/* comparator: returns -1 if identical, else index of first differing word */ +static long first_diff(const uint64_t *a, const uint64_t *b, size_t nw) { + for (size_t w = 0; w < nw; w++) if (a[w] != b[w]) return (long)w; + return -1; +} + +static uint64_t *run_cpu(uint64_t limit, void **stp) { + const pr_impl *im = &pr_cpu_base_impl; + void *st = NULL; + if (im->setup(&st, limit) != 0 || im->pass(st, limit) != 0) return NULL; + uint64_t *out = (uint64_t *)calloc(pr_words64(limit) ? pr_words64(limit) : 1, 8); + if (!out || im->export_bitmap(st, limit, out) != 0) return NULL; + *stp = st; + return out; +} + +static void check_limit(uint64_t limit, const uint64_t *expect) { + void *st = NULL; + uint64_t *got = run_cpu(limit, &st); + CHECK(got != NULL, "cpu_base failed at limit %llu", (unsigned long long)limit); + if (!got) return; + long d = first_diff(expect, got, pr_words64(limit)); + CHECK(d < 0, "limit %llu: first differing word %ld", (unsigned long long)limit, d); + pr_cpu_base_impl.teardown(st); + free(got); +} + +static void test_all_small(void) { + uint64_t *exp = (uint64_t *)malloc(64 * 8); + for (uint64_t limit = 0; limit <= 3000; limit++) { + oracle(limit, exp); + check_limit(limit, exp); + } + free(exp); +} + +/* design limits up to 2,000,000: expected bitmap derived from one trial-division master (prefix + tail mask) */ + +static size_t g_nlim = 0; +static uint64_t g_lims[8192]; +static void addlim(uint64_t l) { if (l <= 2000000 && g_nlim < 8192) g_lims[g_nlim++] = l; } +static void addrange(uint64_t a, uint64_t b) { for (uint64_t l = a; l <= b; l++) addlim(l); } + +static void test_design_limits(void) { + static const uint64_t one[] = {0, 1, 2, 3, 4, 5, 8, 9, 15, 25, 49, 121, 169, 289, 361, 961, 1000000, 2000000}; + for (size_t i = 0; i < sizeof one / sizeof one[0]; i++) addlim(one[i]); + addrange(31, 34); addrange(63, 66); addrange(95, 97); addrange(127, 130); addrange(255, 258); + addrange(1023, 1025); addrange(1999, 2001); addrange(4095, 4097); + addrange(999983, 1000003); + for (uint64_t k = 1; 2048 * k <= 2000000; k++) { addlim(2048 * k - 1); addlim(2048 * k); addlim(2048 * k + 1); } + for (uint64_t p = 2; p <= 997; p++) if (is_prime_td(p)) { addlim(p * p - 1); addlim(p * p); addlim(p * p + 1); } + + size_t mw = pr_words64(2000000); + uint64_t *m = (uint64_t *)malloc(mw * 8); + oracle(2000000, m); + uint64_t *exp = (uint64_t *)malloc(mw * 8); + for (size_t i = 0; i < g_nlim; i++) { + uint64_t limit = g_lims[i]; + size_t nw = pr_words64(limit); + uint64_t odd = pr_odd_count(limit); + for (size_t w = 0; w < nw; w++) exp[w] = m[w]; + if (nw && odd % 64) exp[nw - 1] &= (1ULL << (odd % 64)) - 1; + if (limit <= 3000) { /* master prefix must agree with direct oracle */ + uint64_t d[64]; oracle(limit, d); + CHECK(first_diff(d, exp, nw) < 0, "master prefix disagrees with direct oracle at %llu", (unsigned long long)limit); + } + check_limit(limit, exp); + } + printf("design limits checked: %zu\n", g_nlim); + free(m); free(exp); +} + +static void test_pi_table(void) { + static const struct { uint64_t limit, pi; } t[] = {{10, 4}, {100, 25}, {1000, 168}, {10000, 1229}, {100000, 9592}, {1000000, 78498}, {10000000, 664579}}; + for (size_t i = 0; i < sizeof t / sizeof t[0]; i++) { + void *st = NULL; + uint64_t *bm = run_cpu(t[i].limit, &st); + CHECK(bm != NULL, "run failed at %llu", (unsigned long long)t[i].limit); + if (!bm) continue; + uint64_t c = count_primes(bm, t[i].limit); + CHECK(c == t[i].pi, "pi(%llu)=%llu expected %llu", (unsigned long long)t[i].limit, (unsigned long long)c, (unsigned long long)t[i].pi); + pr_cpu_base_impl.teardown(st); + free(bm); + } +} + +/* negative self-checks: the comparator must catch corruption */ +static void test_negative(void) { + static const uint64_t lims[] = {100, 1000, 4097, 1000000}; + for (size_t i = 0; i < sizeof lims / sizeof lims[0]; i++) { + uint64_t limit = lims[i]; + size_t nw = pr_words64(limit); + uint64_t *exp = (uint64_t *)malloc(nw * 8), *bad = (uint64_t *)malloc(nw * 8); + oracle(limit, exp); + memcpy(bad, exp, nw * 8); + CHECK(first_diff(exp, bad, nw) < 0, "identical copies must compare equal"); + bad[nw / 2] ^= 1ULL << 1; /* flip one bit */ + CHECK(first_diff(exp, bad, nw) == (long)(nw / 2), "one flipped bit not caught at %llu", (unsigned long long)limit); + memcpy(bad, exp, nw * 8); + uint64_t odd = pr_odd_count(limit); + if (odd % 64) { bad[nw - 1] |= 1ULL << 63; CHECK(first_diff(exp, bad, nw) >= 0, "tail garbage not caught"); } + memcpy(bad, exp, nw * 8); + memset(bad, 0, nw * 8); + CHECK(first_diff(exp, bad, nw) >= 0, "all-zero not caught"); + free(exp); free(bad); + } +} + +/* each pass recomputes; second pass on same state gives the same canonical result */ +static void test_repeat_pass(void) { + void *st = NULL; + const pr_impl *im = &pr_cpu_base_impl; + uint64_t limit = 12345, a[256], b[256]; + CHECK(im->setup(&st, limit) == 0, "setup"); + CHECK(im->pass(st, limit) == 0 && im->export_bitmap(st, limit, a) == 0, "pass1"); + CHECK(im->pass(st, limit) == 0 && im->export_bitmap(st, limit, b) == 0, "pass2"); + CHECK(first_diff(a, b, pr_words64(limit)) < 0, "pass1 != pass2"); + CHECK(im->threads(st) == 1, "threads"); + im->teardown(st); +} + +static void test_formatting(void) { + char buf[512]; + const pr_impl *im = &pr_cpu_base_impl; + int n = pr_format_line(buf, sizeof buf, im, 1234, 5.000123456, 1); + CHECK(n > 0 && strcmp(buf, "aien-cpu-c-base;1234;5.000123;1;algorithm=base,faithful=yes,bits=1") == 0, "line: %s", buf); + char tiny[8]; + CHECK(pr_format_line(tiny, sizeof tiny, im, 1, 1.0, 1) < 0, "truncated line must be rejected"); + CHECK(pr_line_allowed(0, 1, 5.0, 5.0) == 1, "allowed"); + CHECK(pr_line_allowed(1, 1, 5.0, 5.0) == 0, "failed -> no line"); + CHECK(pr_line_allowed(0, 0, 5.0, 5.0) == 0, "passes 0 -> no line"); + CHECK(pr_line_allowed(0, 3, 4.999, 5.0) == 0, "short elapsed -> no line"); + + char *mem = NULL; size_t sz = 0; + FILE *f = open_memstream(&mem, &sz); + pr_json_string(f, "a\"b\\c\n\t\x01z"); + fclose(f); + CHECK(strcmp(mem, "\"a\\\"b\\\\c\\n\\t\\u0001z\"") == 0, "json escape: %s", mem); + free(mem); + + void *st = NULL; + im->setup(&st, 100); + pr_report r = {im, st, 1, 100, 5.0, "timed", 7, 5.25, "COMPLETE", NULL}; + f = open_memstream(&mem, &sz); + CHECK(pr_write_report(f, &r) == 0, "report write"); + fclose(f); + CHECK(strstr(mem, "\"schema\": \"aien-prime-race/impl-report/v1\"") != NULL, "schema"); + CHECK(strstr(mem, "\"label\": \"aien-cpu-c-base\"") != NULL, "label"); + CHECK(strstr(mem, "\"status\": \"COMPLETE\"") != NULL && strstr(mem, "\"error\": null") != NULL, "status/error"); + CHECK(strstr(mem, "\"passes\": 7") != NULL && strstr(mem, "\"elapsed_s\": 5.250000") != NULL, "passes/elapsed"); + CHECK(strstr(mem, "\"environment\": \"linux-host-cpu\"") != NULL, "environment"); + CHECK(strstr(mem, "\"build\": {\"source_commit\"") != NULL, "build"); + free(mem); + r.status = "EXEC_FAILED"; r.error = "boom \"x\""; + f = open_memstream(&mem, &sz); + pr_write_report(f, &r); + fclose(f); + CHECK(strstr(mem, "\"error\": \"boom \\\"x\\\"\"") != NULL, "failure report error escaped"); + free(mem); + im->teardown(st); +} + +static void test_args(void) { + pr_args a; char err[128]; + char *ok[] = {"x", "--limit", "1000", "--min-seconds", "0.5", "--audit-passes", "3", "--bitmap-out", "/tmp/b"}; + CHECK(pr_parse_args(9, ok, &a, err, sizeof err) == 0 && a.limit == 1000 && a.min_seconds == 0.5 && a.audit_passes == 3, "valid args"); + char *def[] = {"x"}; + CHECK(pr_parse_args(1, def, &a, err, sizeof err) == 0 && a.limit == 1000000 && a.min_seconds == 5.0 && a.audit_passes == 0, "defaults"); + char *bad1[] = {"x", "--limit", "12abc"}; + char *bad2[] = {"x", "--limit", "-5"}; + char *bad3[] = {"x", "--limit", "1099511627777"}; /* 2^40 + 1 */ + char *bad4[] = {"x", "--limit"}; + char *bad5[] = {"x", "--min-seconds", "nan"}; + char *bad6[] = {"x", "--audit-passes", "0", "--bitmap-out", "/tmp/b"}; + char *bad7[] = {"x", "--bogus"}; + char *bad8[] = {"x", "--audit-passes", "2"}; + char *bad9[] = {"x", "--limit", ""}; + char *good40[] = {"x", "--limit", "1099511627776"}; + CHECK(pr_parse_args(3, bad1, &a, err, sizeof err) != 0, "trailing junk"); + CHECK(pr_parse_args(3, bad2, &a, err, sizeof err) != 0, "negative"); + CHECK(pr_parse_args(3, bad3, &a, err, sizeof err) != 0, "above 2^40"); + CHECK(pr_parse_args(2, bad4, &a, err, sizeof err) != 0, "missing value"); + CHECK(pr_parse_args(3, bad5, &a, err, sizeof err) != 0, "nan"); + CHECK(pr_parse_args(5, bad6, &a, err, sizeof err) != 0, "audit 0"); + CHECK(pr_parse_args(2, bad7, &a, err, sizeof err) != 0, "unknown option"); + CHECK(pr_parse_args(3, bad8, &a, err, sizeof err) != 0, "audit without bitmap-out"); + CHECK(pr_parse_args(3, bad9, &a, err, sizeof err) != 0, "empty limit"); + CHECK(pr_parse_args(3, good40, &a, err, sizeof err) == 0, "2^40 allowed"); +} + +int main(void) { + test_formatting(); + test_args(); + test_negative(); + test_repeat_pass(); + test_pi_table(); + test_all_small(); + test_design_limits(); + printf("prime_race_host_test: %d checks, %d failures\n", g_checks, g_fail); + printf(g_fail ? "PRIME_RACE_HOST_TEST FAIL\n" : "PRIME_RACE_HOST_TEST PASS\n"); + return g_fail ? 1 : 0; +} diff --git a/bench/prime_race/tests/run_gb10_chip.sh b/bench/prime_race/tests/run_gb10_chip.sh new file mode 100755 index 000000000..ed32b68fd --- /dev/null +++ b/bench/prime_race/tests/run_gb10_chip.sh @@ -0,0 +1,145 @@ +#!/bin/bash +# bench/prime_race/tests/run_gb10_chip.sh -- AIEN Prime Drag Race: native GB10 sieve chip test. +# +# GB10_CHIP_RUN=1 bench/prime_race/tests/run_gb10_chip.sh --physics-dir DIR [--evidence-dir DIR] +# +# Pattern of tests/run_tensor_chip.sh (never creates or touches the quiet flag; the +# operator runs it inside an own quiet window). +# 1. Refuses unless GB10_CHIP_RUN=1, the omega tree is clean, and the physics checkout is +# clean and at the physics.lock commit. +# 2. Builds libomega_gpu, gb10_native, gb10_native_mutant and the host test (nice, -j1); +# the Makefile refuses a binary with CUDA symbols (nm, tools/chip_run.sh pattern); this +# script checks again. +# 3. Runs the host test first (golden words, nvdisasm listing, IR simulator sweep): a +# kernel that is wrong on the host never gets chip time. +# 4. Takes /tmp/aien-gb10.lock (waits; no timeout) and holds it for the whole sweep. Every +# limit of the DESIGN sweep (gb10_sieve_host_test --limits) runs in audit mode (K = 2; +# K = 5 at 1e6), every pass's bitmap compared byte for byte with the host oracle +# (independent Eratosthenes); then 1e7 (K = 1), one timed run (1e6, 2 s, stdout line +# and final bitmap checked) and the mutant binary at 1e6, which must be caught. +# The first failing run stops the sweep (no further launches); nothing is ever killed. +# 5. Writes a content-addressed receipt /.json (mode 0444, never +# overwritten) for PASS and FAIL alike, plus the run log as blobs/.log. +# Shell + coreutils + git + jq + make + nm + cmp + flock. No Python. Exit 0 PASS, 1 FAIL, 2 refused. +set -u +SELF_DIR=$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd) +OMEGA=$(cd "$SELF_DIR/../../.." && pwd) +PHYS="" +EVID=$HOME/workspace/evidence/prime-race/gb10-chip +while [ $# -gt 0 ]; do + case $1 in + --physics-dir) PHYS=$2; shift 2 ;; + --evidence-dir) EVID=$2; shift 2 ;; + *) echo "unknown argument $1" >&2; exit 2 ;; + esac +done +die() { echo "run_gb10_chip: $*" >&2; exit 2; } +[ "${GB10_CHIP_RUN:-}" = 1 ] || die "chip run refused: GB10_CHIP_RUN=1 is not set" +[ -n "$PHYS" ] && [ -d "$PHYS" ] || die "--physics-dir is required" +PHYS=$(cd "$PHYS" && pwd) +[ -z "$(git -C "$OMEGA" status --porcelain)" ] || die "omega tree is dirty; refusing" +COMMIT=$(git -C "$OMEGA" rev-parse HEAD) +LOCKED=$(tr -d ' \n' < "$OMEGA/physics.lock") +PHEAD=$(git -C "$PHYS" rev-parse HEAD) +[ "$PHEAD" = "$LOCKED" ] || die "physics checkout is at $PHEAD, physics.lock pins $LOCKED" +[ -z "$(git -C "$PHYS" status --porcelain)" ] || die "physics checkout is dirty" +command -v jq >/dev/null || die "jq missing" +mkdir -p "$EVID/blobs" +EVID=$(cd "$EVID" && pwd) +case "$EVID/" in "$OMEGA/"*|"$PHYS/"*) die "evidence dir must be outside the omega tree and physics checkout" ;; esac + +STARTED=$(date -u +%Y-%m-%dT%H:%M:%SZ) +B=$OMEGA/bench/prime_race/build +BIN=$B/gb10_native MUT=$B/gb10_native_mutant HT=$B/gb10_sieve_host_test +T=$(mktemp -d) || die "no temp dir" +LOG=$T/run.log +FAIL_REASON="" +log() { echo "$*" | tee -a "$LOG"; } + +(cd "$OMEGA" && nice -n 19 make -j1 PHYSICS_DIR="$PHYS" prime-race-gb10 bench/prime_race/build/gb10_sieve_host_test) > "$T/build.log" 2>&1 \ + || FAIL_REASON="build failed" +if [ -z "$FAIL_REASON" ]; then + for x in "$BIN" "$MUT"; do + nm -u "$x" | grep -Eiq 'cuda|cuInit|cuLaunch|nvrtc|cublas' && FAIL_REASON="CUDA symbols in $(basename "$x")" + done +fi +BIN_SHA=$( [ -f "$BIN" ] && sha256sum "$BIN" | cut -d' ' -f1 ) +MUT_SHA=$( [ -f "$MUT" ] && sha256sum "$MUT" | cut -d' ' -f1 ) +HOST_OK=false +if [ -z "$FAIL_REASON" ]; then + "$HT" >> "$LOG" 2>&1 && HOST_OK=true || FAIL_REASON="host test (simulator) failed" +fi + +NRUNS=0 NPASSES=0 MUTANT_CAUGHT=false TIMED_OK=false KERNEL_SHA="" +# run_audit LIMIT K BINARY -> 0 match, 1 mismatch, 2 run failed +run_audit() { + local L=$1 K=$2 X=$3 + rm -f "$T/got.bin" "$T/want.bin" "$T/rep.json" + "$X" --limit "$L" --min-seconds 0 --audit-passes "$K" --bitmap-out "$T/got.bin" --report-out "$T/rep.json" \ + > "$T/stdout" 2> "$T/stderr" + local rc=$? + NRUNS=$((NRUNS + 1)) + if [ $rc -ne 0 ]; then log "limit $L: $(basename "$X") exit $rc: $(tail -2 "$T/stderr" | tr '\n' ' ')"; return 2; fi + "$HT" --oracle "$L" "$T/want.bin" "$K" || { log "limit $L: oracle failed"; return 2; } + if ! cmp -s "$T/got.bin" "$T/want.bin"; then + log "limit $L: bitmap differs from oracle: $(cmp "$T/got.bin" "$T/want.bin" 2>&1 | head -1)"; return 1 + fi + NPASSES=$((NPASSES + K)) + return 0 +} + +if [ -z "$FAIL_REASON" ]; then + exec 9> /tmp/aien-gb10.lock || FAIL_REASON="cannot open /tmp/aien-gb10.lock" +fi +if [ -z "$FAIL_REASON" ]; then + # waits for the lock; no timeout; never killed + flock 9 + LOCK_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ) + log "GPU lock held from $LOCK_AT" + for L in $("$HT" --limits) 10000000; do + K=2; [ "$L" = 1000000 ] && K=5; [ "$L" = 10000000 ] && K=1 + run_audit "$L" "$K" "$BIN"; r=$? + [ $r -eq 0 ] || { FAIL_REASON="limit $L: $( [ $r = 1 ] && echo mismatch || echo run failed )"; break; } + [ "$L" = 1000000 ] && KERNEL_SHA=$(jq -r '.detail.kernel_code_sha256 // empty' "$T/rep.json" 2>/dev/null) + done + log "audit sweep: $NRUNS runs, $NPASSES passes checked" + if [ -z "$FAIL_REASON" ]; then + "$BIN" --limit 1000000 --min-seconds 2 --bitmap-out "$T/got.bin" --report-out "$T/timed.json" > "$T/timed.out" 2> "$T/timed.err" + rc=$? + "$HT" --oracle 1000000 "$T/want.bin" 1 + if [ $rc -eq 0 ] && [ "$(wc -l < "$T/timed.out")" = 1 ] \ + && grep -Eq '^aien-gb10-native;[1-9][0-9]*;[0-9]+\.[0-9]{6};[0-9]+;algorithm=other,faithful=no,bits=1$' "$T/timed.out" \ + && cmp -s "$T/got.bin" "$T/want.bin"; then + TIMED_OK=true; log "timed smoke: $(cat "$T/timed.out")" + else + FAIL_REASON="timed run at 1e6: exit $rc, line '$(head -1 "$T/timed.out")'" + fi + fi + if [ -z "$FAIL_REASON" ]; then + run_audit 1000000 1 "$MUT"; r=$? + if [ $r -eq 1 ]; then MUTANT_CAUGHT=true; log "mutant caught at 1e6" + else FAIL_REASON="mutant not caught at 1e6 (status $r)"; fi + fi + flock -u 9 +fi + +VERDICT=PASS; [ -z "$FAIL_REASON" ] || VERDICT=FAIL +LOG_SHA=$(sha256sum "$LOG" 2>/dev/null | cut -d' ' -f1) +[ -n "$LOG_SHA" ] && [ ! -e "$EVID/blobs/$LOG_SHA.log" ] && cp "$LOG" "$EVID/blobs/$LOG_SHA.log" && chmod 0444 "$EVID/blobs/$LOG_SHA.log" +jq -n --arg v "$VERDICT" --arg reason "$FAIL_REASON" --arg commit "$COMMIT" --arg physics "$PHEAD" \ + --arg started "$STARTED" --arg finished "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg bin "${BIN_SHA:-}" --arg mut "${MUT_SHA:-}" \ + --arg kernel "$KERNEL_SHA" --arg log "${LOG_SHA:-}" --argjson host "$HOST_OK" --argjson runs "$NRUNS" \ + --argjson passes "$NPASSES" --argjson mutant "$MUTANT_CAUGHT" --argjson timed "$TIMED_OK" \ + --arg gpu "$(nvidia-smi --query-gpu=name,uuid,driver_version --format=csv,noheader 2>/dev/null || echo unavailable)" \ + --arg kern "$(uname -r)" \ + '{schema:"aien-prime-race/gb10-chip-test/v1", verdict:$v, reason:$reason, omega_commit:$commit, physics_commit:$physics, + started:$started, finished:$finished, binary_sha256:$bin, mutant_binary_sha256:$mut, kernel_code_sha256:$kernel, + host_test_pass:$host, audit_runs:$runs, audit_passes_checked:$passes, timed_smoke_pass:$timed, mutant_caught:$mutant, + gpu:$gpu, kernel:$kern, gpu_lock:"/tmp/aien-gb10.lock", quiet_flag:"not touched (operator window)", + reference:"independent Eratosthenes oracle (gb10_sieve_host_test --oracle), byte-for-byte per pass", log_blob:$log}' \ + > "$T/receipt.json" +RSHA=$(sha256sum "$T/receipt.json" | cut -d' ' -f1) +if [ ! -e "$EVID/$RSHA.json" ]; then cp "$T/receipt.json" "$EVID/$RSHA.json" && chmod 0444 "$EVID/$RSHA.json"; fi +echo "run_gb10_chip: VERDICT $VERDICT ${FAIL_REASON:+($FAIL_REASON) }receipt=$EVID/$RSHA.json" +rm -rf "$T" +[ "$VERDICT" = PASS ] && exit 0 || exit 1 diff --git a/mk/.crumb b/mk/.crumb index 716798072..f8a8a27ac 100644 --- a/mk/.crumb +++ b/mk/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-05T16:48:41Z", + "compiled_at": "2026-10-05T18:58:51Z", "compiler": "crumb-compile/1", - "digest": "sha256:7a280ae41e1051f14529ab2c8b2749f4712ea37df87254fd90bfbc3e1bba2048", + "digest": "sha256:bf8aa4246cf9b4a9d21e0a57856079a75bced3f53adefae2584b428f8afbd07a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 56, - "generated_at_commit": "678ed89f7b0213130c92d20d481bf429414772e2", - "source_tree": "sha256:0fcc8e338cb26be5ab3c9d7d009c5cb65055a68e4e20ccaab359691ac79afc78" + "files": 58, + "generated_at_commit": "dc7a3d7a8c1997a0821c098fb862107d3fd54b9d", + "source_tree": "sha256:8c46fbfd97a0d6112b4dc8e6564fb8742e4f71bf52d550b66761fb3ef4168f8e" }, "owner_lane": "", "provenance": { diff --git a/mk/prime_race.mk b/mk/prime_race.mk new file mode 100644 index 000000000..e3072a4f7 --- /dev/null +++ b/mk/prime_race.mk @@ -0,0 +1,28 @@ +# AIEN Prime Drag Race (bench/prime_race/): implementation-side protocol + conventional CPU baseline. +# Standalone: new files only under bench/prime_race/. Picked up by `-include mk/*.mk`; not part of `all` +# or `test`. No physics, no GPU, no libraries. +# +# prime-race-cpu builds bench/prime_race/build/cpu_base (-O3 -mcpu=native; flags baked in via -D) +# prime-race-host-test trial-division oracle test of cpu_base + protocol formatting/parsing +ifndef PRIME_RACE_MK +PRIME_RACE_MK := 1 +.PHONY: prime-race-cpu prime-race-host-test +PR_DIR = bench/prime_race +PR_BUILD = $(PR_DIR)/build +PR_WARN = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE +PR_OPT = -O3 -mcpu=native +PR_SOURCE_COMMIT_VAL := $(shell git rev-parse HEAD 2>/dev/null || echo unknown) +PR_DEFS = -DPR_SOURCE_COMMIT='"$(PR_SOURCE_COMMIT_VAL)"' -DPR_CC='"$(CC)"' -DPR_CFLAGS='"$(PR_WARN) $(PR_OPT)"' +PR_HDRS = $(PR_DIR)/prime_race_impl.h + +$(PR_BUILD)/cpu_base: $(PR_DIR)/cpu_base.c $(PR_DIR)/prime_race_impl.c $(PR_HDRS) + @mkdir -p $(PR_BUILD) + $(CC) $(PR_WARN) $(PR_OPT) $(PR_DEFS) -o $@ $(PR_DIR)/cpu_base.c $(PR_DIR)/prime_race_impl.c -lm +prime-race-cpu: $(PR_BUILD)/cpu_base + +$(PR_BUILD)/prime_race_host_test: $(PR_DIR)/tests/prime_race_host_test.c $(PR_DIR)/cpu_base.c $(PR_DIR)/prime_race_impl.c $(PR_HDRS) + @mkdir -p $(PR_BUILD) + $(CC) $(PR_WARN) -O2 -DPR_NO_MAIN -o $@ $(PR_DIR)/tests/prime_race_host_test.c $(PR_DIR)/cpu_base.c $(PR_DIR)/prime_race_impl.c -lm +prime-race-host-test: $(PR_BUILD)/prime_race_host_test + ./$(PR_BUILD)/prime_race_host_test +endif diff --git a/mk/prime_race_gb10.mk b/mk/prime_race_gb10.mk new file mode 100644 index 000000000..0c78729f6 --- /dev/null +++ b/mk/prime_race_gb10.mk @@ -0,0 +1,45 @@ +# AIEN Prime Drag Race: native GB10 implementation (bench/prime_race/gb10_native.c) on Omega's +# own Blackwell codegen + session (libomega_gpu.a, no CUDA). Picked up by `-include mk/*.mk`; +# not part of `all` or `test`. Needs PHYSICS_DIR at the physics.lock commit (libomega_gpu). +# +# prime-race-gb10 build bench/prime_race/build/gb10_native (+ _mutant, the chip test's +# negative control) and refuse them if nm finds a CUDA symbol +# prime-race-gb10-host-test golden words, nvdisasm listing, host IR simulator sweep (no device) +# The chip test is bench/prime_race/tests/run_gb10_chip.sh (holds /tmp/aien-gb10.lock). +# prime-race-gb10-launch-cost build the DIAGNOSTIC per-launch cost tool (tests/gb10_launch_cost.c; +# chip launches need GB10_CHIP_RUN=1 and the GPU lock) +ifndef PRIME_RACE_GB10_MK +PRIME_RACE_GB10_MK := 1 +.PHONY: prime-race-gb10 prime-race-gb10-host-test prime-race-gb10-launch-cost +GB_DIR = bench/prime_race +GB_BUILD = $(GB_DIR)/build +GB_OPT = -O3 -mcpu=native +GB_SRC_COMMIT := $(shell git rev-parse HEAD 2>/dev/null || echo unknown) +GB_DEFS = -DPR_SOURCE_COMMIT='"$(GB_SRC_COMMIT)"' -DPR_CC='"$(CC)"' \ + -DPR_CFLAGS='"$(GB_OPT) -I$(GB_DIR) + omega CFLAGS; libomega_gpu.a built with omega CFLAGS"' +GB_DEPS = $(GB_DIR)/gb10_native.c $(GB_DIR)/prime_race_impl.c $(GB_DIR)/prime_race_impl.h \ + src/omega_gpu_elementwise_api.h src/omega_gpu_session.h $(OUT_DIR)/libomega_gpu.a +# Same pattern as tools/chip_run.sh REFUSAL:cuda +GB_NM_CHECK = if nm -u $@ | grep -Eiq 'cuda|cuInit|cuLaunch|nvrtc|cublas'; then echo "CUDA symbols in $@"; rm -f $@; exit 1; fi + +$(GB_BUILD)/gb10_native: $(GB_DEPS) + @mkdir -p $(GB_BUILD) + $(CC) $(CFLAGS) $(GB_OPT) -I$(GB_DIR) $(GB_DEFS) -o $@ $(GB_DIR)/gb10_native.c $(GB_DIR)/prime_race_impl.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm + @$(GB_NM_CHECK) +$(GB_BUILD)/gb10_native_mutant: $(GB_DEPS) + @mkdir -p $(GB_BUILD) + $(CC) $(CFLAGS) $(GB_OPT) -I$(GB_DIR) $(GB_DEFS) -DPR_GB10_MUTANT=1 -o $@ $(GB_DIR)/gb10_native.c $(GB_DIR)/prime_race_impl.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm + @$(GB_NM_CHECK) +prime-race-gb10: $(GB_BUILD)/gb10_native $(GB_BUILD)/gb10_native_mutant + +$(GB_BUILD)/gb10_sieve_host_test: $(GB_DIR)/tests/gb10_sieve_host_test.c $(GB_DIR)/prime_race_impl.h src/omega_blackwell_codegen.h src/omega_gpu_elementwise_api.h $(OUT_DIR)/libomega_gpu.a + @mkdir -p $(GB_BUILD) + $(CC) $(CFLAGS) -I$(GB_DIR) -o $@ $(GB_DIR)/tests/gb10_sieve_host_test.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm +prime-race-gb10-host-test: $(GB_BUILD)/gb10_sieve_host_test + ./$(GB_BUILD)/gb10_sieve_host_test +$(GB_BUILD)/gb10_launch_cost: $(GB_DIR)/tests/gb10_launch_cost.c src/omega_blackwell_codegen.h src/omega_gpu_elementwise_api.h src/omega_gpu_session.h $(OUT_DIR)/libomega_gpu.a + @mkdir -p $(GB_BUILD) + $(CC) $(CFLAGS) $(GB_OPT) -o $@ $(GB_DIR)/tests/gb10_launch_cost.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm + @$(GB_NM_CHECK) +prime-race-gb10-launch-cost: $(GB_BUILD)/gb10_launch_cost +endif diff --git a/src/.crumb b/src/.crumb index d0e514468..a0b0d90b0 100644 --- a/src/.crumb +++ b/src/.crumb @@ -134,7 +134,7 @@ }, { "digest": "63f3df62adf0a29ee2fdfdc4e170409de18f8a2a33c5644ab8d4009cf1c5246f", - "last_commit": "def0a0d", + "last_commit": "f816473", "name": "runtime", "purpose": "Directory src/runtime. Purpose not yet described by a human." }, @@ -170,14 +170,14 @@ } ], "children_root": "sha256:920218d42490379078986bd65f6d50e8ef9064df20da67bfc0ca50ea0de4b4c0", - "compiled_at": "2026-10-06T00:23:42Z", + "compiled_at": "2026-10-06T01:31:06Z", "compiler": "crumb-compile/1", - "digest": "sha256:bf667679bc7c3494f148e83e9d8f56193a3768c2f7145a614a21e701e3bddabd", + "digest": "sha256:c4d0989f06c0bcfd0bd58edabdf147c0894d0882fa12ed69c55c0440302f46dd", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 408, - "generated_at_commit": "fa18e58a86a7402de785e07044f5f444a1dcca3c", - "source_tree": "sha256:d171d30065cacc0d402c1013b920ad3cf4392e78ed56d71fd0fa4669a2ac865b" + "generated_at_commit": "39f93e5e6dbb405fcbaa276f4fc41fd9700d683d", + "source_tree": "sha256:dcee4fbb0262400359e7fa3054b55b6d26b98108bf59e0b8353713c1a1be9813" }, "owner_lane": "", "provenance": { diff --git a/src/omega_blackwell_codegen.c b/src/omega_blackwell_codegen.c index 560f8ef45..3873cfd7d 100644 --- a/src/omega_blackwell_codegen.c +++ b/src/omega_blackwell_codegen.c @@ -701,12 +701,82 @@ static int encode_single_insn(const BlackwellIRInsn *insn, const OmegaRegAlloc * w[3] = insn->control ? insn->control : 0x000fe200; break; + /* Prime race cut (2026-10-05). An absent operand is RZ for these three ops. */ + case BW_IR_LOP3_LUT: { + /* LOP3.LUT Rd, Ra, Rb, Rc, imm8, !PT. LOP3_XOR above is this form with Rc = RZ, LUT 0x3c. */ + uint32_t a = (insn->src1_vreg >= 0) ? (uint32_t)(src1 & 0xff) : 0xffU; + uint32_t b = (insn->src2_vreg >= 0) ? (uint32_t)(src2 & 0xff) : 0xffU; + w[0] = 0x7212U | ((uint32_t)(dst & 0xff) << 16) | (a << 24); + w[1] = b; + w[2] = 0x078e0000U | ((insn->imm & 0xffU) << 8) | (uint32_t)(src3 & 0xff); + w[3] = insn->control ? insn->control : 0x001fca00; + break; + } + + case BW_IR_SHF_L_U32: { + /* SHF.L.U32 Rd, Ra, Rb, Rc: register-amount form (0x7219) of SHF_R's 0x7819, with the + * .R (w[2] bit 12) and .HI (bit 16) flags clear. Rc is the funnel high word (RZ). */ + uint32_t a = (insn->src1_vreg >= 0) ? (uint32_t)(src1 & 0xff) : 0xffU; + uint32_t b = (insn->src2_vreg >= 0) ? (uint32_t)(src2 & 0xff) : 0xffU; + w[0] = 0x7219U | ((uint32_t)(dst & 0xff) << 16) | (a << 24); + w[1] = b; + w[2] = 0x00000600U | (uint32_t)(src3 & 0xff); + w[3] = insn->control ? insn->control : 0x001fca00; + break; + } + + case BW_IR_IMAD_HI_U32: { + /* IMAD.HI.U32 Rd, Ra, Rb, Rc: opcode 0x227 with the IMAD.WIDE.U32 modifier word. */ + uint32_t a = (insn->src1_vreg >= 0) ? (uint32_t)(src1 & 0xff) : 0xffU; + uint32_t b = (insn->src2_vreg >= 0) ? (uint32_t)(src2 & 0xff) : 0xffU; + w[0] = 0x7227U | ((uint32_t)(dst & 0xff) << 16) | (a << 24); + w[1] = b; + w[2] = 0x078e0000U | (uint32_t)(src3 & 0xff); + w[3] = insn->control ? insn->control : 0x001fca00; + break; + } + default: return -1; } return 0; } +/* Prime race cut (2026-10-05): golden words for LOP3_LUT, SHF_L_U32 and IMAD_HI_U32. + * Each expected (w0, w1, w2) is the low 96 bits of an instruction nvcc 13.0.88 emitted + * for sm_121 (nvcc -arch=sm_121 -cubin, cuobjdump -sass; source and dump in + * bench/prime_race/tests/encoding_oracle.md). Control words (w3) are scheduler output and + * not compared. nvcc is an offline oracle only; nothing here links CUDA. 0 = all good. */ +int omega_blackwell_verify_codegen_fixtures_intops(void) { + OmegaRegAlloc ra; + memset(&ra, 0, sizeof(ra)); + static const int phys[] = { 0, 2, 6, 7, 9, 11, 13 }; + for (int i = 0; i < (int)(sizeof phys / sizeof phys[0]); i++) ra.vreg_to_phys[i] = phys[i]; + enum { R0 = 0, R2, R6, R7, R9, R11, R13, RZ = -1 }; + static const struct { + BlackwellIROpcode op; int d, a, b, c; uint32_t imm; uint32_t w0, w1, w2; const char *text; + } fx[] = { + { BW_IR_LOP3_LUT, R9, R7, R0, RZ, 0xfc, 0x07097212U, 0x00000000U, 0x078efcffU, "LOP3.LUT R9, R7, R0, RZ, 0xfc, !PT" }, + { BW_IR_LOP3_LUT, R11, R6, R7, R0, 0x78, 0x060b7212U, 0x00000007U, 0x078e7800U, "LOP3.LUT R11, R6, R7, R0, 0x78, !PT" }, + { BW_IR_LOP3_LUT, R13, R6, R7, R0, 0x10, 0x060d7212U, 0x00000007U, 0x078e1000U, "LOP3.LUT R13, R6, R7, R0, 0x10, !PT" }, + { BW_IR_LOP3_LUT, R7, RZ, R9, RZ, 0x33, 0xff077212U, 0x00000009U, 0x078e33ffU, "LOP3.LUT R7, RZ, R9, RZ, 0x33, !PT" }, + { BW_IR_SHF_L_U32, R7, R9, R2, RZ, 0, 0x09077219U, 0x00000002U, 0x000006ffU, "SHF.L.U32 R7, R9, R2, RZ" }, + { BW_IR_SHF_L_U32, R7, R0, R7, RZ, 0, 0x00077219U, 0x00000007U, 0x000006ffU, "SHF.L.U32 R7, R0, R7, RZ" }, + { BW_IR_IMAD_HI_U32, R9, R9, R0, R6, 0, 0x09097227U, 0x00000000U, 0x078e0006U, "IMAD.HI.U32 R9, R9, R0, R6" }, + { BW_IR_IMAD_HI_U32, R7, R0, R7, RZ, 0, 0x00077227U, 0x00000007U, 0x078e00ffU, "IMAD.HI.U32 R7, R0, R7, RZ" }, + }; + for (int i = 0; i < (int)(sizeof fx / sizeof fx[0]); i++) { + BlackwellIRInsn in; + memset(&in, 0, sizeof in); + in.op = fx[i].op; in.dst_vreg = fx[i].d; in.src1_vreg = fx[i].a; in.src2_vreg = fx[i].b; + in.src3_vreg = fx[i].c; in.ureg = -1; in.imm = fx[i].imm; + uint32_t w[4]; + if (encode_single_insn(&in, &ra, w) != 0) return -(2 * i + 1); + if (w[0] != fx[i].w0 || w[1] != fx[i].w1 || w[2] != fx[i].w2) return -(2 * i + 2); + } + return 0; +} + /* FB-1 cut 4: word-level fixtures for the four additive ops (checked against the * nvdisasm decodes recorded in docs/numeric/FB1_CUT4_ELEMENTWISE.md). 0 = all good. */ int omega_blackwell_verify_codegen_fixtures_fb1cut4(void) { diff --git a/src/omega_blackwell_codegen.h b/src/omega_blackwell_codegen.h index b0828b26d..8cbfedf73 100644 --- a/src/omega_blackwell_codegen.h +++ b/src/omega_blackwell_codegen.h @@ -71,7 +71,18 @@ typedef enum { BW_IR_MUFU_EX2, /* MUFU.EX2 Rd, Ra (2^x, approximate: PTX ex2.approx.f32 bound 2^-22.5 rel) */ BW_IR_BAR_SYNC, /* BAR.SYNC.DEFER_BLOCKING 0x0 (CTA barrier 0; the QMD declares 1 barrier) */ BW_IR_LDS32, /* LDS Rd, [Ra+URZ] 32-bit shared load (BW_IR_LDS encodes LDS.U8: byte) */ - BW_IR_STS32 /* STS [Ra+URZ], Rb 32-bit shared store (BW_IR_STS encodes STS.U8: byte) */ + BW_IR_STS32, /* STS [Ra+URZ], Rb 32-bit shared store (BW_IR_STS encodes STS.U8: byte) */ + /* Prime race cut (2026-10-05), additive, general integer ops. Words derived from the + * register forms of LOP3_XOR / SHF_R / IMAD and matched word for word against + * nvcc 13.0.88 -arch=sm_121 -cubin + cuobjdump -sass (offline oracle only; see + * omega_blackwell_verify_codegen_fixtures_intops). For these three ops an operand + * vreg of -1 encodes RZ (not R0). */ + BW_IR_LOP3_LUT, /* LOP3.LUT Rd, Ra, Rb, Rc, imm8, !PT: Rd = LUT(Ra, Rb, Rc). imm & 0xff is the + * truth table over Ra = 0xf0, Rb = 0xcc, Rc = 0xaa (a|b = 0xfc, ~(a|b) = 0x03) */ + BW_IR_SHF_L_U32, /* SHF.L.U32 Rd, Ra, Rb, RZ: Rd = Ra << Rb, register amount (the form nvcc emits + * for PTX shl.b32). Amounts >= 32 are NOT chip-verified: callers keep Rb < 32 */ + BW_IR_IMAD_HI_U32 /* IMAD.HI.U32 Rd, Ra, Rb, Rc: Rd = hi32(Ra * Rb) + Rc mod 2^32 (nvcc emits this + * word for __umulhi(a, b) + c) */ } BlackwellIROpcode; /* Special Register Identifiers */ @@ -189,6 +200,9 @@ int omega_blackwell_verify_codegen_fixtures(void); /* FB-1 cut 4: fixtures for MUFU_EX2, BAR_SYNC, LDS32, STS32 (0 = pass) */ int omega_blackwell_verify_codegen_fixtures_fb1cut4(void); +/* Prime race cut: golden words for LOP3_LUT, SHF_L_U32, IMAD_HI_U32 (0 = pass) */ +int omega_blackwell_verify_codegen_fixtures_intops(void); + /* Unit test for bounded register allocation live intervals and bounds enforcement (Gate 4) */ int omega_blackwell_test_regalloc_bounds(void); diff --git a/src/omega_gpu_elementwise_api.c b/src/omega_gpu_elementwise_api.c index 3d5970ce2..7b48b0a39 100644 --- a/src/omega_gpu_elementwise_api.c +++ b/src/omega_gpu_elementwise_api.c @@ -47,6 +47,8 @@ typedef struct { int err; int loop_start[EW_MAX_LOOPS], loop_end[EW_MAX_LOOPS]; int n_loops; + int open_start[EW_MAX_LOOPS]; /* starts of loops begun and not yet ended (nesting stack) */ + int depth; } Em; static void emit(Em *e, BlackwellIRInsn in, int kind) { @@ -112,15 +114,19 @@ static void tail(Em *e) { self.control = 0x000fc000u; if (omega_bw_ir_append(e->p, &self) < 0) e->err = -1; } -static void loop_begin(Em *e) { if (e->n_loops < EW_MAX_LOOPS) e->loop_start[e->n_loops] = here(e); } +/* Loops may nest (prime race cut): begin pushes the start, end pops it, so the inner + * loop is closed (and its liveness fixed) first. For the single-level loops above this + * is exactly the old behaviour. */ +static void loop_begin(Em *e) { if (e->depth >= EW_MAX_LOOPS) { e->err = -1; return; } e->open_start[e->depth++] = here(e); } /* Closing a loop: every value defined before the loop and read inside it stays * live until the back-branch, otherwise the linear-scan allocator (which knows * nothing about back-edges) would hand its register to a body temporary whose * first definition comes after the value's last textual use (e.g. the scale y * in rmsnorm pass 2), and the next iteration would read garbage. */ static void loop_end(Em *e) { - if (e->n_loops >= EW_MAX_LOOPS) { e->err = -1; return; } - int start = e->loop_start[e->n_loops], end = here(e) - 1; + if (e->n_loops >= EW_MAX_LOOPS || e->depth <= 0) { e->err = -1; return; } + int start = e->open_start[--e->depth], end = here(e) - 1; + e->loop_start[e->n_loops] = start; e->loop_end[e->n_loops] = end; e->n_loops++; OmegaRegAlloc *ra = &e->p->regalloc; @@ -299,6 +305,124 @@ static void gen_swiglu(Em *e, int mutant) { tail(e); } +/* ------------------------------------------- prime race sieve (2026-10-05) */ +static void lop3lut(Em *e, int d, int a, int b, int c, uint32_t lut) { BlackwellIRInsn i = I0(BW_IR_LOP3_LUT); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; i.src3_vreg = c; i.imm = lut & 0xffu; emit(e, i, K_FIXED); } +static void shl_r(Em *e, int d, int a, int n) { BlackwellIRInsn i = I0(BW_IR_SHF_L_U32); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = n; emit(e, i, K_FIXED); } +static void shr_i(Em *e, int d, int a, uint32_t n) { BlackwellIRInsn i = I0(BW_IR_SHF_R); i.dst_vreg = d; i.src1_vreg = a; i.imm = n; emit(e, i, K_FIXED); } +static void imadhi(Em *e, int d, int a, int b) { BlackwellIRInsn i = I0(BW_IR_IMAD_HI_U32); i.dst_vreg = d; i.src1_vreg = a; i.src2_vreg = b; emit(e, i, K_FIXED); } +/* dst64 = a * imm + c64 (IMAD.WIDE.U32 immediate form) */ +static void widei(Em *e, int dst64, int a, uint32_t imm, int c64) { BlackwellIRInsn i = I0(BW_IR_IMAD_WIDE); i.dst_vreg = dst64; i.src1_vreg = a; i.imm = imm; i.src3_vreg = c64; emit(e, i, K_FIXED); } +/* @P0 BRA forward; returns the instruction index for bra_patch_here */ +static int bra_fwd_if_p0(Em *e) { int at = here(e); BlackwellIRInsn i = I0(BW_IR_BRA); i.predicate_p0 = true; i.imm = 1; emit(e, i, K_BRA); return at; } +static void bra_patch_here(Em *e, int at) { if (e->err == 0 && at >= 0 && at < here(e)) e->p->insns[at].imm = (uint32_t)(here(e) - at); else e->err = -1; } +static void bra_always(Em *e, int target) { BlackwellIRInsn i = I0(BW_IR_BRA); i.imm = (uint32_t)(target - here(e)); emit(e, i, K_BRA); } + +/* Word-parallel odd-only sieve (docs: handoff 2026-10-05 DESIGN "GPU kernel (native)"). + * Thread t owns 32-bit output words w = t, t + S, t + 2S, ... (S = P1 = threads launched; + * the I42 envelope caps a launch at OMEGA_GPU_EW_MAX_CTAS CTAs, so a grid-stride loop + * replaces one thread per word). Every word has exactly one writer; no atomics. + * Bit j of word w is the odd number 2(32w + j) + 1. + * Arguments: a (0x380) = prime table, entries {p, magic = ceil(2^32 / p), k0 = (p*p - 1)/2} + * (12 bytes, ascending p, odd primes <= isqrt(limit)) followed by ONE sentinel entry with + * k0 = 0xffffffff that ends every scan; c (0x390) = output words; + * P0 = nwords, P1 = S, P2 = last word index, P3 = ~tailmask (bits past the last odd). + * Range: limit < 2^32 (so base, k0 < 2^31 and the sign-bit tricks below hold). + * Per word: base = 32w; for each prime while k0 < base + 32: + * d = base - k0; neg = d >> 31 (k0 > base); dpos = neg ? 0 : d; jadd = neg ? k0 - base : 0 + * q = hi32(dpos * magic) (= floor(dpos/p) or one more: magic is rounded up) + * r = dpos - q*p (q one too big -> r = (dpos mod p) - p, wrapped) + * j = p - r; j -= p * ((r - 1) >> 31) (r == 0 -> 0; wrapped r -> p - (dpos mod p)) + * One fix covers both cases: with q one too big, dpos mod p >= p - dpos*e/2^32 > p/2 > 0 + * (e = magic*p - 2^32 < p, dpos < 2^31), so the true remainder is never 0 there and + * p - r - p = p - (dpos mod p) is the right offset. A separate "r += p if wrapped" step was + * removed after a negative control showed it changes no output (host sim, limit 1e7, where + * the overshoot occurs 268 times; bench/prime_race/tests magic_model). + * j += jadd; while j < 32 { acc |= 1 << j; j += p } + * then acc |= (w == 0) (the number 1), word = ~(acc | (w == last ? ~tailmask : 0)). + * Branch-free except the loop branches. Mutant: drops the j fix (j = p - r unreduced), so words where + * base - k0 is a multiple of p (or q overshot) mark the wrong bits. */ +static void gen_prime_sieve(Em *e, int mutant) { + Pro pr = prologue(e); + int nwords = V(e), stride = V(e), lastw = V(e), tailinv = V(e); + int one = V(e), c32 = V(e), cm1 = V(e), w = V(e); + ldc32(e, nwords, ARG_P0); ldc32(e, stride, ARG_P1); ldc32(e, lastw, ARG_P2); ldc32(e, tailinv, ARG_P3); + movi(e, one, 1); movi(e, c32, 32); movi(e, cm1, 0xffffffffu); + imadi(e, w, pr.cta, OMEGA_GPU_EW_THREADS, pr.tid); + isetp_ge_u32(e, w, nwords); + exit_if_p0(e); + + int base = V(e), basep32 = V(e), acc = V(e), ptr = V64(e), a64 = V64(e); + int p = V(e), magic = V(e), k0 = V(e), negp = V(e), d = V(e), neg = V(e), nd = V(e), dpos = V(e), jadd = V(e); + int q = V(e), r = V(e), j = V(e), t = V(e), z = V(e), bit = V(e); + int e1 = V(e), m = V(e), word = V(e), oaddr = V64(e); + + loop_begin(e); /* word loop */ + int lw = here(e); + imadi(e, base, w, 32, NOREG); + iadd3(e, basep32, base, c32); + movrz(e, acc); + widei(e, ptr, one, 0, pr.pa); + + loop_begin(e); /* prime loop */ + int lp = here(e); + widei(e, a64, one, 8, ptr); + ldg(e, k0, a64, pr.udesc); + isetp_ge_u32(e, k0, basep32); + int brk = bra_fwd_if_p0(e); + ldg(e, p, ptr, pr.udesc); + widei(e, a64, one, 4, ptr); + ldg(e, magic, a64, pr.udesc); + imadi(e, negp, p, 0xffffffffu, NOREG); /* -p */ + imadi(e, d, k0, 0xffffffffu, base); /* base - k0 */ + shr_i(e, neg, d, 31); + imadi(e, nd, d, 0xffffffffu, NOREG); /* -d */ + imadr(e, dpos, neg, nd, d); /* d - neg*d */ + imadr(e, jadd, neg, nd, NOREG); /* neg * (k0 - base) */ + imadhi(e, q, dpos, magic); + imadr(e, r, q, negp, dpos); /* dpos - q*p */ + imadi(e, j, r, 0xffffffffu, p); /* p - r */ + if (!mutant) { + iadd3(e, t, r, cm1); + shr_i(e, z, t, 31); /* r == 0, or r wrapped (q one too big) */ + imadr(e, j, z, negp, j); /* j - p */ + } + iadd3(e, j, j, jadd); + + loop_begin(e); /* mark loop */ + int li = here(e); + isetp_ge_u32(e, j, c32); + int done = bra_fwd_if_p0(e); + shl_r(e, bit, one, j); + lop3lut(e, acc, acc, bit, NOREG, 0xfc); /* acc | bit */ + iadd3(e, j, j, p); + bra_always(e, li); + loop_end(e); + bra_patch_here(e, done); + + widei(e, ptr, one, 12, ptr); + bra_always(e, lp); + loop_end(e); + bra_patch_here(e, brk); + + iadd3(e, t, w, cm1); + shr_i(e, z, t, 31); /* w == 0: the number 1 is not prime */ + lop3lut(e, acc, acc, z, NOREG, 0xfc); + lop3xor(e, e1, w, lastw); + iadd3(e, t, e1, cm1); + shr_i(e, z, t, 31); /* w == last word */ + imadr(e, m, z, tailinv, NOREG); + lop3lut(e, word, acc, m, NOREG, 0x03); /* ~(acc | m) */ + addr4(e, oaddr, w, pr.pc); + stg(e, oaddr, word, pr.udesc); + /* IMAD, not IADD3: the IADD3 encoder ignores the scheduler control word (fixed + * 0x010fca00), so right after a store it would not wait on the read barrier */ + imadr(e, w, stride, one, w); + isetp_ge_u32(e, w, nwords); + bra_back_if_not_p0(e, lw); + loop_end(e); + tail(e); +} + /* A value first defined inside a loop body may not be read after the loop * before it is written again: the allocator could have let a later body * temporary share its register, and the last iteration's value would be lost. */ @@ -319,7 +443,7 @@ static int check_loop_invariant(const Em *e) { #define EW_GPR_BUDGET 64u /* the QMD declares 64 registers, as the matmul launcher does */ -static int build_kernel(OmegaGpuEwOp op, int mutant, OmegaBlackwellKernel *kernel) { +static int build_kernel(OmegaGpuEwOp op, int mutant, OmegaBlackwellKernel *kernel, BlackwellIRProgram *prog_out) { BlackwellIRProgram *prog = calloc(1, sizeof *prog); if (!prog) return OMEGA_GPU_EW_CODEGEN_FAIL; omega_bw_ir_init(prog); @@ -330,6 +454,7 @@ static int build_kernel(OmegaGpuEwOp op, int mutant, OmegaBlackwellKernel *kerne case OMEGA_GPU_EW_RMSNORM: gen_rmsnorm(&e, mutant); break; case OMEGA_GPU_EW_ROPE: gen_rope(&e, mutant); break; case OMEGA_GPU_EW_SWIGLU: gen_swiglu(&e, mutant); break; + case OMEGA_GPU_EW_PRIME_SIEVE: gen_prime_sieve(&e, mutant); break; default: e.err = -1; break; } int rc = OMEGA_GPU_EW_CODEGEN_FAIL; @@ -350,6 +475,7 @@ static int build_kernel(OmegaGpuEwOp op, int mutant, OmegaBlackwellKernel *kerne kernel->gpr_count = prog->regalloc.peak_gpr_usage; kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage; sha256_hash(kernel->code, kernel->code_size, kernel->code_digest); + if (prog_out) *prog_out = *prog; rc = OMEGA_GPU_EW_OK; } else { #ifdef OMEGA_EW_DEBUG @@ -407,7 +533,7 @@ static int kernel_for(OmegaGpuEwOp op, bool upload, Slot **out, bool *hit) { if (g_cache[i].used && g_cache[i].op == (int)op && g_cache[i].mutant == mutant) { s = &g_cache[i]; *hit = true; break; } if (!s) { OmegaBlackwellKernel k; - int rc = build_kernel(op, mutant, &k); + int rc = build_kernel(op, mutant, &k, NULL); if (rc != OMEGA_GPU_EW_OK) return rc; size_t slot = 0; for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; } @@ -432,7 +558,12 @@ int omega_gpu_elementwise_codegen(OmegaGpuEwOp op, const uint32_t *dims, float e LOCK(); int mutant = (g_mutant_op == (int)op); UNLOCK(); - return build_kernel(op, mutant, kernel); + return build_kernel(op, mutant, kernel, NULL); +} + +int omega_gpu_elementwise_codegen_ir(OmegaGpuEwOp op, int mutant, void *prog, OmegaBlackwellKernel *kernel) { + if (!kernel) return OMEGA_GPU_EW_BAD_ARGS; + return build_kernel(op, mutant ? 1 : 0, kernel, (BlackwellIRProgram *)prog); } const char *omega_gpu_elementwise_last_error(void) { return omega_gpu_session_last_error(); } diff --git a/src/omega_gpu_elementwise_api.h b/src/omega_gpu_elementwise_api.h index a21710bb4..cf41877ec 100644 --- a/src/omega_gpu_elementwise_api.h +++ b/src/omega_gpu_elementwise_api.h @@ -59,7 +59,10 @@ typedef enum { OMEGA_GPU_EW_XCHG, /* out[i] = a[i ^ (T-1)] inside each CTA (probe for STS/BAR.SYNC/LDS) */ OMEGA_GPU_EW_RMSNORM, OMEGA_GPU_EW_ROPE, - OMEGA_GPU_EW_SWIGLU + OMEGA_GPU_EW_SWIGLU, + OMEGA_GPU_EW_PRIME_SIEVE /* prime race (2026-10-05): word-parallel odd-only sieve, codegen only + * here; launched by bench/prime_race/gb10_native.c (argument words in + * gen_prime_sieve's comment) */ } OmegaGpuEwOp; /* Shape rules (checked, refused with BAD_ARGS / TOO_LARGE): @@ -113,6 +116,13 @@ int omega_gpu_shared_xchg_u32(uint32_t n, const uint32_t *x, uint32_t *out, Omeg int omega_gpu_elementwise_codegen(OmegaGpuEwOp op, const uint32_t *dims, float eps, OmegaBlackwellKernel *kernel); +/* Same, with the mutant chosen by the caller (0 = production kernel) and, when prog is + * not NULL, a copy of the allocated IR program (a BlackwellIRProgram, post register + * allocation) for a host IR simulator. Does not touch the device or the kernel cache. + * Caller frees kernel->code. */ +int omega_gpu_elementwise_codegen_ir(OmegaGpuEwOp op, int mutant, void *prog, + OmegaBlackwellKernel *kernel); + /* TEST ONLY. Selects a deliberately wrong kernel for one op (0 clears). Each * mutant changes the math by far more than the op's tolerance, so a parity * check that still passes against it proves nothing. Clears the kernel cache. ```