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
GitHub aien-dev/omega-mv#263 (code only)
Apply it
git checkout -b patch-a4a358f322782144 bceec7b38a1d8f9f93ef195100f016fd8ded87b4 curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/a4a358f322782144.patch | git am
Provenance
github-import 1
aien-dev/omega-mv
263
6f7a644b023ce3912ace9f338d3530eef0c0afdd
{"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":263,"url":"https://github.com/aien-dev/omega-mv/pull/263","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:01Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/Makefile b/Makefile index 609922011..2fa3b810f 100644 --- a/Makefile +++ b/Makefile @@ -19,7 +19,7 @@ SRCS = src/sha256.c src/omega_canonical.c src/omega_validate.c src/omega_core.c src/omega_library.c src/omega_discovery.c src/omega_machine.c src/omega_realize_synth.c \ src/omega_matvec.c src/omega_accelerator.c src/omega_accelerator_world.c \ src/omega_vector.c src/omega_blackwell_encoder.c src/omega_blackwell_qmd.c \ - src/omega_blackwell_realize.c src/omega_blackwell_submit.c src/omega_blackwell_engine.c src/omega_gpu_engine.c src/omega_blackwell_gates.c src/omega_blackwell_matmul.c src/omega_blackwell_codegen.c src/omega_gpu_matmul_api.c src/omega_gpu_elementwise_api.c src/omega_gpu_attention_api.c src/omega_world_gates.c src/omega_gpu_wait.c \ + src/omega_blackwell_realize.c src/omega_blackwell_submit.c src/omega_blackwell_engine.c src/omega_gpu_engine.c src/omega_blackwell_gates.c src/omega_blackwell_matmul.c src/omega_blackwell_codegen.c src/omega_gpu_session.c src/omega_gpu_matmul_api.c src/omega_gpu_elementwise_api.c src/omega_gpu_attention_api.c src/omega_world_gates.c src/omega_gpu_wait.c \ src/omega_evidence.c \ $(PHYSICS_DIR)/m16/m16_native.c $(PHYSICS_DIR)/nvrm/nvrm.c \ tools/omegatool.c @@ -2167,3 +2167,7 @@ $(GPU_ATTN_TEST): tests/gpu_attention_test.c src/omega_gpu_attention_api.h $(OUT test-gpu-attention: $(GPU_ATTN_TEST) ./$(GPU_ATTN_TEST) --host-only ./$(GPU_ATTN_TEST) --sim + +# FB-1 cut 4b: fresh-process device-open probe (flake investigation, tools/probe_gpu_open.sh) +$(OUT_DIR)/gpu_session_probe: tests/gpu_session_probe.c src/omega_gpu_session.h $(OUT_DIR)/libomega_gpu.a + $(CC) $(CFLAGS) -o $@ tests/gpu_session_probe.c $(OUT_DIR)/libomega_gpu.a -lpthread -lm diff --git a/src/omega_gpu_attention_api.c b/src/omega_gpu_attention_api.c index 1425f8e9d..cdba59416 100644 --- a/src/omega_gpu_attention_api.c +++ b/src/omega_gpu_attention_api.c @@ -27,10 +27,9 @@ #include "omega_blackwell_codegen.h" #include "omega_blackwell_qmd.h" #include "omega_blackwell_submit.h" -#include "m16_native.h" +#include "omega_gpu_session.h" #include "sha256.h" #include <math.h> -#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -399,199 +398,159 @@ static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellI /* --------------------------------------------------------- kernel cache */ +/* One kernel per KSpec; the device copy is uploaded once and stays resident for + * the process (cut 4b). The IR program is kept for the host simulator. */ static int g_mutant; -typedef struct { int used; KSpec k; OmegaBlackwellKernel kernel; BlackwellIRProgram *prog; } Slot; +typedef struct { int used; KSpec k; OmegaBlackwellKernel kernel; BlackwellIRProgram *prog; NvrmMem code; } Slot; static OmegaGpuAttnSim g_sim; static Slot g_cache[8]; -static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER; -void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim) { pthread_mutex_lock(&g_mu); g_sim = sim; pthread_mutex_unlock(&g_mu); } +static OmegaGpuScratch g_q, g_pool, g_tab, g_out; /* staging, grown to the high-water mark, reused per call */ +static bool g_hooked; +#define LOCK() omega_gpu_session_lock() +#define UNLOCK() omega_gpu_session_unlock() -void omega_gpu_attention_cache_clear(void) { - pthread_mutex_lock(&g_mu); +void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim) { LOCK(); g_sim = sim; UNLOCK(); } + +static void cache_clear_locked(void) { for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) - if (g_cache[i].used) { free(g_cache[i].kernel.code); free(g_cache[i].prog); memset(&g_cache[i], 0, sizeof g_cache[i]); } - pthread_mutex_unlock(&g_mu); + if (g_cache[i].used) { free(g_cache[i].kernel.code); free(g_cache[i].prog); omega_gpu_session_free(&g_cache[i].code); memset(&g_cache[i], 0, sizeof g_cache[i]); } +} + +void omega_gpu_attention_cache_clear(void) { + LOCK(); + cache_clear_locked(); + UNLOCK(); +} + +/* Called by the session (lock held, device still open) right before it closes. */ +static void on_session_close(void) { + cache_clear_locked(); + omega_gpu_session_scratch_free(&g_q); omega_gpu_session_scratch_free(&g_pool); + omega_gpu_session_scratch_free(&g_tab); omega_gpu_session_scratch_free(&g_out); } void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m) { - pthread_mutex_lock(&g_mu); + LOCK(); g_mutant = (int)m; - pthread_mutex_unlock(&g_mu); - omega_gpu_attention_cache_clear(); + cache_clear_locked(); + UNLOCK(); } -static int kernel_for(bool f32, uint32_t log2bs, uint32_t log2gqa, OmegaBlackwellKernel *out, const BlackwellIRProgram **prog, bool *hit) { - pthread_mutex_lock(&g_mu); +/* Caller holds the lock. Builds the kernel if needed; uploads the device copy when + * `upload` (the chip path; the simulator never needs one). */ +static int kernel_for(bool f32, uint32_t log2bs, uint32_t log2gqa, bool upload, Slot **out, bool *hit) { KSpec k = { .f32 = f32, .log2bs = log2bs, .log2gqa = log2gqa, .mutant = g_mutant }; + Slot *s = NULL; for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (g_cache[i].used && g_cache[i].k.f32 == k.f32 && g_cache[i].k.log2bs == k.log2bs && g_cache[i].k.log2gqa == k.log2gqa && g_cache[i].k.mutant == k.mutant) { /* field compare: memcmp would read struct padding */ - *out = g_cache[i].kernel; *prog = g_cache[i].prog; *hit = true; pthread_mutex_unlock(&g_mu); return OMEGA_GPU_ATTN_OK; + s = &g_cache[i]; *hit = true; break; } - OmegaBlackwellKernel kern; BlackwellIRProgram *kp = NULL; - int rc = build_kernel(&k, &kern, &kp); - if (rc == OMEGA_GPU_ATTN_OK) { - size_t slot = sizeof g_cache / sizeof g_cache[0]; + if (!s) { + OmegaBlackwellKernel kern; BlackwellIRProgram *kp = NULL; + int rc = build_kernel(&k, &kern, &kp); + if (rc != OMEGA_GPU_ATTN_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; } - if (slot == sizeof g_cache / sizeof g_cache[0]) { slot = 0; free(g_cache[0].kernel.code); free(g_cache[0].prog); } - g_cache[slot].used = 1; g_cache[slot].k = k; g_cache[slot].kernel = kern; g_cache[slot].prog = kp; - *out = kern; *prog = kp; *hit = false; + s = &g_cache[slot]; + if (s->used) { free(s->kernel.code); free(s->prog); omega_gpu_session_free(&s->code); } /* full: evict slot 0 */ + memset(s, 0, sizeof *s); + s->used = 1; s->k = k; s->kernel = kern; s->prog = kp; + *hit = false; } - pthread_mutex_unlock(&g_mu); - return rc; + if (upload && !s->code.cpu) { + if (omega_gpu_session_alloc(s->kernel.code_size, &s->code) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; + memcpy(s->code.cpu, s->kernel.code, s->kernel.code_size); + __asm__ volatile("dsb sy" ::: "memory"); + } + *out = s; + return OMEGA_GPU_ATTN_OK; } int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, OmegaBlackwellKernel *kernel) { if (!kernel || log2_block_size > 16 || log2_gqa > 6) return OMEGA_GPU_ATTN_BAD_ARGS; - pthread_mutex_lock(&g_mu); + LOCK(); KSpec k = { .f32 = kv_f32, .log2bs = log2_block_size, .log2gqa = log2_gqa, .mutant = g_mutant }; - pthread_mutex_unlock(&g_mu); + UNLOCK(); return build_kernel(&k, kernel, NULL); } +const char *omega_gpu_attention_last_error(void) { return omega_gpu_session_last_error(); } + /* ------------------------------------------------------------ launcher */ #define AT_POISON 0xffbadbadu #define AT_WAIT_MS 600000ull -static const uint32_t SETUP_WORDS[18] = { - 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, - 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000, - 0x20012559, 0x00000000, -}; - 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 size_t page_round(size_t b) { b = (b + 0xFFFULL) & ~0xFFFULL; return b < 0x1000 ? 0x1000 : b; } typedef OmegaGpuAttnLaunch Launch; -/* One launch. Cloned from cut 4's run_abc (itself from omega_blackwell_execute_matmul_tensor): - * every buffer GPU-uncached, shader caches invalidated (cut 1b), first marker, L2_FLUSH_DIRTY, - * second marker, readback, poison scan. */ -static int run_launch(const OmegaBlackwellKernel *kernel, const Launch *L, OmegaGpuAttnInfo *info) { - M16NativeContext ctx; - if (m16_native_open(&ctx) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; - if (m16_native_create_channel(&ctx) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; } - NvrmMem large_pb; - if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x10000, &large_pb) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; } - ctx.pb_mem = large_pb; - - NvrmMem code_mem, cbank_mem, q_mem, pool_mem, tab_mem, out_mem, marker_mem, qmd_mem; -#define AT_ALLOC(mem, bytes) if (nvrm_alloc_gpu_uncached(&ctx.rm, (bytes), &(mem)) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; } - AT_ALLOC(code_mem, page_round(kernel->code_size)); - AT_ALLOC(cbank_mem, 0x1000); - AT_ALLOC(q_mem, page_round(L->q_bytes)); - AT_ALLOC(pool_mem, page_round(L->pool_bytes)); - AT_ALLOC(tab_mem, page_round(L->tab_bytes)); - AT_ALLOC(out_mem, page_round(L->out_bytes)); - AT_ALLOC(marker_mem, 0x1000); - AT_ALLOC(qmd_mem, 0x10000); -#undef AT_ALLOC - memcpy(code_mem.cpu, kernel->code, kernel->code_size); - memcpy(q_mem.cpu, L->q, L->q_bytes); - memcpy(pool_mem.cpu, L->pool, L->pool_bytes); - memcpy(tab_mem.cpu, L->tab, L->tab_bytes); +/* Caller holds the lock. Chip path: open the shared device on first use. */ +static int dev_open_locked(void) { + if (!g_hooked) { (void)omega_gpu_session_on_close(on_session_close); g_hooked = true; } + return omega_gpu_session_open() ? OMEGA_GPU_ATTN_OK : OMEGA_GPU_ATTN_CHIP_FAIL; +} + +/* Where a call stages the KV slice it is about to hand the kernel: straight into the + * device staging buffer on the chip path (one copy), a host buffer under the simulator. + * Caller holds the lock; the result is valid until the next staging call. */ +static void *stage_target(size_t bytes, void **host_tmp) { + *host_tmp = NULL; + if (g_sim) { *host_tmp = malloc(bytes ? bytes : 1); return *host_tmp; } + if (omega_gpu_session_scratch(&g_pool, bytes) != 0) return NULL; + return g_pool.mem.cpu; +} + +/* One launch through the shared session (omega_gpu_session_launch: shader-cache + * invalidate, constant bank, QMD0/QMD1, first marker, L2_FLUSH_DIRTY, second marker), + * then readback and the poison scan. L->pool may already be the pool staging buffer. */ +static int run_launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) { + if (omega_gpu_session_scratch(&g_q, L->q_bytes) || omega_gpu_session_scratch(&g_tab, L->tab_bytes) || + omega_gpu_session_scratch(&g_out, L->out_bytes) || (L->pool != g_pool.mem.cpu && omega_gpu_session_scratch(&g_pool, L->pool_bytes))) + return OMEGA_GPU_ATTN_CHIP_FAIL; + memcpy(g_q.mem.cpu, L->q, L->q_bytes); + if (L->pool != g_pool.mem.cpu) memcpy(g_pool.mem.cpu, L->pool, L->pool_bytes); + memcpy(g_tab.mem.cpu, L->tab, L->tab_bytes); size_t out_words = L->out_bytes / 4; - uint32_t *out_dev = (uint32_t *)out_mem.cpu; + uint32_t *out_dev = (uint32_t *)g_out.mem.cpu; for (size_t i = 0; i < out_words; i++) out_dev[i] = AT_POISON; - - const uint32_t threads_x = HD; - uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; - omega_blackwell_build_cbank_driver_2d(cbank_data, cbank_mem.va, threads_x, 1, L->grid_x, L->grid_y); - uint32_t cbank_args[ARG_WORDS]; - cbank_args[0] = (uint32_t)q_mem.va; cbank_args[1] = (uint32_t)(q_mem.va >> 32); - cbank_args[2] = (uint32_t)pool_mem.va; cbank_args[3] = (uint32_t)(pool_mem.va >> 32); - cbank_args[4] = (uint32_t)out_mem.va; cbank_args[5] = (uint32_t)(out_mem.va >> 32); - cbank_args[6] = (uint32_t)tab_mem.va; cbank_args[7] = (uint32_t)(tab_mem.va >> 32); - memcpy(&cbank_args[8], L->params, sizeof L->params); - memcpy(cbank_mem.cpu, cbank_data, sizeof(cbank_data)); - memcpy((uint8_t *)cbank_mem.cpu + 0x380, cbank_args, sizeof(cbank_args)); - - uint64_t qmd0_va = qmd_mem.va, qmd1_va = qmd_mem.va + 0x1000, sem_va = qmd_mem.va + 0x2000, scratch_va = qmd_mem.va + 0x4000; - OmegaBlackwellQmdConfig qmd_cfg = { - .code_va = code_mem.va, .cbank_va = cbank_mem.va, .scratch_va = scratch_va, .sem_va = sem_va, - .qmd0_va = qmd0_va, .qmd1_va = qmd1_va, .num_elements = out_words, .threads_per_block = threads_x, - .grid_width = L->grid_x * L->grid_y, .threads_x = threads_x, .threads_y = 1, .grid_x = L->grid_x, .grid_y = L->grid_y, - .gpr_count = AT_GPR_BUDGET - }; - uint32_t qmd0_words[OMEGA_BW_QMD_WORDS], qmd1_words[OMEGA_BW_QMD_WORDS]; - omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va); - omega_blackwell_build_qmd1(qmd1_words, &qmd_cfg); - if (omega_blackwell_verify_qmd_invariants(qmd1_words) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; } - memcpy(qmd_mem.cpu, qmd0_words, sizeof(qmd0_words)); - memcpy((uint8_t *)qmd_mem.cpu + 0x1000, qmd1_words, sizeof(qmd1_words)); - - volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)qmd_mem.cpu + 0x2000); - volatile uint32_t *hmarker = (volatile uint32_t *)marker_mem.cpu; - volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10); - *hsem = 0; *hmarker = 0; *hmarker2 = 0; __asm__ volatile("dsb sy" ::: "memory"); - uint32_t pb[1024]; - size_t n = 0; - memcpy(&pb[n], SETUP_WORDS, sizeof(SETUP_WORDS)); n += sizeof(SETUP_WORDS) / 4; - /* NVCEC0_INVALIDATE_SHADER_CACHES 0x021c: INSTRUCTION 0:0, DATA 4:4, CONSTANT 12:12 - * (clcec0.h; cut 1b: the SM instruction cache served stale code at a reused code address). */ - pb[n++] = nvrm_mthd(1, 0x021c, 1); pb[n++] = (1u << 0) | (1u << 4) | (1u << 12); - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(cbank_mem.va >> 32); pb[n++] = (uint32_t)cbank_mem.va; - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (224 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[n], cbank_data, 224 * 4); n += 224; - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((cbank_mem.va + 0x380) >> 32); pb[n++] = (uint32_t)(cbank_mem.va + 0x380); - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = ARG_WORDS * 4; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (ARG_WORDS << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[n], cbank_args, ARG_WORDS * 4); n += ARG_WORDS; - pb[n++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28); - pb[n++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd0_va >> 8); - memcpy(&pb[n], qmd0_words, 96 * 4); n += 96; - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va; - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (1 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; - pb[n++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28); - pb[n++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd1_va >> 8); - memcpy(&pb[n], qmd1_words, 96 * 4); n += 96; - pb[n++] = nvrm_mthd(0, 0x005c, 5); - pb[n++] = (uint32_t)marker_mem.va; pb[n++] = (uint32_t)(marker_mem.va >> 32); - pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); - /* C3 tail: L2_FLUSH_DIRTY, then the second release the host waits for before reading */ - pb[n++] = nvrm_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27); - pb[n++] = nvrm_mthd(0, 0x005c, 5); - pb[n++] = (uint32_t)(marker_mem.va + 0x10); pb[n++] = (uint32_t)((marker_mem.va + 0x10) >> 32); - pb[n++] = OMEGA_BW_MARKER2_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); - - uint64_t t0 = now_ns(); - if (m16_native_submit_methods(&ctx, pb, n) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; } - if (m16_native_wait_marker(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, AT_WAIT_MS) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; } - if (m16_native_wait_marker(hmarker2, OMEGA_BW_MARKER2_PAYLOAD, AT_WAIT_MS) != 0) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; } - __asm__ volatile("dsb sy" ::: "memory"); - uint64_t t1 = now_ns(); - if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { m16_native_close(&ctx); return OMEGA_GPU_ATTN_CHIP_FAIL; } + uint32_t args[ARG_WORDS]; + args[0] = (uint32_t)g_q.mem.va; args[1] = (uint32_t)(g_q.mem.va >> 32); + args[2] = (uint32_t)g_pool.mem.va; args[3] = (uint32_t)(g_pool.mem.va >> 32); + args[4] = (uint32_t)g_out.mem.va; args[5] = (uint32_t)(g_out.mem.va >> 32); + args[6] = (uint32_t)g_tab.mem.va; args[7] = (uint32_t)(g_tab.mem.va >> 32); + memcpy(&args[8], L->params, sizeof L->params); + OmegaGpuLaunch GL = { + .code_va = ks->code.va, .gpr_count = AT_GPR_BUDGET, .threads_x = HD, .threads_y = 1, + .grid_x = L->grid_x, .grid_y = L->grid_y, .num_elements = out_words, + .args = args, .n_args = ARG_WORDS, .timeout_ms = AT_WAIT_MS, + }; + uint64_t elapsed = 0; uint32_t marker = 0; + if (omega_gpu_session_launch(&GL, &elapsed, &marker) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; - memcpy(L->out, out_mem.cpu, L->out_bytes); + memcpy(L->out, g_out.mem.cpu, L->out_bytes); uint32_t unwritten = 0; for (size_t i = 0; i < out_words; i++) if (((uint32_t *)L->out)[i] == AT_POISON) unwritten++; if (info) { info->chip_calls++; - info->elapsed_ns += (t1 > t0) ? (t1 - t0) : 0; - info->completion_marker = *hmarker; + info->elapsed_ns += elapsed; + info->completion_marker = marker; info->unwritten_words += unwritten; - info->threads_per_cta = threads_x; + info->threads_per_cta = HD; info->ctas_last_launch = L->grid_x * L->grid_y; } - m16_native_close(&ctx); return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK; } -static int launch(const OmegaBlackwellKernel *kernel, const BlackwellIRProgram *prog, const Launch *L, OmegaGpuAttnInfo *info) { - pthread_mutex_lock(&g_mu); OmegaGpuAttnSim sim = g_sim; pthread_mutex_unlock(&g_mu); - if (sim) return sim(prog, L, info); - return run_launch(kernel, L, info); +/* Caller holds the lock. */ +static int launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) { + if (g_sim) return g_sim(ks->prog, L, info); + return run_launch(ks, L, info); } /* ------------------------------------------------------- public entries */ @@ -621,6 +580,17 @@ static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t hea return OMEGA_GPU_ATTN_OK; } +/* Common prologue of every chip entry (lock held on success): device, kernel, info. */ +static int begin(bool f32, uint32_t log2bs, uint32_t log2gqa, Slot **ks, OmegaGpuAttnInfo *info) { + LOCK(); + int rc = g_sim ? OMEGA_GPU_ATTN_OK : dev_open_locked(); + bool hit = false; + if (rc == OMEGA_GPU_ATTN_OK) rc = kernel_for(f32, log2bs, log2gqa, !g_sim, ks, &hit); + if (rc != OMEGA_GPU_ATTN_OK) { UNLOCK(); return rc; } + info_begin(info, &(*ks)->kernel, hit); + return OMEGA_GPU_ATTN_OK; +} + int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache, uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) { @@ -632,14 +602,14 @@ int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const floa if (seq_len > OMEGA_GPU_ATTN_MAX_GQA_CTX) return OMEGA_GPU_ATTN_TOO_LARGE; size_t n_out = (size_t)num_q_heads * HD; if (seq_len == 0) { memset(out, 0, n_out * 4); if (info) { memset(info, 0, sizeof *info); info->call_ns = now_ns() - t0; } return OMEGA_GPU_ATTN_OK; } - OmegaBlackwellKernel k; const BlackwellIRProgram *kp = NULL; bool hit = false; + Slot *ks = NULL; const uint32_t log2bs = 12; /* one block of 4096 slots */ - rc = kernel_for(true, log2bs, log2gqa, &k, &kp, &hit); + rc = begin(true, log2bs, log2gqa, &ks, info); if (rc != OMEGA_GPU_ATTN_OK) return rc; - info_begin(info, &k, hit); size_t plane = (size_t)seq_len * num_kv_heads * HD * 4; - uint8_t *pool = malloc(2 * plane); - if (!pool) return OMEGA_GPU_ATTN_CHIP_FAIL; + void *host_tmp = NULL; + uint8_t *pool = stage_target(2 * plane, &host_tmp); + if (!pool) { UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } memcpy(pool, k_cache, plane); memcpy(pool + plane, v_cache, plane); uint32_t tab[2] = { 0, seq_len }; /* table row {0}, then the context length at byte 4 */ @@ -648,8 +618,9 @@ int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const floa .out = out, .out_bytes = n_out * 4, .grid_x = num_q_heads, .grid_y = 1, .params = { 1, f2u(score_scale()), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, 4 } }; - rc = launch(&k, kp, &L, info); - free(pool); + rc = launch(ks, &L, info); + free(host_tmp); + UNLOCK(); if (info) info->call_ns = now_ns() - t0; return rc; } @@ -682,10 +653,9 @@ static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayou if (id >= ly->num_blocks || id * ly->block_stride_bytes + (uint64_t)(layer_idx + 1) * ly->layer_stride_bytes > ly->pool_bytes) { free(eff); return OMEGA_GPU_ATTN_BAD_ARGS; } } } - OmegaBlackwellKernel k; const BlackwellIRProgram *kp = NULL; bool hit = false; - rc = kernel_for(false, log2bs, log2gqa, &k, &kp, &hit); + Slot *ks = NULL; + rc = begin(false, log2bs, log2gqa, &ks, info); if (rc != OMEGA_GPU_ATTN_OK) { free(eff); return rc; } - info_begin(info, &k, hit); uint32_t seqs_per_launch = OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads; if (seqs_per_launch == 0) seqs_per_launch = 1; uint32_t maxb = 1; @@ -697,9 +667,10 @@ static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayou for (uint32_t s = 0; s < ns; s++) total += eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0; uint64_t staged_bytes = (uint64_t)(total ? total : 1) * ly->layer_stride_bytes; if (staged_bytes > 0xffffffffull) { rc = OMEGA_GPU_ATTN_TOO_LARGE; break; } - uint8_t *staged = malloc((size_t)staged_bytes); + void *host_tmp = NULL; + uint8_t *staged = stage_target((size_t)staged_bytes, &host_tmp); uint32_t *tab = calloc((size_t)ns * maxb + ns, sizeof *tab); - if (!staged || !tab) { free(staged); free(tab); rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; } + if (!staged || !tab) { free(host_tmp); free(tab); rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; } uint32_t g = 0; for (uint32_t s = 0; s < ns; s++) { uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0; @@ -717,9 +688,10 @@ static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayou .params = { maxb, f2u(score_scale()), (uint32_t)ly->layer_stride_bytes, (uint32_t)ly->token_stride_bytes, (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 } }; - rc = launch(&k, kp, &L, info); - free(staged); free(tab); + rc = launch(ks, &L, info); + free(host_tmp); free(tab); } + UNLOCK(); free(eff); if (info) info->call_ns = now_ns() - t0; return rc; diff --git a/src/omega_gpu_attention_api.h b/src/omega_gpu_attention_api.h index 4baf67c49..ab47354f4 100644 --- a/src/omega_gpu_attention_api.h +++ b/src/omega_gpu_attention_api.h @@ -42,10 +42,16 @@ * src/omega_blackwell_qmd.c word 36); the kernel uses exactly 4 x 256 bytes for * head_dim 64, so head_dim is fixed at 64 in this cut (TinyLlama and Llama-3.2-1B). * - * Staging (this cut): the host copies q, the referenced KV blocks' layer slice, the - * (compacted, renumbered) block tables and the context lengths into GPU-uncached - * buffers for each launch and copies the result back. The kernel itself walks the - * block table; a resident pool handle is a later cut. + * Staging: the host copies q, the referenced KV blocks' layer slice, the (compacted, + * renumbered) block tables and the context lengths into GPU-uncached staging buffers + * for each launch and copies the result back. The kernel itself walks the block + * table; a resident pool handle is a later cut. + * + * Cut 4b (2026-10-04): the device, channel and launch scratch are the process-wide + * session shared with the matmul and elementwise APIs (omega_gpu_session.h): one + * open per process instead of one per call (~40 ms), kernels resident after first + * use, staging buffers reused at their high-water mark (the KV slice is written + * straight into the device staging buffer). Calls serialise on one lock. */ #include <stdbool.h> #include <stddef.h> @@ -119,6 +125,10 @@ int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const const char *omega_gpu_attention_rc_name(int rc); void omega_gpu_attention_cache_clear(void); +/* Stage name of the most recent CHIP_FAIL ("" if none), shared with the other GPU APIs + * (omega_gpu_session_last_error); an open failure carries the driver text. */ +const char *omega_gpu_attention_last_error(void); + /* Test hooks. Mutants are deliberately wrong kernels the parity test must catch; * never set in production. */ typedef enum { diff --git a/src/omega_gpu_elementwise_api.c b/src/omega_gpu_elementwise_api.c index f6ef2aa09..3d5970ce2 100644 --- a/src/omega_gpu_elementwise_api.c +++ b/src/omega_gpu_elementwise_api.c @@ -21,9 +21,8 @@ #include "omega_blackwell_codegen.h" #include "omega_blackwell_qmd.h" #include "omega_blackwell_submit.h" -#include "m16_native.h" +#include "omega_gpu_session.h" #include "sha256.h" -#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -365,188 +364,135 @@ static int build_kernel(OmegaGpuEwOp op, int mutant, OmegaBlackwellKernel *kerne /* --------------------------------------------------------- kernel cache */ +/* One kernel per (op, mutant); the device copy is uploaded once and stays + * resident for the process (cut 4b: no per-call code page). */ +typedef struct { int used; int op; int mutant; OmegaBlackwellKernel kernel; NvrmMem code; } Slot; static int g_mutant_op; /* 0 = none */ -typedef struct { int used; int op; int mutant; OmegaBlackwellKernel kernel; } Slot; static Slot g_cache[8]; -static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER; +static OmegaGpuScratch g_a, g_b, g_c; /* staging, grown to the high-water mark, reused per call */ +static bool g_hooked; +#define LOCK() omega_gpu_session_lock() +#define UNLOCK() omega_gpu_session_unlock() -void omega_gpu_elementwise_cache_clear(void) { - pthread_mutex_lock(&g_mu); +static void cache_clear_locked(void) { for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) - if (g_cache[i].used) { free(g_cache[i].kernel.code); memset(&g_cache[i], 0, sizeof g_cache[i]); } - pthread_mutex_unlock(&g_mu); + if (g_cache[i].used) { free(g_cache[i].kernel.code); omega_gpu_session_free(&g_cache[i].code); memset(&g_cache[i], 0, sizeof g_cache[i]); } +} + +void omega_gpu_elementwise_cache_clear(void) { + LOCK(); + cache_clear_locked(); + UNLOCK(); +} + +/* Called by the session (lock held, device still open) right before it closes. */ +static void on_session_close(void) { + cache_clear_locked(); + omega_gpu_session_scratch_free(&g_a); omega_gpu_session_scratch_free(&g_b); omega_gpu_session_scratch_free(&g_c); } void omega_gpu_elementwise_test_set_mutant(int op) { - pthread_mutex_lock(&g_mu); + LOCK(); g_mutant_op = op; - pthread_mutex_unlock(&g_mu); - omega_gpu_elementwise_cache_clear(); + cache_clear_locked(); + UNLOCK(); } -static int kernel_for(OmegaGpuEwOp op, OmegaBlackwellKernel *out, bool *hit) { - pthread_mutex_lock(&g_mu); +/* Caller holds the lock. Builds the kernel if needed; uploads the device copy when a + * device is open (upload = false lets the host-only codegen path run without a chip). */ +static int kernel_for(OmegaGpuEwOp op, bool upload, Slot **out, bool *hit) { int mutant = (g_mutant_op == (int)op); + Slot *s = NULL; for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) - if (g_cache[i].used && g_cache[i].op == (int)op && g_cache[i].mutant == mutant) { - *out = g_cache[i].kernel; *hit = true; pthread_mutex_unlock(&g_mu); return OMEGA_GPU_EW_OK; - } - OmegaBlackwellKernel k; - int rc = build_kernel(op, mutant, &k); - if (rc == OMEGA_GPU_EW_OK) { - for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) - if (!g_cache[i].used) { g_cache[i].used = 1; g_cache[i].op = (int)op; g_cache[i].mutant = mutant; g_cache[i].kernel = k; break; } - *out = k; *hit = false; + 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); + 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; } + s = &g_cache[slot]; + if (s->used) { free(s->kernel.code); omega_gpu_session_free(&s->code); } /* full: evict slot 0 */ + memset(s, 0, sizeof *s); + s->used = 1; s->op = (int)op; s->mutant = mutant; s->kernel = k; + *hit = false; } - pthread_mutex_unlock(&g_mu); - return rc; + if (upload && !s->code.cpu) { + if (omega_gpu_session_alloc(s->kernel.code_size, &s->code) != 0) return OMEGA_GPU_EW_CHIP_FAIL; + memcpy(s->code.cpu, s->kernel.code, s->kernel.code_size); + __asm__ volatile("dsb sy" ::: "memory"); + } + *out = s; + return OMEGA_GPU_EW_OK; } int omega_gpu_elementwise_codegen(OmegaGpuEwOp op, const uint32_t *dims, float eps, OmegaBlackwellKernel *kernel) { (void)dims; (void)eps; /* kernels read their shape from the argument words */ if (!kernel) return OMEGA_GPU_EW_BAD_ARGS; - pthread_mutex_lock(&g_mu); + LOCK(); int mutant = (g_mutant_op == (int)op); - pthread_mutex_unlock(&g_mu); + UNLOCK(); return build_kernel(op, mutant, kernel); } +const char *omega_gpu_elementwise_last_error(void) { return omega_gpu_session_last_error(); } + /* ------------------------------------------------------------ launcher */ #define EW_POISON 0xffbadbadu /* a NaN pattern no kernel here produces on purpose */ -#define EW_MARKER2_PAYLOAD 0x46464646u /* same value as omega_blackwell_submit.c and the engine */ #define EW_WAIT_MS 600000ull /* like main's load/store launchers; a 5 s wait failed under contention (omega#198) */ -static const uint32_t SETUP_WORDS[18] = { - 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, - 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000, - 0x20012559, 0x00000000, -}; - 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 size_t page_round(size_t b) { b = (b + 0xFFFULL) & ~0xFFFULL; return b < 0x1000 ? 0x1000 : b; } -/* One launch: a and b in, c out (c_bytes/4 words, poison-filled first). Cloned - * from omega_blackwell_execute_matmul_tensor: every buffer GPU-uncached, first - * marker, L2_FLUSH_DIRTY, second marker, then readback and the poison scan. */ -static int run_abc(const OmegaBlackwellKernel *kernel, - const void *a, size_t a_bytes, const void *b, size_t b_bytes, +/* Caller holds the lock. Opens the shared device on first use. */ +static int dev_open_locked(void) { + if (!g_hooked) { (void)omega_gpu_session_on_close(on_session_close); g_hooked = true; } + return omega_gpu_session_open() ? OMEGA_GPU_EW_OK : OMEGA_GPU_EW_CHIP_FAIL; +} + +/* One launch: a and b staged in, c out (c_bytes/4 words, poison-filled first), through + * the shared session (omega_gpu_session_launch: shader-cache invalidate, constant bank, + * QMD0/QMD1, first marker, L2_FLUSH_DIRTY, second marker), then readback and the + * poison scan. b may be NULL when b_fill wrote the staging buffer already. */ +static int run_abc(const Slot *ks, const void *a, size_t a_bytes, const void *b, size_t b_bytes, void *c, size_t c_bytes, uint32_t threads_x, uint32_t grid_x, const uint32_t params[4], OmegaGpuEwInfo *info) { - M16NativeContext ctx; - if (m16_native_open(&ctx) != 0) return OMEGA_GPU_EW_CHIP_FAIL; - if (m16_native_create_channel(&ctx) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } - NvrmMem large_pb; - if (nvrm_alloc_gpu_uncached(&ctx.rm, 0x10000, &large_pb) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } - ctx.pb_mem = large_pb; - - NvrmMem code_mem, cbank_mem, a_mem, b_mem, c_mem, marker_mem, qmd_mem; -#define EW_ALLOC(mem, bytes) if (nvrm_alloc_gpu_uncached(&ctx.rm, (bytes), &(mem)) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } - EW_ALLOC(code_mem, page_round(kernel->code_size)); - EW_ALLOC(cbank_mem, 0x1000); - EW_ALLOC(a_mem, page_round(a_bytes)); - EW_ALLOC(b_mem, page_round(b_bytes)); - EW_ALLOC(c_mem, page_round(c_bytes)); - EW_ALLOC(marker_mem, 0x1000); - EW_ALLOC(qmd_mem, 0x10000); -#undef EW_ALLOC - memcpy(code_mem.cpu, kernel->code, kernel->code_size); - memcpy(a_mem.cpu, a, a_bytes); - memcpy(b_mem.cpu, b, b_bytes); + if (omega_gpu_session_scratch(&g_a, a_bytes) || omega_gpu_session_scratch(&g_b, b_bytes) || omega_gpu_session_scratch(&g_c, c_bytes)) + return OMEGA_GPU_EW_CHIP_FAIL; + memcpy(g_a.mem.cpu, a, a_bytes); + if (b) memcpy(g_b.mem.cpu, b, b_bytes); size_t c_words = c_bytes / 4; - uint32_t *c_dev = (uint32_t *)c_mem.cpu; + uint32_t *c_dev = (uint32_t *)g_c.mem.cpu; for (size_t i = 0; i < c_words; i++) c_dev[i] = EW_POISON; - - uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; - omega_blackwell_build_cbank_driver_2d(cbank_data, cbank_mem.va, threads_x, 1, grid_x, 1); - uint32_t cbank_args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS]; - cbank_args[0] = (uint32_t)a_mem.va; cbank_args[1] = (uint32_t)(a_mem.va >> 32); - cbank_args[2] = (uint32_t)b_mem.va; cbank_args[3] = (uint32_t)(b_mem.va >> 32); - cbank_args[4] = (uint32_t)c_mem.va; cbank_args[5] = (uint32_t)(c_mem.va >> 32); - cbank_args[6] = params[0]; cbank_args[7] = params[1]; cbank_args[8] = params[2]; cbank_args[9] = params[3]; - memcpy(cbank_mem.cpu, cbank_data, sizeof(cbank_data)); - memcpy((uint8_t *)cbank_mem.cpu + 0x380, cbank_args, sizeof(cbank_args)); - - uint64_t qmd0_va = qmd_mem.va, qmd1_va = qmd_mem.va + 0x1000, sem_va = qmd_mem.va + 0x2000, scratch_va = qmd_mem.va + 0x4000; - OmegaBlackwellQmdConfig qmd_cfg = { - .code_va = code_mem.va, .cbank_va = cbank_mem.va, .scratch_va = scratch_va, .sem_va = sem_va, - .qmd0_va = qmd0_va, .qmd1_va = qmd1_va, .num_elements = c_words, .threads_per_block = threads_x, - .grid_width = grid_x, .threads_x = threads_x, .threads_y = 1, .grid_x = grid_x, .grid_y = 1, - .gpr_count = EW_GPR_BUDGET - }; - uint32_t qmd0_words[OMEGA_BW_QMD_WORDS], qmd1_words[OMEGA_BW_QMD_WORDS]; - omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va); - omega_blackwell_build_qmd1(qmd1_words, &qmd_cfg); - if (omega_blackwell_verify_qmd_invariants(qmd1_words) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } - memcpy(qmd_mem.cpu, qmd0_words, sizeof(qmd0_words)); - memcpy((uint8_t *)qmd_mem.cpu + 0x1000, qmd1_words, sizeof(qmd1_words)); - - volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)qmd_mem.cpu + 0x2000); - volatile uint32_t *hmarker = (volatile uint32_t *)marker_mem.cpu; - volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)marker_mem.cpu + 0x10); - *hsem = 0; *hmarker = 0; *hmarker2 = 0; __asm__ volatile("dsb sy" ::: "memory"); - uint32_t pb[1024]; - size_t n = 0; - memcpy(&pb[n], SETUP_WORDS, sizeof(SETUP_WORDS)); n += sizeof(SETUP_WORDS) / 4; - /* Every launch uploads fresh code into a freshly allocated page, so the code address - * of the previous (different) kernel is routinely reused: exactly the stale-SM-icache - * case cut 1b hit. Invalidate before the kernel (constants in omega_blackwell_submit.h). */ - pb[n++] = nvrm_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1); pb[n++] = OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL; - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(cbank_mem.va >> 32); pb[n++] = (uint32_t)cbank_mem.va; - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (224 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[n], cbank_data, 224 * 4); n += 224; - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((cbank_mem.va + 0x380) >> 32); pb[n++] = (uint32_t)(cbank_mem.va + 0x380); - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000028; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (10 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[n], cbank_args, 10 * 4); n += 10; - pb[n++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28); - pb[n++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd0_va >> 8); - memcpy(&pb[n], qmd0_words, 96 * 4); n += 96; - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va; - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (1 << 16) | (1 << 13) | (0x01b4 >> 2) | (6u << 28); - pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; - pb[n++] = (98 << 16) | (1 << 13) | (0x0318 >> 2) | (2u << 28); - pb[n++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd1_va >> 8); - memcpy(&pb[n], qmd1_words, 96 * 4); n += 96; - pb[n++] = nvrm_mthd(0, 0x005c, 5); - pb[n++] = (uint32_t)marker_mem.va; pb[n++] = (uint32_t)(marker_mem.va >> 32); - pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); - /* C3 tail: L2_FLUSH_DIRTY, then the second release the host waits for before reading */ - pb[n++] = nvrm_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27); - pb[n++] = nvrm_mthd(0, 0x005c, 5); - pb[n++] = (uint32_t)(marker_mem.va + 0x10); pb[n++] = (uint32_t)((marker_mem.va + 0x10) >> 32); - pb[n++] = EW_MARKER2_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); - - uint64_t t0 = now_ns(); - if (m16_native_submit_methods(&ctx, pb, n) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } - if (m16_native_wait_marker(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, EW_WAIT_MS) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } - if (m16_native_wait_marker(hmarker2, EW_MARKER2_PAYLOAD, EW_WAIT_MS) != 0) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } - __asm__ volatile("dsb sy" ::: "memory"); - uint64_t t1 = now_ns(); - if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { m16_native_close(&ctx); return OMEGA_GPU_EW_CHIP_FAIL; } + uint32_t args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS]; + args[0] = (uint32_t)g_a.mem.va; args[1] = (uint32_t)(g_a.mem.va >> 32); + args[2] = (uint32_t)g_b.mem.va; args[3] = (uint32_t)(g_b.mem.va >> 32); + args[4] = (uint32_t)g_c.mem.va; args[5] = (uint32_t)(g_c.mem.va >> 32); + args[6] = params[0]; args[7] = params[1]; args[8] = params[2]; args[9] = params[3]; + OmegaGpuLaunch L = { + .code_va = ks->code.va, .gpr_count = EW_GPR_BUDGET, .threads_x = threads_x, .threads_y = 1, + .grid_x = grid_x, .grid_y = 1, .num_elements = c_words, + .args = args, .n_args = OMEGA_BW_CBANK_MATMUL_ARGS_WORDS, .timeout_ms = EW_WAIT_MS, + }; + uint64_t elapsed = 0; uint32_t marker = 0; + if (omega_gpu_session_launch(&L, &elapsed, &marker) != 0) return OMEGA_GPU_EW_CHIP_FAIL; - memcpy(c, c_mem.cpu, c_bytes); + memcpy(c, g_c.mem.cpu, c_bytes); uint32_t unwritten = 0; for (size_t i = 0; i < c_words; i++) if (((uint32_t *)c)[i] == EW_POISON) unwritten++; if (info) { info->chip_calls++; - info->elapsed_ns += (t1 > t0) ? (t1 - t0) : 0; - info->completion_marker = *hmarker; + info->elapsed_ns += elapsed; + info->completion_marker = marker; info->unwritten_words += unwritten; info->threads_per_cta = threads_x; info->ctas_last_launch = grid_x; } - m16_native_close(&ctx); return unwritten ? OMEGA_GPU_EW_UNWRITTEN : OMEGA_GPU_EW_OK; } @@ -562,73 +508,85 @@ static void info_begin(OmegaGpuEwInfo *info, const OmegaBlackwellKernel *k, bool info->sm_architecture = 121; } static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } +static void info_end(OmegaGpuEwInfo *info, uint64_t t0) { if (info) info->call_ns = now_ns() - t0; } + +/* Common prologue of every chip entry: lock, open, kernel (resident), info. */ +static int begin(OmegaGpuEwOp op, Slot **ks, OmegaGpuEwInfo *info) { + LOCK(); + int rc = dev_open_locked(); + bool hit = false; + if (rc == OMEGA_GPU_EW_OK) rc = kernel_for(op, true, ks, &hit); + if (rc != OMEGA_GPU_EW_OK) { UNLOCK(); return rc; } + info_begin(info, &(*ks)->kernel, hit); + return OMEGA_GPU_EW_OK; +} int omega_gpu_rmsnorm_f32(uint32_t rows, uint32_t dim, const float *x, const float *weight, float eps, float *out, OmegaGpuEwInfo *info) { + uint64_t t0 = now_ns(); if (!x || !weight || !out || rows == 0 || dim == 0 || dim % OMEGA_GPU_EW_THREADS != 0) return OMEGA_GPU_EW_BAD_ARGS; if (dim > OMEGA_GPU_EW_MAX_DIM) return OMEGA_GPU_EW_TOO_LARGE; - OmegaBlackwellKernel k; bool hit = false; - int rc = kernel_for(OMEGA_GPU_EW_RMSNORM, &k, &hit); + Slot *k = NULL; + int rc = begin(OMEGA_GPU_EW_RMSNORM, &k, info); if (rc != OMEGA_GPU_EW_OK) return rc; - info_begin(info, &k, hit); uint32_t params[4] = { dim / OMEGA_GPU_EW_THREADS, f2u(1.0f / (float)dim), f2u(eps), dim }; - for (uint32_t r0 = 0; r0 < rows; r0 += OMEGA_GPU_EW_MAX_CTAS) { + for (uint32_t r0 = 0; r0 < rows && rc == OMEGA_GPU_EW_OK; r0 += OMEGA_GPU_EW_MAX_CTAS) { uint32_t nr = rows - r0 < OMEGA_GPU_EW_MAX_CTAS ? rows - r0 : OMEGA_GPU_EW_MAX_CTAS; size_t bytes = (size_t)nr * dim * 4; - rc = run_abc(&k, x + (size_t)r0 * dim, bytes, weight, (size_t)dim * 4, out + (size_t)r0 * dim, bytes, + rc = run_abc(k, x + (size_t)r0 * dim, bytes, weight, (size_t)dim * 4, out + (size_t)r0 * dim, bytes, OMEGA_GPU_EW_THREADS, nr, params, info); - if (rc != OMEGA_GPU_EW_OK) return rc; } - return OMEGA_GPU_EW_OK; + UNLOCK(); + info_end(info, t0); + return rc; } int omega_gpu_rope_f32(uint32_t heads, uint32_t head_dim, const float *v, const float *cos_half, const float *sin_half, float *out, OmegaGpuEwInfo *info) { + uint64_t t0 = now_ns(); if (!v || !cos_half || !sin_half || !out || heads == 0 || head_dim < 2 || (head_dim & 1)) return OMEGA_GPU_EW_BAD_ARGS; if (head_dim > 2048) return OMEGA_GPU_EW_TOO_LARGE; - OmegaBlackwellKernel k; bool hit = false; - int rc = kernel_for(OMEGA_GPU_EW_ROPE, &k, &hit); + Slot *k = NULL; + int rc = begin(OMEGA_GPU_EW_ROPE, &k, info); if (rc != OMEGA_GPU_EW_OK) return rc; - info_begin(info, &k, hit); uint32_t half = head_dim / 2; - uint32_t hchunk = OMEGA_GPU_EW_MAX_CTAS; - size_t chunk_elems = (size_t)hchunk * head_dim; - float *table = malloc(chunk_elems * sizeof *table); - float *tmp = malloc(chunk_elems * sizeof *tmp); - if (!table || !tmp) { free(table); free(tmp); return OMEGA_GPU_EW_CHIP_FAIL; } - for (uint32_t h = 0; h < hchunk; h++) { - memcpy(table + (size_t)h * head_dim, cos_half, half * sizeof *table); - memcpy(table + (size_t)h * head_dim + half, sin_half, half * sizeof *table); - } uint32_t params[4] = { head_dim, half, 0, 0 }; - for (uint32_t h0 = 0; h0 < heads; h0 += hchunk) { - uint32_t nh = heads - h0 < hchunk ? heads - h0 : hchunk; + for (uint32_t h0 = 0; h0 < heads && rc == OMEGA_GPU_EW_OK; h0 += OMEGA_GPU_EW_MAX_CTAS) { + uint32_t nh = heads - h0 < OMEGA_GPU_EW_MAX_CTAS ? heads - h0 : OMEGA_GPU_EW_MAX_CTAS; size_t bytes = (size_t)nh * head_dim * 4; - /* through tmp so out may alias v */ - rc = run_abc(&k, v + (size_t)h0 * head_dim, bytes, table, bytes, tmp, bytes, half, nh, params, info); - if (rc != OMEGA_GPU_EW_OK) break; - memcpy(out + (size_t)h0 * head_dim, tmp, bytes); + /* table: cos in the first half of each head, sin in the second, written straight into + * the staging buffer (one copy per head of this launch) */ + if (omega_gpu_session_scratch(&g_b, bytes) != 0) { rc = OMEGA_GPU_EW_CHIP_FAIL; break; } + float *table = g_b.mem.cpu; + for (uint32_t h = 0; h < nh; h++) { + memcpy(table + (size_t)h * head_dim, cos_half, half * sizeof *table); + memcpy(table + (size_t)h * head_dim + half, sin_half, half * sizeof *table); + } + /* out may alias v: v is copied into the staging buffer before the result lands in out */ + rc = run_abc(k, v + (size_t)h0 * head_dim, bytes, NULL, bytes, out + (size_t)h0 * head_dim, bytes, half, nh, params, info); } - free(table); free(tmp); + UNLOCK(); + info_end(info, t0); return rc; } static int run_1d(OmegaGpuEwOp op, uint32_t n, const void *a, const void *b, void *c, OmegaGpuEwInfo *info) { - OmegaBlackwellKernel k; bool hit = false; - int rc = kernel_for(op, &k, &hit); + uint64_t t0 = now_ns(); + Slot *k = NULL; + int rc = begin(op, &k, info); if (rc != OMEGA_GPU_EW_OK) return rc; - info_begin(info, &k, hit); const uint32_t chunk = OMEGA_GPU_EW_MAX_CTAS * OMEGA_GPU_EW_THREADS; - for (uint32_t i0 = 0; i0 < n; i0 += chunk) { + for (uint32_t i0 = 0; i0 < n && rc == OMEGA_GPU_EW_OK; i0 += chunk) { uint32_t ni = n - i0 < chunk ? n - i0 : chunk; uint32_t grid = (ni + OMEGA_GPU_EW_THREADS - 1) / OMEGA_GPU_EW_THREADS; uint32_t params[4] = { ni, 0, 0, 0 }; size_t bytes = (size_t)ni * 4; - rc = run_abc(&k, (const uint8_t *)a + (size_t)i0 * 4, bytes, b ? (const uint8_t *)b + (size_t)i0 * 4 : a, bytes, + rc = run_abc(k, (const uint8_t *)a + (size_t)i0 * 4, bytes, b ? (const uint8_t *)b + (size_t)i0 * 4 : a, bytes, (uint8_t *)c + (size_t)i0 * 4, bytes, OMEGA_GPU_EW_THREADS, grid, params, info); - if (rc != OMEGA_GPU_EW_OK) return rc; } - return OMEGA_GPU_EW_OK; + UNLOCK(); + info_end(info, t0); + return rc; } int omega_gpu_swiglu_f32(uint32_t n, const float *gate, const float *up, float *out, OmegaGpuEwInfo *info) { diff --git a/src/omega_gpu_elementwise_api.h b/src/omega_gpu_elementwise_api.h index 051c40d71..a21710bb4 100644 --- a/src/omega_gpu_elementwise_api.h +++ b/src/omega_gpu_elementwise_api.h @@ -25,6 +25,11 @@ * MUFU.EX2(g * -log2(e)) and MUFU.RCP (approximate units), the * oracle computes in f64. Tolerance is stated per op in the test. * + * Cut 4b (2026-10-04): the device, channel and launch scratch are the process-wide + * session shared with the matmul and attention APIs (omega_gpu_session.h): one open + * per process instead of one per call (~40 ms), kernels resident after first use, + * staging buffers reused at their high-water mark. Calls serialise on one lock. + * * Launch envelope: at most OMEGA_GPU_EW_MAX_CTAS CTAs per launch (the matmul * sweep of 2026-10-03 lost whole tiles at 128 CTAs, investigation I42); the * API splits larger work on the host and makes several launches. @@ -78,6 +83,7 @@ typedef struct { uint32_t ctas_last_launch; char target_chip[64]; uint32_t sm_architecture; + uint64_t call_ns; /* cut 4b: wall time of the whole API call (staging, launches, copy-out) */ } OmegaGpuEwInfo; /* out[r*dim + i] = x[r*dim + i] * scale_r * weight[i]; scale_r = 1/sqrt(mean_i(x^2) + eps). */ @@ -118,6 +124,10 @@ void omega_gpu_elementwise_test_set_mutant(int op); const char *omega_gpu_elementwise_rc_name(int rc); void omega_gpu_elementwise_cache_clear(void); +/* Stage name of the most recent CHIP_FAIL ("" if none), shared with the other GPU APIs + * (omega_gpu_session_last_error); an open failure carries the driver text. */ +const char *omega_gpu_elementwise_last_error(void); + #ifdef __cplusplus } #endif diff --git a/src/omega_gpu_matmul_api.c b/src/omega_gpu_matmul_api.c index 4abe6afe2..bb797d4c9 100644 --- a/src/omega_gpu_matmul_api.c +++ b/src/omega_gpu_matmul_api.c @@ -1,43 +1,35 @@ /* - * omega_gpu_matmul_api.c: FB-1 cut 1b. See the header for the contract. + * omega_gpu_matmul_api.c: FB-1 cut 1b, on the shared session since cut 4b. + * See the header for the contract. * - * Submission path: the same words the chip-proven single-tile path uses - * (omega_blackwell_execute_matmul_tensor: SETUP_WORDS, constant bank upload, - * QMD0/QMD1 launch, first marker release, then the C3 tail: L2_FLUSH_DIRTY and a - * second release on uncached memory that the host waits for before reading). - * Every buffer both sides touch is GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE: - * "For system memory this will not be coherent with direct CPU mappings"). - * Difference from cut 1: the device, channel, pushbuffer, constant bank, marker - * page, QMD page and kernel code buffers persist for the process; the GPFIFO is - * retired after every completed launch (nvrm_enqueue refuses to overrun - * unretired entries, nvrm.c). + * Submission path: omega_gpu_session_launch (src/omega_gpu_session.c), the same + * words this file emitted in cut 1b (chip PASS FB1-CUT1B-4345406): SETUP_WORDS, + * shader-cache invalidate, constant bank upload, QMD0/QMD1 launch, first marker + * release, then the C3 tail (L2_FLUSH_DIRTY and a second release on uncached + * memory the host waits for before reading). Every buffer both sides touch is + * GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE: "For system memory this will + * not be coherent with direct CPU mappings"). The device, channel, pushbuffer, + * constant bank, marker page and QMD page now belong to the session and are + * shared with the elementwise and attention APIs; this file keeps the resident + * tensors, the kernel cache (host and device copies) and its staging buffers. */ #include "omega_gpu_matmul_api.h" +#include "omega_gpu_session.h" #include "omega_blackwell_codegen.h" #include "omega_blackwell_matmul.h" #include "omega_blackwell_qmd.h" #include "omega_blackwell_submit.h" -#include "m16_native.h" #include "nvrm.h" #include <math.h> -#include <pthread.h> #include <stdlib.h> #include <string.h> #include <time.h> #define CACHE_SLOTS 8 -#define PAGE 0x1000ull #define MARKER_TIMEOUT_MS 20000ull /* a 1x2048x128256 call is ~0.1 s; 20 s is a stall, not a slow run */ #define POISON_F32 (-999.0f) #define ORACLE_TOL 1e-5 -/* Same words as src/omega_blackwell_submit.c SETUP_WORDS (compute class setup). */ -static const uint32_t SETUP_WORDS[18] = { - 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, - 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000, - 0x20012559, 0x00000000, -}; - struct OmegaGpuTensor { uint32_t k, n, kp, np; NvrmMem mem; /* kp x np bf16 */ @@ -53,21 +45,16 @@ typedef struct { } CacheSlot; static struct { - bool open, blocked; - M16NativeContext ctx; - NvrmMem pb, cbank, marker, qmd; /* per-launch scratch, reused */ - NvrmMem a_buf, c_buf; /* activation and result staging, grown on demand */ - size_t a_cap, c_cap; + OmegaGpuScratch a_buf, c_buf; /* activation and result staging, grown to the high-water mark */ uint32_t cta_budget; int oracle, mutant; + bool hooked; CacheSlot cache[CACHE_SLOTS]; unsigned cache_next; } g = { .cta_budget = OMEGA_GPU_MATMUL_MAX_CTAS, .oracle = 1 }; -static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER; -static const char *g_err = ""; -#define FAILAT(s) (g_err = (s)) -const char *omega_gpu_matmul_last_error(void) { return g_err; } +#define FAILAT(s) (omega_gpu_session_set_error(s), 1) +const char *omega_gpu_matmul_last_error(void) { return omega_gpu_session_last_error(); } static uint64_t now_ns(void) { struct timespec t; @@ -76,7 +63,6 @@ static uint64_t now_ns(void) { } static uint32_t round_up(uint32_t v, uint32_t q) { return (v + q - 1) / q * q; } -static size_t page_up(size_t b) { b = (b + PAGE - 1) & ~(PAGE - 1); return b < PAGE ? PAGE : b; } const char *omega_gpu_matmul_rc_name(int rc) { switch (rc) { @@ -90,71 +76,46 @@ const char *omega_gpu_matmul_rc_name(int rc) { } } -int omega_gpu_matmul_is_blocked(void) { return g.blocked ? 1 : 0; } - -/* ---- device lifetime (caller holds g_mu) ---- */ - -static int dev_alloc(size_t bytes, NvrmMem *out) { - return nvrm_alloc_gpu_uncached(&g.ctx.rm, page_up(bytes), out) == 0 ? 0 : -1; -} +int omega_gpu_matmul_is_blocked(void) { return omega_gpu_session_is_blocked(); } -static void dev_free(NvrmMem *m) { - if (m->cpu) (void)nvrm_free(&g.ctx.rm, m); - memset(m, 0, sizeof *m); -} +/* ---- device-side state (caller holds the session lock) ---- */ static void cache_clear_locked(void) { for (unsigned i = 0; i < CACHE_SLOTS; i++) { CacheSlot *s = &g.cache[i]; if (!s->valid) continue; omega_blackwell_kernel_free(&s->kernel); - if (g.open && !g.blocked) dev_free(&s->code); + omega_gpu_session_free(&s->code); memset(s, 0, sizeof *s); } g.cache_next = 0; } -static int dev_open_locked(void) { - if (g.blocked) return -1; - if (g.open) return 0; - memset(&g.ctx, 0, sizeof g.ctx); - if (m16_native_open(&g.ctx) != 0) { FAILAT("m16_native_open"); return -1; } - if (m16_native_create_channel(&g.ctx) != 0) { FAILAT("m16_native_create_channel"); m16_native_close(&g.ctx); return -1; } - if (dev_alloc(0x10000, &g.pb) || dev_alloc(PAGE, &g.cbank) || dev_alloc(PAGE, &g.marker) || dev_alloc(0x10000, &g.qmd)) { - FAILAT("device scratch alloc"); - m16_native_close(&g.ctx); - memset(&g.pb, 0, sizeof g.pb); memset(&g.cbank, 0, sizeof g.cbank); - memset(&g.marker, 0, sizeof g.marker); memset(&g.qmd, 0, sizeof g.qmd); - return -1; - } - g.ctx.pb_mem = g.pb; /* m16_native_enqueue_methods copies the method stream here */ - g.open = true; - return 0; +/* Called by the session (lock held, device still open) right before it closes. */ +static void on_session_close(void) { + cache_clear_locked(); + omega_gpu_session_scratch_free(&g.a_buf); + omega_gpu_session_scratch_free(&g.c_buf); } -void omega_gpu_device_close(void) { - pthread_mutex_lock(&g_mu); - if (g.open && !g.blocked) { - cache_clear_locked(); - dev_free(&g.a_buf); dev_free(&g.c_buf); g.a_cap = g.c_cap = 0; - dev_free(&g.qmd); dev_free(&g.marker); dev_free(&g.cbank); dev_free(&g.pb); - m16_native_close(&g.ctx); - g.open = false; - } - pthread_mutex_unlock(&g_mu); +static OmegaGpuSession *dev_open_locked(void) { + if (!g.hooked) { (void)omega_gpu_session_on_close(on_session_close); g.hooked = true; } + return omega_gpu_session_open(); } +void omega_gpu_device_close(void) { omega_gpu_session_close(); } + void omega_gpu_matmul_cache_clear(void) { - pthread_mutex_lock(&g_mu); + omega_gpu_session_lock(); cache_clear_locked(); - pthread_mutex_unlock(&g_mu); + omega_gpu_session_unlock(); } void omega_gpu_matmul_set_cta_budget(uint32_t ctas) { - pthread_mutex_lock(&g_mu); + omega_gpu_session_lock(); g.cta_budget = ctas ? ctas : OMEGA_GPU_MATMUL_MAX_CTAS; cache_clear_locked(); - pthread_mutex_unlock(&g_mu); + omega_gpu_session_unlock(); } uint32_t omega_gpu_matmul_cta_budget(void) { return g.cta_budget; } @@ -162,23 +123,13 @@ uint32_t omega_gpu_matmul_cta_budget(void) { return g.cta_budget; } void omega_gpu_matmul_set_oracle(int on) { g.oracle = on ? 1 : 0; } void omega_gpu_matmul_test_set_mutant(int on) { - pthread_mutex_lock(&g_mu); + omega_gpu_session_lock(); g.mutant = on ? 1 : 0; cache_clear_locked(); - pthread_mutex_unlock(&g_mu); + omega_gpu_session_unlock(); } -/* Staging buffer at least `bytes` long (grown by reallocation; contents not kept). */ -static int staging(NvrmMem *buf, size_t *cap, size_t bytes) { - if (*cap >= bytes && buf->cpu) return 0; - dev_free(buf); - *cap = 0; - if (dev_alloc(bytes, buf) != 0) return -1; - *cap = buf->size; - return 0; -} - -/* ---- kernel cache (caller holds g_mu, device open) ---- */ +/* ---- kernel cache (caller holds the lock, device open) ---- */ static int kernel_for(uint32_t kp, uint32_t np, uint32_t grid_x, CacheSlot **out, bool *hit) { for (unsigned i = 0; i < CACHE_SLOTS; i++) { @@ -196,113 +147,30 @@ static int kernel_for(uint32_t kp, uint32_t np, uint32_t grid_x, CacheSlot **out if (omega_blackwell_codegen_matmul_tensor_loop(&spec, grid_x, g.mutant, &kernel) != 0 || !kernel.code || kernel.code_size == 0) return OMEGA_GPU_MATMUL_CODEGEN_FAIL; NvrmMem code; - if (dev_alloc(kernel.code_size, &code) != 0) { FAILAT("kernel code alloc"); omega_blackwell_kernel_free(&kernel); return OMEGA_GPU_MATMUL_CHIP_FAIL; } + if (omega_gpu_session_alloc(kernel.code_size, &code) != 0) { omega_blackwell_kernel_free(&kernel); return OMEGA_GPU_MATMUL_CHIP_FAIL; } memcpy(code.cpu, kernel.code, kernel.code_size); CacheSlot *s = &g.cache[g.cache_next]; g.cache_next = (g.cache_next + 1) % CACHE_SLOTS; - if (s->valid) { omega_blackwell_kernel_free(&s->kernel); dev_free(&s->code); } + if (s->valid) { omega_blackwell_kernel_free(&s->kernel); omega_gpu_session_free(&s->code); } s->valid = true; s->kp = kp; s->np = np; s->grid_x = grid_x; s->mutant = g.mutant; s->spec = spec; s->kernel = kernel; s->code = code; *out = s; *hit = false; return OMEGA_GPU_MATMUL_OK; } -/* ---- one launch (caller holds g_mu, device open, not blocked) ---- */ +/* ---- one launch (caller holds the lock, device open, not blocked) ---- */ static int launch(const CacheSlot *ks, uint64_t a_va, uint64_t b_va, uint64_t c_va, uint32_t grid_x, uint32_t grid_y, uint64_t *elapsed_ns, uint32_t *marker_out) { - const uint32_t threads_x = 32, threads_y = 1; - uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; uint32_t cbank_args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS]; - omega_blackwell_build_cbank_driver_2d(cbank_data, g.cbank.va, threads_x, threads_y, grid_x, grid_y); omega_blackwell_build_cbank_args_matmul(cbank_args, a_va, b_va, c_va, grid_y * 16u, ks->kp, ks->np); - memcpy(g.cbank.cpu, cbank_data, sizeof cbank_data); - memcpy((uint8_t *)g.cbank.cpu + 0x380, cbank_args, sizeof cbank_args); - - const uint64_t qmd0_va = g.qmd.va, qmd1_va = g.qmd.va + 0x1000, sem_va = g.qmd.va + 0x2000, scratch_va = g.qmd.va + 0x4000; - uint32_t gpr = ks->kernel.gpr_count > 64u ? round_up(ks->kernel.gpr_count, 8u) : 64u; - OmegaBlackwellQmdConfig cfg = { - .code_va = ks->code.va, .cbank_va = g.cbank.va, .scratch_va = scratch_va, .sem_va = sem_va, - .qmd0_va = qmd0_va, .qmd1_va = qmd1_va, .num_elements = (size_t)grid_x * grid_y * 128u, - .threads_per_block = 32, .grid_width = grid_x * grid_y, .threads_x = threads_x, .threads_y = threads_y, - .grid_x = grid_x, .grid_y = grid_y, .gpr_count = gpr, + OmegaGpuLaunch L = { + .code_va = ks->code.va, .gpr_count = ks->kernel.gpr_count, + .threads_x = 32, .threads_y = 1, .grid_x = grid_x, .grid_y = grid_y, + .num_elements = (size_t)grid_x * grid_y * 128u, + .args = cbank_args, .n_args = OMEGA_BW_CBANK_MATMUL_ARGS_WORDS, .timeout_ms = MARKER_TIMEOUT_MS, }; - uint32_t qmd0_words[OMEGA_BW_QMD_WORDS], qmd1_words[OMEGA_BW_QMD_WORDS]; - omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va); - omega_blackwell_build_qmd1(qmd1_words, &cfg); - if (omega_blackwell_verify_qmd_invariants(qmd1_words) != 0) { FAILAT("qmd invariants"); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - memcpy(g.qmd.cpu, qmd0_words, sizeof qmd0_words); - memcpy((uint8_t *)g.qmd.cpu + 0x1000, qmd1_words, sizeof qmd1_words); - - volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)g.qmd.cpu + 0x2000); - volatile uint32_t *hmarker = (volatile uint32_t *)g.marker.cpu; - volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)g.marker.cpu + 0x10); - *hsem = 0; *hmarker = 0; *hmarker2 = 0; - __asm__ volatile("dsb sy" ::: "memory"); - - uint32_t pb[1024]; - size_t n = 0; - memcpy(&pb[n], SETUP_WORDS, sizeof SETUP_WORDS); n += sizeof SETUP_WORDS / 4; - /* Invalidate the SM instruction, constant and data caches before this launch. - * Kernel code lives in GPU-uncached memory, but the SM instruction cache is - * not coherent with host writes: when a cache slot is evicted and its code - * address is reused for a different kernel, the chip ran stale instructions - * (FB1-CUT1B-f629798 sweep: 8x1024x8, 192x16x192, 512x16x64 unwritten, - * 128x16x512 hung, all after the eighth distinct kernel). Method and bits - * from NVIDIA open-gpu-doc classes/compute/clcec0.h (BLACKWELL_COMPUTE_B): - * NVCEC0_INVALIDATE_SHADER_CACHES 0x021c, INSTRUCTION 0:0, DATA 4:4, - * CONSTANT 12:12 (the 0x021c form waits for idle first). Shared constants in - * omega_blackwell_submit.h so every launcher emits the same words. */ - pb[n++] = nvrm_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1); pb[n++] = OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL; - /* constant bank 0: driver words then our arguments at 0x380 (inline upload, same as cut 1) */ - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(g.cbank.va >> 32); pb[n++] = (uint32_t)g.cbank.va; - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (224u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[n], cbank_data, 224 * 4); n += 224; - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((g.cbank.va + 0x380) >> 32); pb[n++] = (uint32_t)(g.cbank.va + 0x380); - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000028; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (10u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); - memcpy(&pb[n], cbank_args, 10 * 4); n += 10; - /* QMD0 (null grid, dependence 2) */ - pb[n++] = (98u << 16) | (1u << 13) | (0x0318 >> 2) | (2u << 28); - pb[n++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd0_va >> 8); - memcpy(&pb[n], qmd0_words, 96 * 4); n += 96; - /* intermediate semaphore init */ - pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va; - pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001; - pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; - pb[n++] = (1u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); - pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; - /* QMD1 (the kernel) */ - pb[n++] = (98u << 16) | (1u << 13) | (0x0318 >> 2) | (2u << 28); - pb[n++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd1_va >> 8); - memcpy(&pb[n], qmd1_words, 96 * 4); n += 96; - /* first marker */ - pb[n++] = nvrm_mthd(0, 0x005c, 5); - pb[n++] = (uint32_t)g.marker.va; pb[n++] = (uint32_t)(g.marker.va >> 32); - pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); - /* C3 tail: L2_FLUSH_DIRTY, then the second release on the uncached marker page */ - pb[n++] = nvrm_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27); - pb[n++] = nvrm_mthd(0, 0x005c, 5); - pb[n++] = (uint32_t)(g.marker.va + 0x10); pb[n++] = (uint32_t)((g.marker.va + 0x10) >> 32); - pb[n++] = OMEGA_BW_MARKER2_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); - - uint64_t t0 = now_ns(); - if (m16_native_submit_methods(&g.ctx, pb, n) != 0) { FAILAT("submit_methods"); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - if (m16_native_wait_marker(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, MARKER_TIMEOUT_MS) != 0 || - m16_native_wait_marker(hmarker2, OMEGA_BW_MARKER2_PAYLOAD, MARKER_TIMEOUT_MS) != 0) { - g.blocked = true; (void)FAILAT("marker wait timed out (latched)"); /* uncertain completion: keep everything, refuse every later call */ - return OMEGA_GPU_MATMUL_CHIP_FAIL; - } - __asm__ volatile("dsb sy" ::: "memory"); - uint64_t t1 = now_ns(); - nvrm_retire(&g.ctx.rm, g.ctx.rm.put); /* both releases landed: the GPFIFO entry is consumed */ - if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { FAILAT("intermediate semaphore not DONE"); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - if (elapsed_ns) *elapsed_ns += t1 - t0; - if (marker_out) *marker_out = *hmarker; - return OMEGA_GPU_MATMUL_OK; + return omega_gpu_session_launch(&L, elapsed_ns, marker_out) == 0 ? OMEGA_GPU_MATMUL_OK : OMEGA_GPU_MATMUL_CHIP_FAIL; } /* ---- tensors ---- */ @@ -320,9 +188,9 @@ int omega_gpu_tensor_upload_bf16(uint32_t k, uint32_t n, const uint16_t *b, Omeg if (!t) return OMEGA_GPU_MATMUL_BAD_ARGS; t->k = k; t->n = n; t->kp = round_up(k, OMEGA_GPU_MATMUL_TILE_K); t->np = round_up(n, OMEGA_GPU_MATMUL_TILE_N); int rc = OMEGA_GPU_MATMUL_OK; - pthread_mutex_lock(&g_mu); - if (dev_open_locked() != 0 || (FAILAT("tensor alloc"), dev_alloc((size_t)t->kp * t->np * 2u, &t->mem) != 0)) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; - pthread_mutex_unlock(&g_mu); + omega_gpu_session_lock(); + if (!dev_open_locked() || omega_gpu_session_alloc((size_t)t->kp * t->np * 2u, &t->mem) != 0) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; + omega_gpu_session_unlock(); if (rc != OMEGA_GPU_MATMUL_OK) { free(t); return rc; } uint16_t *d = t->mem.cpu; if (t->np != n || t->kp != k) memset(d, 0, (size_t)t->kp * t->np * 2u); @@ -347,9 +215,9 @@ int omega_gpu_tensor_upload_f32(uint32_t k, uint32_t n, const float *b, OmegaGpu void omega_gpu_tensor_free(OmegaGpuTensor *t) { if (!t) return; - pthread_mutex_lock(&g_mu); - if (g.open && !g.blocked) dev_free(&t->mem); - pthread_mutex_unlock(&g_mu); + omega_gpu_session_lock(); + omega_gpu_session_free(&t->mem); + omega_gpu_session_unlock(); free(t); } @@ -358,10 +226,9 @@ void omega_gpu_tensor_free(OmegaGpuTensor *t) { static int matmul_core(uint32_t m, const uint16_t *a, const OmegaGpuTensor *b, float *c, OmegaGpuMatmulInfo *info) { const uint32_t k = b->k, n = b->n, kp = b->kp, np = b->np; const uint32_t mp = round_up(m, OMEGA_GPU_MATMUL_TILE_M), mt = mp / 16, nt = np / 8; - pthread_mutex_lock(&g_mu); + omega_gpu_session_lock(); int rc = OMEGA_GPU_MATMUL_OK; - if (g.blocked && FAILAT("process latched")) { pthread_mutex_unlock(&g_mu); return OMEGA_GPU_MATMUL_CHIP_FAIL; } - if (dev_open_locked() != 0) { pthread_mutex_unlock(&g_mu); return OMEGA_GPU_MATMUL_CHIP_FAIL; } + if (!dev_open_locked()) { omega_gpu_session_unlock(); return OMEGA_GPU_MATMUL_CHIP_FAIL; } const uint32_t budget = g.cta_budget ? g.cta_budget : OMEGA_GPU_MATMUL_MAX_CTAS; /* rows per launch: all of them unless the row tiles alone exceed the budget */ uint32_t rows_per_launch = mt <= budget ? mp : budget * 16u; @@ -374,14 +241,14 @@ static int matmul_core(uint32_t m, const uint16_t *a, const OmegaGpuTensor *b, f strncpy(info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)", sizeof info->target_chip - 1); info->sm_architecture = 121; } - if (staging(&g.a_buf, &g.a_cap, (size_t)mp * kp * 2u) != 0 || staging(&g.c_buf, &g.c_cap, (size_t)mp * np * 4u) != 0) { - pthread_mutex_unlock(&g_mu); return OMEGA_GPU_MATMUL_CHIP_FAIL; + if (omega_gpu_session_scratch(&g.a_buf, (size_t)mp * kp * 2u) != 0 || omega_gpu_session_scratch(&g.c_buf, (size_t)mp * np * 4u) != 0) { + omega_gpu_session_unlock(); return OMEGA_GPU_MATMUL_CHIP_FAIL; } /* activation rows in, zero padded; result rows poisoned */ - uint16_t *ad = g.a_buf.cpu; + uint16_t *ad = g.a_buf.mem.cpu; if (mp != m || kp != k) memset(ad, 0, (size_t)mp * kp * 2u); for (uint32_t r = 0; r < m; r++) memcpy(&ad[(size_t)r * kp], &a[(size_t)r * k], (size_t)k * 2u); - float *cd = g.c_buf.cpu; + float *cd = g.c_buf.mem.cpu; for (size_t i = 0; i < (size_t)m * np; i++) cd[i] = POISON_F32; __asm__ volatile("dsb sy" ::: "memory"); @@ -392,7 +259,7 @@ static int matmul_core(uint32_t m, const uint16_t *a, const OmegaGpuTensor *b, f rc = kernel_for(kp, np, grid_x, &ks, &hit); if (rc != OMEGA_GPU_MATMUL_OK) break; if (info && !hit) info->kernel_cache_hit = false; - rc = launch(ks, g.a_buf.va + (uint64_t)r0 * kp * 2u, b->mem.va, g.c_buf.va + (uint64_t)r0 * np * 4u, + rc = launch(ks, g.a_buf.mem.va + (uint64_t)r0 * kp * 2u, b->mem.va, g.c_buf.mem.va + (uint64_t)r0 * np * 4u, grid_x, grid_y, info ? &info->elapsed_ns : NULL, info ? &info->completion_marker : NULL); if (info) info->chip_calls++; } @@ -404,9 +271,9 @@ static int matmul_core(uint32_t m, const uint16_t *a, const OmegaGpuTensor *b, f for (uint32_t j = 0; j < n; j++) if (row[j] == POISON_F32) unchanged++; memcpy(&c[(size_t)r * n], row, (size_t)n * sizeof *c); } - if (unchanged) { FAILAT("output poison survived"); rc = OMEGA_GPU_MATMUL_CHIP_FAIL; } + if (unchanged && FAILAT("output poison survived")) rc = OMEGA_GPU_MATMUL_CHIP_FAIL; } - pthread_mutex_unlock(&g_mu); + omega_gpu_session_unlock(); return rc; } diff --git a/src/omega_gpu_session.c b/src/omega_gpu_session.c new file mode 100644 index 000000000..c66d99385 --- /dev/null +++ b/src/omega_gpu_session.c @@ -0,0 +1,224 @@ +/* + * omega_gpu_session.c: FB-1 cut 4b. See the header for the contract. + * + * The launch words are the ones omega_gpu_matmul_api.c (cut 1b, chip PASS + * FB1-CUT1B-4345406) and omega_gpu_elementwise_api.c (cut 4, FB1-CUT4-0d0241a) + * both emitted; the two were identical except for the argument word count, which + * is now a parameter. Nothing about the sequence changed in this cut. + */ +#include "omega_gpu_session.h" +#include "omega_blackwell_qmd.h" +#include "omega_blackwell_submit.h" +#include "nvrm.h" +#include <pthread.h> +#include <stdio.h> +#include <string.h> +#include <time.h> + +#define PAGE 0x1000ull + +/* Same words as src/omega_blackwell_submit.c SETUP_WORDS (compute class setup). */ +static const uint32_t SETUP_WORDS[18] = { + 0x20012061, 0x0000cec0, 0x20012092, 0x00000001, 0x200120a8, 0x0000000f, 0x2001255d, 0x00000003, + 0x2001255e, 0x20000000, 0x2001255f, 0x000fffff, 0x20012557, 0x00000003, 0x20012558, 0x22000000, + 0x20012559, 0x00000000, +}; + +static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER; +static OmegaGpuSession g_s; +static bool g_open, g_blocked; +static char g_err[320] = ""; +static void (*g_hooks[8])(void); +static unsigned g_nhooks; + +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 size_t page_up(size_t b) { b = (b + PAGE - 1) & ~(PAGE - 1); return b < PAGE ? PAGE : b; } + +const char *omega_gpu_session_last_error(void) { return g_err; } +void omega_gpu_session_set_error(const char *stage) { + snprintf(g_err, sizeof g_err, "%s", stage ? stage : ""); +} +static void fail_rm(const char *stage, const Nvrm *rm) { + /* the driver text (RM class / ioctl errno / RM status, nvrm.c fail()) travels with the stage */ + snprintf(g_err, sizeof g_err, "%s: %s", stage, rm && rm->err[0] ? rm->err : "(no driver text)"); +} + +void omega_gpu_session_lock(void) { pthread_mutex_lock(&g_mu); } +void omega_gpu_session_unlock(void) { pthread_mutex_unlock(&g_mu); } +bool omega_gpu_session_is_open(void) { return g_open; } +int omega_gpu_session_is_blocked(void) { return g_blocked ? 1 : 0; } + +int omega_gpu_session_alloc(size_t bytes, NvrmMem *out) { + if (!g_open || g_blocked) { omega_gpu_session_set_error("alloc without open device"); return -1; } + if (nvrm_alloc_gpu_uncached(&g_s.ctx.rm, page_up(bytes), out) != 0) { fail_rm("nvrm_alloc_gpu_uncached", &g_s.ctx.rm); memset(out, 0, sizeof *out); return -1; } + return 0; +} + +void omega_gpu_session_free(NvrmMem *m) { + if (m->cpu && g_open && !g_blocked) (void)nvrm_free(&g_s.ctx.rm, m); + memset(m, 0, sizeof *m); +} + +int omega_gpu_session_scratch(OmegaGpuScratch *s, size_t bytes) { + if (bytes > s->high_water) s->high_water = bytes; + if (s->cap >= bytes && s->mem.cpu) return 0; + omega_gpu_session_free(&s->mem); + s->cap = 0; + if (omega_gpu_session_alloc(s->high_water, &s->mem) != 0) return -1; + s->cap = (size_t)s->mem.size; + return 0; +} + +void omega_gpu_session_scratch_free(OmegaGpuScratch *s) { + omega_gpu_session_free(&s->mem); + s->cap = 0; +} + +static void free_session_buffers(void) { + omega_gpu_session_free(&g_s.qmd); omega_gpu_session_free(&g_s.marker); + omega_gpu_session_free(&g_s.cbank); omega_gpu_session_free(&g_s.pb); +} + +OmegaGpuSession *omega_gpu_session_open(void) { + if (g_blocked) { omega_gpu_session_set_error("process latched"); return NULL; } + if (g_open) return &g_s; + uint64_t t0 = now_ns(); + memset(&g_s.ctx, 0, sizeof g_s.ctx); + /* nvrm_open directly (m16_native_open is memset + nvrm_open + nvrm_close on + * failure) so the driver's own failure text survives into the stage name. */ + if (nvrm_open(&g_s.ctx.rm) != 0) { fail_rm("nvrm_open", &g_s.ctx.rm); (void)nvrm_close(&g_s.ctx.rm); return NULL; } + if (m16_native_create_channel(&g_s.ctx) != 0) { fail_rm("m16_native_create_channel", &g_s.ctx.rm); (void)m16_native_close(&g_s.ctx); return NULL; } + g_open = true; /* so alloc / free work during the rest of the open */ + if (omega_gpu_session_alloc(0x10000, &g_s.pb) || omega_gpu_session_alloc(PAGE, &g_s.cbank) || + omega_gpu_session_alloc(PAGE, &g_s.marker) || omega_gpu_session_alloc(0x10000, &g_s.qmd)) { + char keep[sizeof g_err]; memcpy(keep, g_err, sizeof keep); + free_session_buffers(); + g_open = false; + (void)m16_native_close(&g_s.ctx); + snprintf(g_err, sizeof g_err, "session scratch alloc (%s)", keep); + return NULL; + } + g_s.ctx.pb_mem = g_s.pb; /* m16_native_enqueue_methods copies the method stream here */ + g_s.opens++; + g_s.last_open_ns = now_ns() - t0; + return &g_s; +} + +int omega_gpu_session_on_close(void (*hook)(void)) { /* caller holds the lock (the APIs register from their open path) */ + if (!hook) return -1; + int rc = 0; + bool seen = false; + for (unsigned i = 0; i < g_nhooks; i++) if (g_hooks[i] == hook) seen = true; + if (!seen) { if (g_nhooks < sizeof g_hooks / sizeof g_hooks[0]) g_hooks[g_nhooks++] = hook; else rc = -1; } + return rc; +} + +void omega_gpu_session_close(void) { + pthread_mutex_lock(&g_mu); + if (g_open && !g_blocked) { + for (unsigned i = 0; i < g_nhooks; i++) g_hooks[i](); + free_session_buffers(); + (void)m16_native_close(&g_s.ctx); + g_open = false; + } + pthread_mutex_unlock(&g_mu); +} + +static uint32_t round_up(uint32_t v, uint32_t q) { return (v + q - 1) / q * q; } + +int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint32_t *marker_out) { + if (!g_open || g_blocked) { omega_gpu_session_set_error(g_blocked ? "process latched" : "launch without open device"); return -1; } + if (!L || !L->args || L->n_args == 0 || L->n_args > OMEGA_GPU_SESSION_MAX_ARGS || L->threads_x == 0 || L->grid_x == 0 || L->grid_y == 0) { + omega_gpu_session_set_error("launch arguments"); return -1; + } + const uint32_t threads_y = L->threads_y ? L->threads_y : 1; + uint32_t cbank_data[OMEGA_BW_CBANK_DRIVER_WORDS]; + omega_blackwell_build_cbank_driver_2d(cbank_data, g_s.cbank.va, L->threads_x, threads_y, L->grid_x, L->grid_y); + memcpy(g_s.cbank.cpu, cbank_data, sizeof cbank_data); + memcpy((uint8_t *)g_s.cbank.cpu + 0x380, L->args, (size_t)L->n_args * 4u); + + const uint64_t qmd0_va = g_s.qmd.va, qmd1_va = g_s.qmd.va + 0x1000, sem_va = g_s.qmd.va + 0x2000, scratch_va = g_s.qmd.va + 0x4000; + uint32_t gpr = L->gpr_count > 64u ? round_up(L->gpr_count, 8u) : 64u; + OmegaBlackwellQmdConfig cfg = { + .code_va = L->code_va, .cbank_va = g_s.cbank.va, .scratch_va = scratch_va, .sem_va = sem_va, + .qmd0_va = qmd0_va, .qmd1_va = qmd1_va, .num_elements = L->num_elements, + .threads_per_block = L->threads_x, .grid_width = L->grid_x * L->grid_y, .threads_x = L->threads_x, .threads_y = threads_y, + .grid_x = L->grid_x, .grid_y = L->grid_y, .gpr_count = gpr, + }; + uint32_t qmd0_words[OMEGA_BW_QMD_WORDS], qmd1_words[OMEGA_BW_QMD_WORDS]; + omega_blackwell_build_qmd0(qmd0_words, qmd0_va, qmd1_va); + omega_blackwell_build_qmd1(qmd1_words, &cfg); + if (omega_blackwell_verify_qmd_invariants(qmd1_words) != 0) { omega_gpu_session_set_error("qmd invariants"); return -1; } + memcpy(g_s.qmd.cpu, qmd0_words, sizeof qmd0_words); + memcpy((uint8_t *)g_s.qmd.cpu + 0x1000, qmd1_words, sizeof qmd1_words); + + volatile uint32_t *hsem = (volatile uint32_t *)((uint8_t *)g_s.qmd.cpu + 0x2000); + volatile uint32_t *hmarker = (volatile uint32_t *)g_s.marker.cpu; + volatile uint32_t *hmarker2 = (volatile uint32_t *)((uint8_t *)g_s.marker.cpu + 0x10); + *hsem = 0; *hmarker = 0; *hmarker2 = 0; + __asm__ volatile("dsb sy" ::: "memory"); + + uint32_t pb[1024]; + size_t n = 0; + memcpy(&pb[n], SETUP_WORDS, sizeof SETUP_WORDS); n += sizeof SETUP_WORDS / 4; + /* Invalidate the SM instruction, constant and data caches before this launch + * (cut 1b finding: a reused code address served stale instructions; clcec0.h + * NVCEC0_INVALIDATE_SHADER_CACHES 0x021c, bits INSTRUCTION 0, DATA 4, CONSTANT 12). */ + pb[n++] = nvrm_mthd(1, OMEGA_BW_MTHD_INVALIDATE_SHADER_CACHES, 1); pb[n++] = OMEGA_BW_INVALIDATE_SHADER_CACHES_ALL; + /* constant bank 0: driver words, then our arguments at 0x380 (inline upload) */ + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(g_s.cbank.va >> 32); pb[n++] = (uint32_t)g_s.cbank.va; + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000380; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (224u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); + memcpy(&pb[n], cbank_data, 224 * 4); n += 224; + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)((g_s.cbank.va + 0x380) >> 32); pb[n++] = (uint32_t)(g_s.cbank.va + 0x380); + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = L->n_args * 4u; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (L->n_args << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); + memcpy(&pb[n], L->args, (size_t)L->n_args * 4u); n += L->n_args; + /* QMD0 (null grid, dependence 2) */ + pb[n++] = (98u << 16) | (1u << 13) | (0x0318 >> 2) | (2u << 28); + pb[n++] = (1u << 30) | (uint32_t)((qmd0_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd0_va >> 8); + memcpy(&pb[n], qmd0_words, 96 * 4); n += 96; + /* intermediate semaphore init */ + pb[n++] = nvrm_mthd(1, 0x0188, 2); pb[n++] = (uint32_t)(sem_va >> 32); pb[n++] = (uint32_t)sem_va; + pb[n++] = nvrm_mthd(1, 0x0180, 2); pb[n++] = 0x00000004; pb[n++] = 0x00000001; + pb[n++] = nvrm_mthd(1, 0x01b0, 1); pb[n++] = 0x00000041; + pb[n++] = (1u << 16) | (1u << 13) | (0x01b4 >> 2) | (6u << 28); + pb[n++] = OMEGA_BW_SEMAPHORE_INTERMEDIATE_INIT; + /* QMD1 (the kernel) */ + pb[n++] = (98u << 16) | (1u << 13) | (0x0318 >> 2) | (2u << 28); + pb[n++] = (1u << 30) | (uint32_t)((qmd1_va >> 40) & 0x1ff); pb[n++] = (uint32_t)(qmd1_va >> 8); + memcpy(&pb[n], qmd1_words, 96 * 4); n += 96; + /* first marker */ + pb[n++] = nvrm_mthd(0, 0x005c, 5); + pb[n++] = (uint32_t)g_s.marker.va; pb[n++] = (uint32_t)(g_s.marker.va >> 32); + pb[n++] = OMEGA_BW_MARKER_COMPLETION_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); + /* C3 tail: L2_FLUSH_DIRTY, then the second release on the uncached marker page */ + pb[n++] = nvrm_mthd(0, 0x0028, 4); pb[n++] = 0; pb[n++] = 0; pb[n++] = 0; pb[n++] = (0x10u << 27); + pb[n++] = nvrm_mthd(0, 0x005c, 5); + pb[n++] = (uint32_t)(g_s.marker.va + 0x10); pb[n++] = (uint32_t)((g_s.marker.va + 0x10) >> 32); + pb[n++] = OMEGA_BW_MARKER2_PAYLOAD; pb[n++] = 0; pb[n++] = 0x1 | (1u << 20); + + uint64_t t0 = now_ns(); + if (m16_native_submit_methods(&g_s.ctx, pb, n) != 0) { fail_rm("submit_methods", &g_s.ctx.rm); return -1; } + if (m16_native_wait_marker(hmarker, OMEGA_BW_MARKER_COMPLETION_PAYLOAD, L->timeout_ms) != 0 || + m16_native_wait_marker(hmarker2, OMEGA_BW_MARKER2_PAYLOAD, L->timeout_ms) != 0) { + g_blocked = true; /* uncertain completion: keep everything, refuse every later call */ + omega_gpu_session_set_error("marker wait timed out (latched)"); + return -1; + } + __asm__ volatile("dsb sy" ::: "memory"); + uint64_t t1 = now_ns(); + nvrm_retire(&g_s.ctx.rm, g_s.ctx.rm.put); /* both releases landed: the GPFIFO entry is consumed */ + if (*hsem != OMEGA_BW_SEMAPHORE_INTERMEDIATE_DONE) { omega_gpu_session_set_error("intermediate semaphore not DONE"); return -1; } + if (elapsed_ns) *elapsed_ns += t1 - t0; + if (marker_out) *marker_out = *hmarker; + return 0; +} + +uint32_t omega_gpu_session_open_count(void) { return g_s.opens; } diff --git a/src/omega_gpu_session.h b/src/omega_gpu_session.h new file mode 100644 index 000000000..bcd5c06e4 --- /dev/null +++ b/src/omega_gpu_session.h @@ -0,0 +1,125 @@ +#ifndef OMEGA_GPU_SESSION_H +#define OMEGA_GPU_SESSION_H +/* + * omega_gpu_session: the ONE persistent device for the native GPU APIs + * (FB-1 cut 4b, 2026-10-04). Shared by omega_gpu_matmul_api, + * omega_gpu_elementwise_api and omega_gpu_attention_api. + * + * Before this cut the matmul API kept its own device open for the process while + * the elementwise and attention APIs opened a client, device, VA space and + * channel for EVERY call and closed them again (~40 ms per call against ~0.1 ms + * of chip time; TinyLlama decode makes ~3500 elementwise calls per 32 tokens, + * sovereign-core cut 3c: 0.207 tok/s). Now: + * - one RM client / device / channel per process, opened on the first launch of + * any API and kept until omega_gpu_session_close(); + * - one pushbuffer, constant bank, marker page and QMD page, reused per launch; + * - staging buffers owned by the callers grow to a high-water mark and are reused + * (omega_gpu_session_scratch); + * - every buffer is GPU-uncached (nvos.h NVOS32_ATTR2_GPU_CACHEABLE, read + * 2026-10-04: "For system memory this will not be coherent with direct CPU + * mappings"; the default for system memory is uncached), because the host + * writes inputs the chip then reads, and polls the markers the chip writes; + * - every launch keeps the chip-proven sequence: shader-cache invalidate + * (clcec0.h NVCEC0_INVALIDATE_SHADER_CACHES, cut 1b finding), constant bank + * upload, QMD0 / QMD1, first marker, L2_FLUSH_DIRTY, second marker on the + * uncached page (C3 tail, omega#225/#230), GPFIFO retire after completion. + * - an uncertain completion (marker wait timed out) latches the process: nothing + * is freed or closed (the chip may still be running) and every later launch + * of every API is refused, as the engine does (omega_gpu_engine.h). + * + * Threading: one process-wide mutex. A caller takes omega_gpu_session_lock(), + * does its whole call (kernel lookup, staging, launches, readback) and unlocks. + * Calls from several threads therefore serialise on the device; that is the + * documented model (one channel, one GPFIFO). + * + * Diagnostics (cut 4b flake investigation): every failure names its stage + * (omega_gpu_session_last_error) and an open failure carries the driver text + * (Nvrm.err: RM class, ioctl errno, RM status) so a first-call failure is never + * reported as a bare CHIP_FAIL again. + */ +#include <stdbool.h> +#include <stddef.h> +#include <stdint.h> +#include "m16_native.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + M16NativeContext ctx; + NvrmMem pb, cbank, marker, qmd; /* per-launch scratch, owned by the session */ + uint32_t opens; /* device opens in this process */ + uint64_t last_open_ns; /* wall time of the last successful open */ +} OmegaGpuSession; + +/* A caller-owned staging buffer that grows to its high-water mark. */ +typedef struct { + NvrmMem mem; + size_t cap; /* usable bytes */ + size_t high_water; /* largest request so far */ +} OmegaGpuScratch; + +/* One launch: a kernel already resident at code_va, the argument words for + * constant bank 0 at 0x380 (buffer addresses then parameters), the grid. */ +typedef struct { + uint64_t code_va; + uint32_t gpr_count; /* registers the QMD declares (multiple of 8, >= 64 in practice) */ + uint32_t threads_x, threads_y; + uint32_t grid_x, grid_y; + size_t num_elements; /* QMD config num_elements (kept per API for identical words) */ + const uint32_t *args; /* n_args words written at cbank + 0x380 */ + uint32_t n_args; /* <= OMEGA_GPU_SESSION_MAX_ARGS */ + uint64_t timeout_ms; /* marker wait; past it the process latches */ +} OmegaGpuLaunch; +#define OMEGA_GPU_SESSION_MAX_ARGS 32u + +/* Take the session lock. Never fails; does not touch the device. */ +void omega_gpu_session_lock(void); +void omega_gpu_session_unlock(void); + +/* Caller holds the lock. Opens the device on first use. NULL when the process is + * latched or the open failed (stage in omega_gpu_session_last_error). */ +OmegaGpuSession *omega_gpu_session_open(void); +bool omega_gpu_session_is_open(void); + +/* 1 once an uncertain completion has latched this process. */ +int omega_gpu_session_is_blocked(void); + +/* Caller holds the lock, device open. GPU-uncached allocation, page rounded. */ +int omega_gpu_session_alloc(size_t bytes, NvrmMem *out); +void omega_gpu_session_free(NvrmMem *m); /* no-op when latched or closed; zeroes *m */ + +/* Caller holds the lock, device open. Makes s->mem at least `bytes` long + * (reallocated when it grows; contents are not kept). */ +int omega_gpu_session_scratch(OmegaGpuScratch *s, size_t bytes); +void omega_gpu_session_scratch_free(OmegaGpuScratch *s); + +/* Caller holds the lock, device open, not latched. Submits one launch and waits + * for both markers. 0 on success; -1 with the stage named on failure. A marker + * timeout latches the process. elapsed_ns (submit to second marker) and the + * observed first marker word are added / stored when the pointers are given. */ +int omega_gpu_session_launch(const OmegaGpuLaunch *L, uint64_t *elapsed_ns, uint32_t *marker_out); + +/* Stage of the most recent failure ("" if none). Shared by every API. */ +const char *omega_gpu_session_last_error(void); +void omega_gpu_session_set_error(const char *stage); + +/* Caller holds the lock. Register a function the session calls (lock held, device + * still open) right before it closes, so an API can drop its resident kernels and + * scratch. Up to 8; the same function is registered once. (Taking the lock inside + * deadlocked the first call of every API on 2026-10-04: the APIs register from + * their open path, which already holds it.) */ +int omega_gpu_session_on_close(void (*hook)(void)); + +/* Close the device and free every session buffer. Takes the lock itself. + * Refused (no-op) after an uncertain completion. The next open reopens. */ +void omega_gpu_session_close(void); + +/* Device opens so far in this process (diagnostics; a persistent session shows 1). */ +uint32_t omega_gpu_session_open_count(void); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/gpu_attention_test.c b/tests/gpu_attention_test.c index 47d0fdf28..bb18b623e 100644 --- a/tests/gpu_attention_test.c +++ b/tests/gpu_attention_test.c @@ -2,6 +2,8 @@ * * ./gpu_attention_test --host-only refusals, codegen (both kernel families and every * mutant), register budget, nvdisasm listing check + * ./gpu_attention_test --timing [--out r.json] cut 4b gate: 1 query x 32 heads x 2048 ctx, 100 calls + * through the persistent session, median under 3 ms * ./gpu_attention_test --out receipt.json chip gate: every shape against the host oracle, the * mutants (deliberately wrong kernels) which the same * check must catch, a negative control, timings @@ -22,6 +24,7 @@ * exponent (3e-5 absolute per score), so it uses 1e-3 relative + 1e-4 absolute. */ #include "omega_gpu_attention_api.h" +#include "omega_gpu_session.h" #include "omega_blackwell_codegen.h" #include <inttypes.h> #include <math.h> @@ -32,6 +35,7 @@ #include <unistd.h> static int g_checks, g_failed; +static int g_sim_mode; /* --sim: the host simulator never opens the device */ #define CHECK(cond, ...) do { g_checks++; if (!(cond)) { g_failed++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0) static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } @@ -371,10 +375,12 @@ static int chip(const char *out_path) { CHECK(g_mutant_run[m] > 0 && g_mutant_caught[m] == g_mutant_run[m], "mutant %s caught %d of %d runs", mutant_name(m), g_mutant_caught[m], g_mutant_run[m]); printf("mutant %s: caught %d of %d\n", mutant_name(m), g_mutant_caught[m], g_mutant_run[m]); } + CHECK(omega_gpu_session_open_count() == (g_sim_mode ? 0u : 1u), "device opened %s for the battery (opens=%u)", g_sim_mode ? "never (simulator)" : "once", omega_gpu_session_open_count()); + printf("device_opens=%u\n", omega_gpu_session_open_count()); if (out) { fprintf(out, "],\"mutants\":{"); for (int m = 1; m <= 4; m++) fprintf(out, "%s\"%s\":{\"run\":%d,\"caught\":%d}", m > 1 ? "," : "", mutant_name(m), g_mutant_run[m], g_mutant_caught[m]); - fprintf(out, "},\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_PASS" : "OMEGA_GPU_ATTENTION_FAIL"); + fprintf(out, "},\"device_opens\":%u,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_session_open_count(), g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_PASS" : "OMEGA_GPU_ATTENTION_FAIL"); fclose(out); } return 0; @@ -483,15 +489,66 @@ static int sim_launch(const void *progv, const OmegaGpuAttnLaunch *L, OmegaGpuAt return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK; } + +/* ---------------------------------------------------- timing (cut 4b) */ +/* One query step of TinyLlama attention at context 2048 (32 q heads, 4 kv heads, + * f32 KV) 100 times through the persistent session, every call checked against the + * oracle; gate: median wall time per call under 3 ms, one device open per process. */ +static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } +static int cmp_d(const void *a, const void *b) { double x = *(const double *)a, y = *(const double *)b; return x < y ? -1 : x > y; } +static int timing(const char *out_path) { + FILE *out = out_path ? fopen(out_path, "w") : NULL; + if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } + enum { N = 100 }; + const uint32_t hd = 64, nqh = 32, nkv = 4, seq = 2048; + const char *name = "gqa_f32_tinyllama_32q4kv_ctx2048"; + if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ATTENTION_TIMING_V1\",\"gate_median_ms\":3.0,\"calls\":%d,\"cases\":[", N); + uint32_t seed = 0xfb1c004bu; + size_t n = (size_t)nqh * hd, nkvs = (size_t)seq * nkv * hd; + float *q = malloc(n * 4), *kc = malloc(nkvs * 4), *vc = malloc(nkvs * 4), *got = malloc(n * 4), *want = malloc(n * 4); + for (size_t i = 0; i < n; i++) q[i] = frand(&seed, -1.0f, 1.0f); + for (size_t i = 0; i < nkvs; i++) { kc[i] = frand(&seed, -1.0f, 1.0f); vc[i] = frand(&seed, -1.0f, 1.0f); } + oracle_gqa(q, kc, vc, seq, nqh, nkv, hd, want); + double samples[N]; int ok_calls = 0; size_t bad_total = 0; double worst = 0; uint64_t chip_sum = 0; int rc_last = 0; + OmegaGpuAttnInfo info; + /* warm-up: the first call opens the device and generates the kernel (not timed) */ + int rc0 = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info); + double first_ms = info.call_ns / 1e6; + CHECK(rc0 == OMEGA_GPU_ATTN_OK, "%s first call rc=%s err=\"%s\"", name, omega_gpu_attention_rc_name(rc0), omega_gpu_attention_last_error()); + for (int i = 0; i < N; i++) { + double t0 = now_ms(); + int rc = omega_gpu_gqa_attention_f32(q, kc, vc, seq, nqh, nkv, hd, got, &info); + samples[i] = now_ms() - t0; + double w; size_t bad = compare(got, want, n, 2e-4, 2e-5, &w); + if (w > worst) worst = w; + bad_total += bad; chip_sum += info.elapsed_ns; rc_last = rc; + if (rc == OMEGA_GPU_ATTN_OK && bad == 0) ok_calls++; + } + qsort(samples, N, sizeof samples[0], cmp_d); + double median = samples[N / 2], p90 = samples[N * 9 / 10], mn = samples[0], mx = samples[N - 1]; + uint32_t opens = omega_gpu_session_open_count(); + int pass = ok_calls == N && bad_total == 0 && median < 3.0 && opens == 1; + CHECK(pass, "timing %s ok_calls=%d/%d violations=%zu median_ms=%.3f opens=%u last_rc=%s err=\"%s\"", name, ok_calls, N, bad_total, median, opens, omega_gpu_attention_rc_name(rc_last), omega_gpu_attention_last_error()); + printf("%s timing %s first_call_ms=%.3f ok_calls=%d/%d violations=%zu worst_scaled_err=%g median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_us_mean=%.1f device_opens=%u\n", + pass ? "PASS" : "FAIL", name, first_ms, ok_calls, N, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens); + if (out) fprintf(out, "{\"case\":\"%s\",\"first_call_ms\":%.3f,\"ok_calls\":%d,\"violations\":%zu,\"worst_scaled_err\":%g,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f,\"chip_us_mean\":%.1f,\"device_opens\":%u,\"pass\":%s}", + name, first_ms, ok_calls, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens, pass ? "true" : "false"); + free(q); free(kc); free(vc); free(got); free(want); + if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ATTENTION_TIMING_PASS" : "OMEGA_GPU_ATTENTION_TIMING_FAIL"); fclose(out); } + return 0; +} + int main(int argc, char **argv) { - const char *out_path = NULL; int host = 0, sim = 0; + const char *out_path = NULL; int host = 0, sim = 0, timing_mode = 0; for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "--host-only") == 0) host = 1; else if (strcmp(argv[i], "--sim") == 0) sim = 1; + else if (strcmp(argv[i], "--timing") == 0) timing_mode = 1; else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; } - if (sim) omega_gpu_attention_test_set_simulator(sim_launch); + if (sim) { g_sim_mode = 1; omega_gpu_attention_test_set_simulator(sim_launch); } if (host) host_only(); + else if (timing_mode) { if (timing(out_path) != 0) return 2; } else if (chip(out_path) != 0) return 2; printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); return g_failed ? 1 : 0; diff --git a/tests/gpu_elementwise_test.c b/tests/gpu_elementwise_test.c index c7be98eaf..c274a063e 100644 --- a/tests/gpu_elementwise_test.c +++ b/tests/gpu_elementwise_test.c @@ -4,6 +4,8 @@ * nvdisasm listing check when /usr/local/cuda/bin/nvdisasm exists * ./gpu_elementwise_test --out receipt.json chip gate: every op against the host oracle, then its mutant * (a deliberately wrong kernel) which the same check must catch + * ./gpu_elementwise_test --timing --out t.json cut 4b gate: persistent device, 100 calls each of rmsnorm 1x2048 + * and swiglu 5632 under 0.5 ms median, one device open per process * * Oracles re-state aien-sovereign-core crates/aien-inference-abi/src/tensor.rs (main 5fdab70) in C: * rmsnorm sums in f64, rope computes cos/sin in f64 and casts to f32 before f32 math, swiglu is f64. @@ -17,6 +19,7 @@ */ #include "omega_gpu_elementwise_api.h" #include "omega_blackwell_codegen.h" +#include "omega_gpu_session.h" #include <inttypes.h> #include <math.h> #include <stdio.h> @@ -309,20 +312,74 @@ static int chip(const char *out_path) { record(c, out); free(x); free(w); free(u); free(got); free(want); free(ch); free(sh); free(xu); free(gu); } + /* cut 4b: the whole battery (clean and mutant kernels, cache clears) ran on ONE device open */ + CHECK(omega_gpu_session_open_count() == 1, "device opened once for the battery (opens=%u)", omega_gpu_session_open_count()); + printf("device_opens=%u\n", omega_gpu_session_open_count()); if (out) { - fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ELEMENTWISE_PASS" : "OMEGA_GPU_ELEMENTWISE_FAIL"); + fprintf(out, "],\"device_opens\":%u,\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", omega_gpu_session_open_count(), g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ELEMENTWISE_PASS" : "OMEGA_GPU_ELEMENTWISE_FAIL"); fclose(out); } return 0; } +/* ------------------------------------------------------------ timing gate (cut 4b) */ +/* The persistent device: 100 calls each of rmsnorm 1x2048 and swiglu 5632 (the TinyLlama + * decode shapes), every call checked against the oracle, median wall time per call under + * 0.5 ms (cut 4 opened and closed the device per call: ~40 ms). The device must have been + * opened exactly once in this process. */ +static int cmp_d(const void *a, const void *b) { double x = *(const double *)a, y = *(const double *)b; return x < y ? -1 : x > y; } +static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } +static int timing(const char *out_path) { + FILE *out = out_path ? fopen(out_path, "w") : NULL; + if (out_path && !out) { printf("cannot open %s\n", out_path); return 2; } + if (out) fprintf(out, "{\"schema\":\"OMEGA_GPU_ELEMENTWISE_TIMING_V1\",\"gate_median_ms\":0.5,\"calls\":100,\"cases\":["); + uint32_t seed = 0xfb1c004bu; + enum { N = 100 }; + for (int t = 0; t < 2; t++) { + const char *name = t == 0 ? "rmsnorm_1x2048" : "swiglu_5632"; + size_t n = t == 0 ? 2048 : 5632; + float *a = malloc(n * 4), *b = malloc(n * 4), *got = malloc(n * 4), *want = malloc(n * 4); + for (size_t i = 0; i < n; i++) { a[i] = frand(&seed, -3.0f, 3.0f); b[i] = t == 0 ? frand(&seed, 0.5f, 1.5f) : frand(&seed, -2.0f, 2.0f); } + if (t == 0) oracle_rmsnorm(a, b, 1e-5f, want, n); else oracle_swiglu(a, b, want, n); + double samples[N]; int ok_calls = 0; size_t bad_total = 0; double worst = 0; uint64_t chip_sum = 0; int rc_last = 0; + OmegaGpuEwInfo info; + /* warm-up: first call opens the device and generates the kernel (not timed) */ + int rc0 = t == 0 ? omega_gpu_rmsnorm_f32(1, (uint32_t)n, a, b, 1e-5f, got, &info) : omega_gpu_swiglu_f32((uint32_t)n, a, b, got, &info); + double first_ms = info.call_ns / 1e6; + CHECK(rc0 == OMEGA_GPU_EW_OK, "%s first call rc=%s err=\"%s\"", name, omega_gpu_elementwise_rc_name(rc0), omega_gpu_elementwise_last_error()); + for (int i = 0; i < N; i++) { + double t0 = now_ms(); + int rc = t == 0 ? omega_gpu_rmsnorm_f32(1, (uint32_t)n, a, b, 1e-5f, got, &info) : omega_gpu_swiglu_f32((uint32_t)n, a, b, got, &info); + samples[i] = now_ms() - t0; + double w; size_t bad = compare(got, want, n, 1e-5, 1e-6, &w); + if (w > worst) worst = w; + bad_total += bad; chip_sum += info.elapsed_ns; rc_last = rc; + if (rc == OMEGA_GPU_EW_OK && bad == 0) ok_calls++; + } + qsort(samples, N, sizeof samples[0], cmp_d); + double median = samples[N / 2], p90 = samples[N * 9 / 10], mn = samples[0], mx = samples[N - 1]; + uint32_t opens = omega_gpu_session_open_count(); + int pass = ok_calls == N && bad_total == 0 && median < 0.5 && opens == 1; + CHECK(pass, "timing %s ok_calls=%d/%d violations=%zu median_ms=%.3f opens=%u last_rc=%s err=\"%s\"", name, ok_calls, N, bad_total, median, opens, omega_gpu_elementwise_rc_name(rc_last), omega_gpu_elementwise_last_error()); + printf("%s timing %s first_call_ms=%.3f ok_calls=%d/%d violations=%zu worst_scaled_err=%g median_ms=%.3f p90_ms=%.3f min_ms=%.3f max_ms=%.3f chip_us_mean=%.1f device_opens=%u\n", + pass ? "PASS" : "FAIL", name, first_ms, ok_calls, N, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens); + if (out) fprintf(out, "%s{\"case\":\"%s\",\"first_call_ms\":%.3f,\"ok_calls\":%d,\"violations\":%zu,\"worst_scaled_err\":%g,\"median_ms\":%.4f,\"p90_ms\":%.4f,\"min_ms\":%.4f,\"max_ms\":%.4f,\"chip_us_mean\":%.1f,\"device_opens\":%u,\"pass\":%s}", + t ? "," : "", name, first_ms, ok_calls, bad_total, worst, median, p90, mn, mx, chip_sum / 1e3 / N, opens, pass ? "true" : "false"); + free(a); free(b); free(got); free(want); + } + if (out) { fprintf(out, "],\"checks\":%d,\"failed\":%d,\"verdict\":\"%s\"}\n", g_checks, g_failed, g_failed == 0 ? "OMEGA_GPU_ELEMENTWISE_TIMING_PASS" : "OMEGA_GPU_ELEMENTWISE_TIMING_FAIL"); fclose(out); } + return 0; +} + int main(int argc, char **argv) { - const char *out_path = NULL; int host = 0; + const char *out_path = NULL; int host = 0, timing_mode = 0; for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "--host-only") == 0) host = 1; + else if (strcmp(argv[i], "--timing") == 0) timing_mode = 1; else if (strcmp(argv[i], "--out") == 0 && i + 1 < argc) out_path = argv[++i]; } if (host) host_only(); + else if (timing_mode) { if (timing(out_path) != 0) return 2; } else if (chip(out_path) != 0) return 2; printf("%s: %d checks, %d failed\n", g_failed ? "FAIL" : "PASS", g_checks, g_failed); return g_failed ? 1 : 0; diff --git a/tests/gpu_session_probe.c b/tests/gpu_session_probe.c new file mode 100644 index 000000000..dee34588b --- /dev/null +++ b/tests/gpu_session_probe.c @@ -0,0 +1,56 @@ +/* gpu_session_probe: FB-1 cut 4b flake investigation (first-call device-open failure). + * + * One fresh process = one sample: open the shared device through the API's own + * path (omega_gpu_ex2_f32 on 128 values is the smallest launch there is), report + * the stage that failed (with the driver's own text) or the open time, exit 0/1. + * + * ./gpu_session_probe [--label L] [--calls N] [--hold-ms M] + * --calls N launches after the first (default 1); keeps the device busy for an overlap test + * --hold-ms M sleep M ms with the device open before exit (overlap window for a second probe) + * + * Output (one line, Astra's SNAP shape; every unknown says so): + * PROBE label=L pid=P rc=OK|CHIP_FAIL|... stage="..." first_call_ms=F open_ms=O calls_ok=K/N opens=1 + * Never run outside the heavy queue (tools/probe_gpu_open.sh). + */ +#include "omega_gpu_elementwise_api.h" +#include "omega_gpu_session.h" +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> + +static double now_ms(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e3 + t.tv_nsec / 1e6; } + +int main(int argc, char **argv) { + const char *label = "probe"; int calls = 1, hold_ms = 0; + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "--label") == 0 && i + 1 < argc) label = argv[++i]; + else if (strcmp(argv[i], "--calls") == 0 && i + 1 < argc) calls = atoi(argv[++i]); + else if (strcmp(argv[i], "--hold-ms") == 0 && i + 1 < argc) hold_ms = atoi(argv[++i]); + else { fprintf(stderr, "unknown flag %s\n", argv[i]); return 2; } + } + float x[128], y[128]; + for (int i = 0; i < 128; i++) { x[i] = (float)i / 16.0f - 4.0f; y[i] = 0.0f; } + OmegaGpuEwInfo info; memset(&info, 0, sizeof info); + double t0 = now_ms(); + int rc = omega_gpu_ex2_f32(128, x, y, &info); + double first_ms = now_ms() - t0; + int ok = 0; + if (rc == OMEGA_GPU_EW_OK) { + /* negative control on the result itself: 2^0 must be 1 (x[64] = 0) */ + if (y[64] < 0.999f || y[64] > 1.001f) { rc = OMEGA_GPU_EW_UNWRITTEN; omega_gpu_session_set_error("probe: 2^0 != 1"); } + else ok = 1; + } + int more_ok = 0; + for (int i = 1; i < calls && ok; i++) if (omega_gpu_ex2_f32(128, x, y, &info) == OMEGA_GPU_EW_OK) more_ok++; + if (hold_ms > 0) usleep((useconds_t)hold_ms * 1000u); + const char *stage = omega_gpu_elementwise_last_error(); + printf("PROBE label=%s pid=%d rc=%s stage=\"%s\" first_call_ms=%.1f chip_us=%.1f calls_ok=%d/%d opens=%u%s\n", + label, (int)getpid(), omega_gpu_elementwise_rc_name(rc), stage[0] ? stage : "-", first_ms, + info.elapsed_ns / 1e3, ok + more_ok, calls, omega_gpu_session_open_count(), + rc == OMEGA_GPU_EW_OK && !stage[0] ? "" : (rc == OMEGA_GPU_EW_OK ? " note=stage_text_from_earlier_failure" : "")); + fflush(stdout); + omega_gpu_session_close(); /* the explicit close is part of what the next process sees */ + return ok ? 0 : 1; +} diff --git a/tools/probe_gpu_open.sh b/tools/probe_gpu_open.sh new file mode 100755 index 000000000..30d061389 --- /dev/null +++ b/tools/probe_gpu_open.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# tools/probe_gpu_open.sh OUT_DIR [N] +# FB-1 cut 4b flake investigation: does the FIRST chip call of a fresh process fail +# in the device-open path (seen twice: cut 1b run 2, cut 3c attempt 1)? Each sample +# is a fresh process (build/gpu_session_probe). Variants, N samples each, in order: +# baseline one probe at a time, idle gap 200 ms between processes +# back_to_back the next probe starts the instant the previous one exits (the sighting: +# "another chip job had just used the chip") +# overlap a holder keeps a device open (hold 300 ms) while the probe opens its own +# after_latch NOT RUN (would need a deliberate stall; never leave the chip uncertain) +# Negative control first: the probe must report a failure when it cannot open the +# control nodes (file-descriptor limit 4 -> open() fails; limit 3 stops the dynamic loader itself, exit 127, which proves nothing), with the stage named. +# Run through the heavy queue only (lanes.sh queue --heavy); never kill it. +set -u +OUT=${1:?out dir}; N=${2:-30} +cd "$(dirname "$0")/.." || exit 2 +P=${PHYSICS_DIR:-../physics} +mkdir -p "$OUT" +make PHYSICS_DIR="$P" build/gpu_session_probe > "$OUT/build.log" 2>&1 || { echo "PROBE BUILD FAIL"; exit 1; } +PR=./build/gpu_session_probe +LOG="$OUT/probe.log"; : > "$LOG" +{ uname -a; nvidia-smi --query-gpu=name,driver_version --format=csv,noheader 2>/dev/null; echo "omega $(git rev-parse HEAD) physics $(git -C "$P" rev-parse HEAD)"; date -u +%FT%TZ; } > "$OUT/device.txt" +echo "## negative_control (fd limit 4: the loader runs, /dev/nvidiactl cannot be opened)" | tee -a "$LOG" +( ulimit -n 4; $PR --label negative_control ) 2>&1 | tee -a "$LOG" +neg_rc=${PIPESTATUS[0]} +echo "negative_control exit=$neg_rc (must be non-zero with a named stage)" | tee -a "$LOG" +fails=0; total=0 +run_variant() { # name + local name=$1 f=0 + echo "## $name N=$N" | tee -a "$LOG" + for i in $(seq 1 "$N"); do + if [ "$name" = overlap ]; then $PR --label holder --hold-ms 300 >> "$LOG" 2>&1 & sleep 0.05; fi + $PR --label "$name#$i" 2>&1 | tee -a "$LOG" | grep -q 'rc=OK' || f=$((f+1)) + [ "$name" = overlap ] && wait + [ "$name" = baseline ] && sleep 0.2 + done + echo "$name: failures $f / $N" | tee -a "$LOG" + fails=$((fails+f)); total=$((total+N)) +} +run_variant baseline +run_variant back_to_back +run_variant overlap +grep -c 'rc=OK' "$LOG" > "$OUT/ok_count.txt" +grep 'rc=' "$LOG" | grep -v 'rc=OK' | grep -v negative_control > "$OUT/failures.txt" +echo "end $(date -u +%FT%TZ)" >> "$OUT/device.txt" +cp tests/gpu_session_probe.c src/omega_gpu_session.c tools/probe_gpu_open.sh "$OUT/" +(cd "$OUT" && sha256sum -- * > SHA256SUMS) +echo "PROBE_GPU_OPEN: negative_control_exit=$neg_rc first_call_failures=$fails/$total (details $OUT/failures.txt)" +[ "$neg_rc" != 0 ] || { echo "PROBE_GPU_OPEN: INSTRUMENT FAIL (negative control passed)"; exit 3; } diff --git a/tools/run_gpu_cut4b_chip.sh b/tools/run_gpu_cut4b_chip.sh new file mode 100755 index 000000000..528e2825b --- /dev/null +++ b/tools/run_gpu_cut4b_chip.sh @@ -0,0 +1,54 @@ +#!/bin/sh +# tools/run_gpu_cut4b_chip.sh [OUT_ROOT] [PROBE_N] +# FB-1 cut 4b chip gate: the three native GPU APIs on ONE persistent session. +# 1. elementwise parity battery (cut 4, unchanged cases) + --timing +# (rmsnorm 1x2048 and swiglu 5632: median of 100 calls under 0.5 ms, one open) +# 2. attention: host simulator first, then the chip parity battery (cut 5, unchanged +# cases) + --timing (1 query x 32 heads x 2048 ctx: median of 100 calls under 3 ms) +# 3. matmul sweep + --timing (cut 1b regression on the shared session) +# 4. fresh-process device-open probe (flake investigation, tools/probe_gpu_open.sh) +# Sealed receipt folder OUT_ROOT/FB1-CUT4B-<sha>/ (default ~/workspace/evidence-out): +# elementwise.json elementwise_timing.json attention.json attention_timing.json +# matmul.json matmul_timing.json + the matching *.log, probe/ (probe.log, failures.txt), +# device.txt build.log, copies of the sources the verdict depends on, SHA256SUMS. +# Every step runs even when an earlier one fails (the receipt records all of them). +# Run it through the heavy queue only (lanes.sh queue --heavy); never kill it. +set -u +cd "$(dirname "$0")/.." || exit 2 +P=${PHYSICS_DIR:-../physics} +SHA=$(git rev-parse --short HEAD) +OUT=${1:-$HOME/workspace/evidence-out}/FB1-CUT4B-$SHA +PROBE_N=${2:-30} +mkdir -p "$OUT" +if ! make PHYSICS_DIR="$P" build/gpu_elementwise_test build/gpu_attention_test build/gpu_matmul_api_test build/gpu_session_probe > "$OUT/build.log" 2>&1; then + echo "FB1-CUT4B BUILD FAIL (see $OUT/build.log)"; exit 1 +fi +{ + uname -a + nvidia-smi --query-gpu=name,driver_version --format=csv,noheader 2>/dev/null || echo "nvidia-smi: unavailable" + echo "omega $(git rev-parse HEAD) ($(git status --porcelain | wc -l) uncommitted paths)" + echo "physics $(git -C "$P" rev-parse HEAD)" + date -u +%FT%TZ +} > "$OUT/device.txt" +fail=0 +step() { # name command... + name=$1; shift + "$@" > "$OUT/$name.log" 2>&1; rc=$? + echo "$name rc=$rc :: $(grep -E '^(PASS|FAIL)' "$OUT/$name.log" | tail -1)" + [ "$rc" -eq 0 ] || fail=$((fail+1)) +} +step elementwise ./build/gpu_elementwise_test --out "$OUT/elementwise.json" +step elementwise_timing ./build/gpu_elementwise_test --timing --out "$OUT/elementwise_timing.json" +step attention_sim ./build/gpu_attention_test --sim +step attention ./build/gpu_attention_test --out "$OUT/attention.json" +step attention_timing ./build/gpu_attention_test --timing --out "$OUT/attention_timing.json" +step matmul ./build/gpu_matmul_api_test --out "$OUT/matmul.json" +step matmul_timing ./build/gpu_matmul_api_test --timing --out "$OUT/matmul_timing.json" +./tools/probe_gpu_open.sh "$OUT/probe" "$PROBE_N" > "$OUT/probe.log" 2>&1; prc=$? +tail -1 "$OUT/probe.log" +echo "end $(date -u +%FT%TZ)" >> "$OUT/device.txt" +cp src/omega_gpu_session.c src/omega_gpu_session.h src/omega_gpu_matmul_api.c src/omega_gpu_elementwise_api.c src/omega_gpu_elementwise_api.h \ + src/omega_gpu_attention_api.c src/omega_gpu_attention_api.h tests/gpu_elementwise_test.c tests/gpu_attention_test.c tests/gpu_matmul_api_test.c "$OUT/" +(cd "$OUT" && sha256sum -- * probe/* 2>/dev/null > SHA256SUMS) +echo "FB1-CUT4B chip gate failed_steps=$fail probe_rc=$prc receipt=$OUT" +[ "$fail" -eq 0 ] && [ "$prc" -ne 3 ]