Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/CUDApp/blob/main/examples/hello_gpu/hello_gpu.c # CUDApp CUDA++: AIEN’s GPU machine-code toolchain, runtime and driver client for NVIDIA GPUs without the CUDA toolkit. Hardware coverage and driver replacement limits are explicit. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `CUDApp / examples / hello_gpu / hello_gpu.c` 554 lines · 33972 bytes Raw Blame History 1 /* ORACLE/foreign-caller example: a C program calling the CUDA++ runtime's C API. Not first-party implementation. */ 2 /* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception */ 3 /* hello_gpu: the smallest complete caller of the runtime's C API (src/omega_gpu_session.h, the Omega Runtime API of 4 * docs/runtime/API.md). It adds two arrays of one million floats on the GPU (c[i] = a[i] + b[i]) and checks every 5 * answer on the CPU. It is C on purpose: it shows what a foreign (non-Omega) program has to do to use the runtime, so 6 * it is an example and a test of the C API, never first-party implementation (`.om` is the implementation language; 7 * the native .om hello of aien-dev/CUDApp#79 is to replace this program). 8 * 9 * What it uses: the GPU program (the kernel) is written below as a short list of machine-level steps, handed to the 10 * runtime's own code generator, and run through the runtime's own launcher. Nothing here uses CUDA, nvcc, PTX or any 11 * NVIDIA user-space library. 12 * 13 * The five steps, in the order they appear in main(): 14 * 1. Build the kernel build_vecadd() a list of IR instructions, then register allocation 15 * 2. Open the GPU omega_gpu_session_open() 16 * 3. Upload kernel + data omega_gpu_session_alloc_code(), omega_gpu_session_alloc() 17 * 4. Launch omega_gpu_session_launch() (eight launches of 131072 elements each) 18 * 5. Check every one of the `1048576` outputs against the CPU's own a + b 19 * 20 * Prints PASS or FAIL. Exit code: 0 PASS, 1 FAIL (wrong or missing results), 2 the GPU could not be used. 21 * 22 * `hello_gpu --sim` runs the same kernel program on the host warp simulator instead (tests/bw_warp_sim.h): 23 * no GPU is opened. A bad memory access there stops at the launch that made it. The simulator names the 24 * pc. This program names the block, thread, address and buffer from the launch it issued (developer bar 25 * D3 and D4, docs/PAIN_POINTS.md): the mirrored simulator does not store those fields. `--sim --bug=past-end` 26 * shows such a report: the last launch is given one element too many, a classic off-by-one. 27 * 28 * `--bug=short` is the negative control for the check itself, on the GPU or with --sim: the last launch is 29 * given one element too FEW, so c[`1048575`] is never written. That writes nothing outside a buffer, so it is 30 * safe on the chip; the check must report "1 never written", print FAIL and exit 1. `make hello-gpu-control` 31 * builds a separate binary, build/hello_gpu_control, with it and passes only when it goes red that way. 32 * MIGRATION-PENDING C (GpuStack PLAN, Language rule): it exists only when CUDAPP_MIGRATION_PENDING_HELLO_CONTROL 33 * is defined to 1, which is OFF by default (build/hello_gpu never has it). Its .om successor is the native .om 34 * hello of aien-dev/CUDApp#79 (OM-GPU-RETIRE), which replaces this whole C program. 35 * 36 * Both paths print the work the job takes (bytes moved, floating-point operations) and the least time 37 * those bytes need at this GB10's measured read ceiling (D12). The mirrored simulator no longer counts 38 * those bytes, so --sim accounts the vecadd this program issued: two f32 loads, one f32 store and one 39 * FADD per element. Both paths also print the time the kernel took to build, the 40 * hash of its machine code (D10, no compiling at run time), and the hash of the output (D7: the same 41 * inputs give the same bits on every run). 42 * 43 * D8 (no per-process CUDA tax, docs/issues/D8-process-tax.md): before its launches the program prints its own 44 * overhead line. It reads its resident memory (VmRSS, /proc/self/status) before the GPU opens, after it opens 45 * and with its buffers allocated and uploaded, and prints those three numbers, its own buffer bytes, what it 46 * asked the driver for through the session, the cost of opening and the resident memory beyond its own 47 * buffers. --sim prints the same line without the open (no device). `--hold-ms=N` (at most 60000) then 48 * prints its pid and sleeps N ms with the buffers held, so an outside reader can record what the driver and 49 * the kernel report for this process (tests/d8_process_tax.om). `--d8-ballast-mib=N` is the line's 50 * negative control: hello_gpu_control only (CUDAPP_MIGRATION_PENDING_HELLO_CONTROL, see above), it holds N MiB 51 * of touched host memory through the measured window, and the measurement must see it. 52 * 53 * Hardware: NVIDIA GB10 (DGX Spark, sm_121), Linux, the open NVIDIA kernel driver loaded. 54 * Built by `make hello-gpu` (see README, "Run your first kernel"). 55 */ 56 #ifndef CUDAPP_MIGRATION_PENDING_HELLO_CONTROL 57 #define CUDAPP_MIGRATION_PENDING_HELLO_CONTROL 0 /* migration-pending switch, OFF by default (see above) */ 58 #endif 59 #include "omega_blackwell_codegen.h" 60 #include "omega_ampere_codegen.h" 61 #include "omega_blackwell_qmd.h" 62 #include "omega_gpu_session.h" 63 #include "omega_runtime_api.h" 64 #include "sha256.h" 65 #include "cudapp_native.h" 66 #ifndef CUDAPP_MIGRATION_PENDING_HELLO_HOST 67 #define CUDAPP_MIGRATION_PENDING_HELLO_HOST 0 68 #endif 69 #include "../../tests/bw_warp_sim.h" /* the host warp simulator the host tests use; only --sim calls it */ 70 #include 71 #include 72 #include 73 #include 74 #include 75 76 #define N_TOTAL (1u << 20) /* `1048576` floats per array */ 77 #define THREADS 128u /* threads per block (CTA) */ 78 #define MAX_CTAS 1024u /* blocks per launch the session is proven for (omega_gpu_elementwise_api.h) */ 79 #define CHUNK (THREADS * MAX_CTAS) /* elements per launch: 131072, so N_TOTAL is 8 launches */ 80 #define POISON 0xFFC0FFEEu /* a NaN pattern c starts out as: an element the GPU never wrote stays this */ 81 #define READ_CEILING_GBPS 195.1 /* GB10 global reads, measured: evidence/OWN30B-T3-TC-PEAK-BW-`5faa0f70`-20261013T2236Z/ */ 82 static uint32_t target_sm = 121; /* explicit --target=sm_86; never infer from the build host */ 83 static unsigned hold_ms = 0; /* D8: --hold-ms, 0 = no hold */ 84 #if CUDAPP_MIGRATION_PENDING_HELLO_CONTROL 85 static unsigned ballast_mib = 0; /* D8 negative control, hello_gpu_control only */ 86 #endif 87 88 /* ---- Step 1: the kernel, as IR instructions ------------------------------------------------------------- 89 * Each instruction carries a "control word" that tells the chip how long to wait before the next one. 90 * Two rules are enough for this kernel (chip-learned, see the header of src/omega_gpu_elementwise_api.c): 91 * - a load or special-register read (LDC, LDCU, S2R, LDG) finishes later, on a scoreboard slot; 92 * the next instruction waits for that slot; 93 * - plain arithmetic (IMAD, FADD) needs about 6 cycles before its result is read. 94 * To stay simple, every instruction here waits for everything still pending. */ 95 #define NOREG (-1) 96 #define CTRL(stall, wbar, rbar, wait) \ 97 (((uint32_t)(stall) << 9) | ((uint32_t)(wbar) << 14) | ((uint32_t)(rbar) << 17) | ((uint32_t)(wait) << 20)) 98 #define YIELD 0x2000u 99 enum { SB_LOAD = 0, SB_STORE = 1, SB_UNIFORM = 2, SB_NONE = 7 }; /* scoreboard slots */ 100 enum { K_ALU, K_PRED, K_LOAD, K_ULOAD, K_STORE, K_EXIT, K_EXIT_IF_P0 }; /* what kind of instruction */ 101 102 typedef struct { BlackwellIRProgram *p; int desc; uint32_t pending; int err; } Kb; /* desc: the memory descriptor register */ 103 104 static void emit(Kb *k, BlackwellIROpcode op, int dst, int a, int b, int c, uint32_t imm, int kind) { 105 BlackwellIRInsn in; memset(&in, 0, sizeof in); 106 in.op = op; in.dst_vreg = dst; in.src1_vreg = a; in.src2_vreg = b; in.src3_vreg = c; in.ureg = (op == BW_IR_LDG_E || op == BW_IR_STG_E) ? k->desc : NOREG; in.imm = imm; 107 uint32_t wait = k->pending; 108 #if CUDAPP_MIGRATION_PENDING_HELLO_HOST 109 switch (kind) { 110 case K_ALU: in.control = CTRL(6, SB_NONE, SB_NONE, wait); k->pending = 0; break; 111 case K_PRED: in.control = CTRL(14, SB_NONE, SB_NONE, wait); k->pending = 0; break; 112 case K_LOAD: in.control = CTRL(4, SB_LOAD, SB_NONE, wait) | YIELD; k->pending = 1u << SB_LOAD; break; 113 case K_ULOAD: in.control = CTRL(4, SB_UNIFORM, SB_NONE, wait) | YIELD; k->pending = 1u << SB_UNIFORM; in.is_uniform = true; break; 114 case K_STORE: in.control = CTRL(4, SB_NONE, SB_STORE, wait) | YIELD; k->pending = 1u << SB_STORE; break; 115 case K_EXIT: in.control = CTRL(5, SB_NONE, SB_NONE, wait); k->pending = 0; break; 116 case K_EXIT_IF_P0: in.control = CTRL(5, SB_NONE, SB_NONE, wait); in.predicate_p0 = true; break; /* may fall through: keep waiting */ 117 } 118 #else 119 const uint64_t control_cfg[16] = {(uint64_t)kind, wait}; uint64_t d[16], result = 0; 120 if (omega_hplan(&result, 1, control_cfg, 16, d, 16) != OMEGA_OK || result != 1) abort(); 121 in.control = (uint32_t)d[0]; k->pending = (uint32_t)d[1]; 122 in.is_uniform = kind == K_ULOAD; in.predicate_p0 = kind == K_EXIT_IF_P0; 123 #endif 124 if (omega_bw_ir_append(k->p, &in) < 0) k->err = -1; 125 } 126 127 /* The kernel the chip runs once per thread: 128 * i = block_index * 128 + thread_index 129 * if (i >= n) exit 130 * c[i] = a[i] + b[i] 131 * a, b, c and n arrive in the launch's argument block (constant bank 0): a at 0x380, b at 0x388, c at 0x390 132 * (64-bit addresses), n at 0x398. 0x358 holds the memory descriptor every load and store names. */ 133 static int build_vecadd(BlackwellIRProgram *prog) { 134 omega_bw_ir_init(prog); 135 Kb k = { .p = prog, .desc = omega_bw_ir_alloc_uvreg64(prog) }; 136 int pa = omega_bw_ir_alloc_vreg64(prog), pb = omega_bw_ir_alloc_vreg64(prog), pc = omega_bw_ir_alloc_vreg64(prog); 137 int tid = omega_bw_ir_alloc_vreg(prog), cta = omega_bw_ir_alloc_vreg(prog), n = omega_bw_ir_alloc_vreg(prog); 138 int i = omega_bw_ir_alloc_vreg(prog), at = omega_bw_ir_alloc_vreg64(prog); 139 int x = omega_bw_ir_alloc_vreg(prog), y = omega_bw_ir_alloc_vreg(prog), z = omega_bw_ir_alloc_vreg(prog); 140 141 emit(&k, BW_IR_LDCU64, k.desc, NOREG, NOREG, NOREG, 0x358, K_ULOAD); 142 emit(&k, BW_IR_LDC64, pa, NOREG, NOREG, NOREG, 0x380, K_LOAD); 143 emit(&k, BW_IR_LDC64, pb, NOREG, NOREG, NOREG, 0x388, K_LOAD); 144 emit(&k, BW_IR_LDC64, pc, NOREG, NOREG, NOREG, 0x390, K_LOAD); 145 emit(&k, BW_IR_LDC, n, NOREG, NOREG, NOREG, 0x398, K_LOAD); 146 emit(&k, BW_IR_S2R, tid, NOREG, NOREG, NOREG, BW_SR_TID_X, K_LOAD); 147 emit(&k, BW_IR_S2R, cta, NOREG, NOREG, NOREG, BW_SR_CTAID_X, K_LOAD); 148 emit(&k, BW_IR_IMAD, i, cta, NOREG, tid, THREADS, K_ALU); /* i = cta * 128 + tid */ 149 emit(&k, BW_IR_ISETP_GE_U32, NOREG, i, n, NOREG, 0, K_PRED); /* P0 = (i >= n) */ 150 emit(&k, BW_IR_EXIT, NOREG, NOREG, NOREG, NOREG, 0, K_EXIT_IF_P0); /* @P0 EXIT */ 151 152 /* IMAD.WIDE builds a 64-bit byte address: at = i * 4 + base pointer */ 153 emit(&k, BW_IR_IMAD_WIDE, at, i, NOREG, pa, 4, K_ALU); 154 emit(&k, BW_IR_LDG_E, x, at, NOREG, NOREG, 0, K_LOAD); /* x = a[i] */ 155 emit(&k, BW_IR_IMAD_WIDE, at, i, NOREG, pb, 4, K_ALU); 156 emit(&k, BW_IR_LDG_E, y, at, NOREG, NOREG, 0, K_LOAD); /* y = b[i] */ 157 emit(&k, BW_IR_FADD, z, x, y, NOREG, 0, K_ALU); /* z = x + y */ 158 emit(&k, BW_IR_IMAD_WIDE, at, i, NOREG, pc, 4, K_ALU); 159 emit(&k, BW_IR_STG_E, NOREG, at, z, NOREG, 0, K_STORE); /* c[i] = z */ 160 161 /* every kernel ends with EXIT, then a branch-to-self the hardware never reaches */ 162 emit(&k, BW_IR_EXIT, NOREG, NOREG, NOREG, NOREG, 0, K_EXIT); 163 emit(&k, BW_IR_BRA, NOREG, NOREG, NOREG, NOREG, 0, K_ALU); 164 prog->insns[prog->count - 1].control = 0x000fc000u; 165 166 if (k.err) return -1; 167 return omega_bw_regalloc_solve(prog); /* picks the physical registers */ 168 } 169 170 /* ---- helpers shared by both paths ---------------------------------------------------------------------- */ 171 static double now_us(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (double)t.tv_sec * 1e6 + (double)t.tv_nsec / 1e3; } 172 static void print_sha(const char *what, const void *data, size_t len) { 173 uint8_t d[SHA256_DIGEST_SIZE]; 174 sha256_hash((const uint8_t *)data, len, d); 175 printf("%s sha256 ", what); 176 for (int i = 0; i < SHA256_DIGEST_SIZE; i++) printf("%02x", d[i]); 177 printf("\n"); 178 } 179 static void print_work(uint64_t read, uint64_t written, uint64_t fp_ops, double measured_us) { 180 #if CUDAPP_MIGRATION_PENDING_HELLO_HOST 181 uint64_t moved = read + written; 182 double floor_us = target_sm == 121 ? (double)moved / (READ_CEILING_GBPS * 1e3) : 0; 183 double percent = measured_us > 0 ? 100.0 * floor_us / measured_us : 0; 184 #else 185 uint64_t bits, result = 0, d[16]; memcpy(&bits, &measured_us, sizeof bits); 186 const uint64_t c[16] = {target_sm, read, written, bits}; 187 if (omega_hplan(&result, 2, c, 16, d, 16) != OMEGA_OK || result != 1) abort(); 188 uint64_t moved = d[0]; double floor_us, percent; 189 memcpy(&floor_us, d + 1, sizeof floor_us); memcpy(&percent, d + 2, sizeof percent); 190 #endif 191 printf("work: %llu bytes moved (%llu read, %llu written), %llu floating-point operations\n", 192 (unsigned long long)moved, (unsigned long long)read, (unsigned long long)written, (unsigned long long)fp_ops); 193 if (target_sm == 121) { 194 printf(" at the GB10's measured %.1f GB/s read ceiling this needs at least %.1f us", READ_CEILING_GBPS, floor_us); 195 if (measured_us > 0) printf("; the GPU took %.1f us (%.0f%% of the ceiling)", measured_us, percent); 196 printf("\n"); 197 } else if (measured_us > 0) printf(" sm_86 device time %.1f us (no GB10 bandwidth claim)\n", measured_us); 198 } 199 static void inputs(float *fa, float *fb, uint32_t *wc) { 200 #if CUDAPP_MIGRATION_PENDING_HELLO_HOST 201 for (uint32_t i = 0; i < N_TOTAL; i++) { fa[i] = (float)i * 0.25f; fb[i] = 1.0f / (float)(1 + i % 7); wc[i] = POISON; } 202 #else 203 uint64_t result = 0, stats[4]; 204 if (omega_hello(&result, 0, fa, N_TOTAL * 4u, fb, N_TOTAL * 4u, 205 wc, N_TOTAL * 4u, stats, 4) != OMEGA_OK || result != 1) abort(); 206 #endif 207 } 208 /* Step 5, both paths: same IEEE single-precision add on both sides, so the bits must match. */ 209 static int check(const float *fa, const float *fb, const uint32_t *wc) { 210 uint32_t wrong = 0, unwritten = 0, first_bad = 0; 211 #if CUDAPP_MIGRATION_PENDING_HELLO_HOST 212 for (uint32_t i = 0; i < N_TOTAL; i++) { 213 float want = fa[i] + fb[i]; 214 if (wc[i] == POISON) unwritten++; 215 if (memcmp(&want, &wc[i], sizeof want) != 0) { if (!wrong++) first_bad = i; } 216 } 217 #else 218 uint64_t result = 0, stats[4]; 219 if (omega_hello(&result, 1, (void *)fa, N_TOTAL * 4u, (void *)fb, N_TOTAL * 4u, 220 (void *)wc, N_TOTAL * 4u, stats, 4) != OMEGA_OK || result != 1) return 1; 221 wrong = (uint32_t)stats[0]; unwritten = (uint32_t)stats[1]; first_bad = (uint32_t)stats[2]; 222 #endif 223 printf("checked %u of %u elements: %u wrong, %u never written\n", N_TOTAL, N_TOTAL, wrong, unwritten); 224 if (wrong) { float want, got; 225 #if CUDAPP_MIGRATION_PENDING_HELLO_HOST 226 want = fa[first_bad] + fb[first_bad]; 227 #else 228 const uint32_t bits = (uint32_t)stats[3]; memcpy(&want, &bits, sizeof want); 229 #endif 230 memcpy(&got, &wc[first_bad], sizeof got); 231 printf("first mismatch: c[%u] = %g, expected %g\n", first_bad, got, want); } 232 return wrong ? 1 : 0; 233 } 234 static const char *op_text(BlackwellIROpcode op) { 235 switch (op) { 236 case BW_IR_LDG_E: return "LDG.E (4-byte load)"; 237 case BW_IR_STG_E: return "STG.E (4-byte store)"; 238 case BW_IR_IMAD_WIDE: return "IMAD.WIDE (64-bit address)"; 239 case BW_IR_IMAD: return "IMAD"; 240 case BW_IR_FADD: return "FADD"; 241 case BW_IR_S2R: return "S2R (read thread or block index)"; 242 case BW_IR_LDC: case BW_IR_LDC64: return "LDC (read a launch argument)"; 243 case BW_IR_ISETP_GE_U32: return "ISETP.GE.U32"; 244 case BW_IR_EXIT: return "EXIT"; 245 case BW_IR_BRA: return "BRA"; 246 default: return "instruction"; 247 } 248 } 249 static void chunk_plan(uint32_t base, int bug, uint64_t d[16]) { 250 #if CUDAPP_MIGRATION_PENDING_HELLO_HOST 251 uint32_t n = N_TOTAL - base < CHUNK ? N_TOTAL - base : CHUNK; 252 if (base + CHUNK >= N_TOTAL) { if (bug == 1) ++n; if (bug == 2) --n; } 253 d[0] = (uint64_t)base * 4u; d[1] = n; 254 d[2] = (n + THREADS - 1) / THREADS; d[3] = (N_TOTAL + CHUNK - 1) / CHUNK; 255 d[4] = (uint64_t)n * 8u; d[5] = (uint64_t)n * 4u; 256 #else 257 const uint64_t c[16] = {base, N_TOTAL, CHUNK, THREADS, (uint64_t)bug}; uint64_t result = 0; 258 if (omega_hplan(&result, 0, c, 16, d, 16) != OMEGA_OK || result != 1) abort(); 259 #endif 260 } 261 262 /* ---- D8: the memory this process holds beyond its own buffers -------------------------------------------- */ 263 /* Migration C (pure-Omega directive 2026-11-07): this D8 measurement, hold and ballast code is an addition to the 264 * existing hello_gpu.c; its arithmetic already lives in om/graph/hello-plan.om mode 5. Its .om successor is the 265 * native .om hello of aien-dev/CUDApp#79 (OM-GPU-RETIRE), which retires this file. */ 266 static uint64_t resident_kib(void) { /* VmRSS of this process; 0 when /proc cannot be read */ 267 FILE *f = fopen("/proc/self/status", "r"); 268 char line[256]; unsigned long long kib = 0; 269 if (!f) return 0; 270 while (fgets(line, sizeof line, f)) if (sscanf(line, "VmRSS: %llu kB", &kib) == 1) break; 271 fclose(f); 272 return kib; 273 } 274 /* opened = 0 is --sim: no device, so before == after open. driver_bytes is what the session asked the driver for. */ 275 static void print_overhead(int opened, uint64_t before, uint64_t after_open, uint64_t with_buffers, 276 uint64_t own_bytes, uint64_t driver_bytes, uint64_t driver_allocs) { 277 if (!before || !after_open || !with_buffers) { printf("overhead (D8): resident memory unreadable (/proc/self/status VmRSS)\n"); return; } 278 uint64_t d[16] = { 0 }; 279 #if CUDAPP_MIGRATION_PENDING_HELLO_HOST 280 d[0] = (own_bytes + 1023u) / 1024u; 281 d[1] = after_open >= before ? after_open - before : before - after_open; d[2] = after_open < before; 282 const uint64_t floor_kib = before + d[0]; 283 d[3] = with_buffers >= floor_kib ? with_buffers - floor_kib : floor_kib - with_buffers; d[4] = with_buffers < floor_kib; 284 d[5] = (driver_bytes + 1023u) / 1024u; 285 #else 286 const uint64_t c[16] = {before, after_open, with_buffers, own_bytes, driver_bytes}; uint64_t result = 0; 287 if (omega_hplan(&result, 5, c, 16, d, 16) != OMEGA_OK || result != 1) abort(); 288 #endif 289 if (opened) 290 printf("overhead (D8): resident %llu KiB before open, %llu KiB after open, %llu KiB with buffers; own buffers %llu KiB; " 291 "session driver allocations %llu KiB in %llu; open cost %c%llu KiB, beyond own buffers %c%llu KiB\n", 292 (unsigned long long)before, (unsigned long long)after_open, (unsigned long long)with_buffers, 293 (unsigned long long)d[0], (unsigned long long)d[5], (unsigned long long)driver_allocs, 294 d[2] ? '-' : '+', (unsigned long long)d[1], d[4] ? '-' : '+', (unsigned long long)d[3]); 295 else 296 printf("overhead (D8, simulator, no device opened): resident %llu KiB before buffers, %llu KiB with buffers; " 297 "own buffers %llu KiB; beyond own buffers %c%llu KiB\n", (unsigned long long)before, 298 (unsigned long long)with_buffers, (unsigned long long)d[0], d[4] ? '-' : '+', (unsigned long long)d[3]); 299 } 300 static void hold(void) { /* D8: keep the buffers while an outside reader records this pid */ 301 if (!hold_ms) return; 302 printf("hold (D8): pid %ld, %u ms with buffers allocated, for an outside reading of this process\n", (long)getpid(), hold_ms); 303 fflush(stdout); 304 struct timespec t = { (time_t)(hold_ms / 1000u), (long)(hold_ms % 1000u) * 1000000L }; 305 while (nanosleep(&t, &t) != 0) {} 306 } 307 static void *ballast(void) { /* D8 negative control: N MiB of touched host memory, NULL when not asked for */ 308 #if CUDAPP_MIGRATION_PENDING_HELLO_CONTROL 309 if (ballast_mib) { 310 const size_t n = (size_t)ballast_mib << 20; 311 char *p = malloc(n); 312 if (!p) { printf("FAIL: ballast of %u MiB not allocated\n", ballast_mib); exit(1); } 313 memset(p, 0x5a, n); 314 printf("ballast (D8 negative control): %u MiB of touched host memory held through the measurement\n", ballast_mib); 315 return p; 316 } 317 #endif 318 return NULL; 319 } 320 static int number_arg(const char *arg, const char *prefix, unsigned max, unsigned *out) { 321 const size_t k = strlen(prefix); 322 if (strncmp(arg, prefix, k) != 0) return 0; 323 char *end = NULL; unsigned long v = strtoul(arg + k, &end, 10); 324 if (end == arg + k || *end || v < 1 || v > max) { printf("%s needs a whole number from 1 to %u\n", prefix, max); exit(2); } 325 *out = (unsigned)v; 326 return 1; 327 } 328 329 /* ---- --sim: the same program on the host warp simulator --------------------------------------------------- */ 330 static int run_sim(const BlackwellIRProgram *prog, int bug) { 331 const size_t bytes = (size_t)N_TOTAL * sizeof(float); 332 const uint64_t rss_before = resident_kib(); 333 void *extra = ballast(); 334 float *fa = aligned_alloc(64, bytes), *fb = aligned_alloc(64, bytes); 335 uint32_t *wc = aligned_alloc(64, bytes); 336 if (!fa || !fb || !wc) { printf("FAIL: host memory\n"); return 1; } 337 inputs(fa, fb, wc); 338 print_overhead(0, rss_before, rss_before, resident_kib(), 3u * bytes, 0, 0); 339 hold(); 340 static WsSim s; 341 memset(&s, 0, sizeof s); 342 s.p = prog; s.threads = THREADS; 343 const char *names[3] = { "a", "b", "c" }; 344 const uintptr_t base_of[3] = { (uintptr_t)fa, (uintptr_t)fb, (uintptr_t)wc }; 345 for (int k = 0; k < 3; k++) { s.ranges[k].lo = base_of[k]; s.ranges[k].hi = base_of[k] + bytes; } 346 s.nranges = 3; /* every global access must land inside a, b or c */ 347 uint64_t plan[16]; chunk_plan(0, 0, plan); 348 const uint32_t launches = (uint32_t)plan[3]; 349 uint32_t li = 0; 350 uint64_t read_b = 0, wrote_b = 0, flops = 0; 351 for (uint32_t base = 0; base < N_TOTAL; base += CHUNK) { 352 li++; 353 chunk_plan(base, bug, plan); 354 uint64_t off = plan[0]; 355 uint32_t n = (uint32_t)plan[1]; 356 uint64_t pa = base_of[0] + off, pb = base_of[1] + off, pc = base_of[2] + off; 357 memset(s.cbank, 0, sizeof s.cbank); 358 s.cbank[0x380 / 4] = (uint32_t)pa; s.cbank[0x384 / 4] = (uint32_t)(pa >> 32); 359 s.cbank[0x388 / 4] = (uint32_t)pb; s.cbank[0x38c / 4] = (uint32_t)(pb >> 32); 360 s.cbank[0x390 / 4] = (uint32_t)pc; s.cbank[0x394 / 4] = (uint32_t)(pc >> 32); 361 s.cbank[0x398 / 4] = n; 362 uint32_t grid = (uint32_t)plan[2]; 363 if (ws_run(&s, grid, 1) != 0) { 364 const BlackwellIRInsn *in = (s.err_pc >= 0 && (size_t)s.err_pc < prog->count) ? &prog->insns[s.err_pc] : NULL; 365 int store = in && in->op == BW_IR_STG_E; 366 /* --bug=past-end: the first out-of-range access is a[N_TOTAL], a 4-byte LDG.E. 367 The mirrored simulator records the pc, not the lane or the address. */ 368 uint64_t fault_plan[16]; 369 #if CUDAPP_MIGRATION_PENDING_HELLO_HOST 370 fault_plan[0] = base + n - 1; 371 fault_plan[1] = (fault_plan[0] - base) / THREADS; 372 fault_plan[2] = (fault_plan[0] - base) % THREADS; 373 fault_plan[3] = (uint64_t)(uintptr_t)fa + fault_plan[0] * sizeof(float); 374 #else 375 const uint64_t fc[16] = {base, n, THREADS, (uint64_t)(uintptr_t)fa}; uint64_t fr = 0; 376 if (omega_hplan(&fr, 3, fc, 16, fault_plan, 16) != OMEGA_OK || fr != 1) abort(); 377 #endif 378 uint32_t block = (uint32_t)fault_plan[1], thread = (uint32_t)fault_plan[2]; 379 uint64_t fault_addr = fault_plan[3]; 380 unsigned fault_bytes = 4; 381 if (s.err == WS_E_MEM) printf("FAULT at launch %u of %u of kernel vecadd (simulator): global %s outside every buffer\n", li, launches, store ? "store" : "load"); 382 else printf("FAULT at launch %u of %u of kernel vecadd (simulator): %s\n", li, launches, ws_err_name(s.err)); 383 printf(" launch: grid %u x 1 blocks of %u threads, n = %u, first element %u\n", grid, THREADS, n, base); 384 if (in) printf(" instruction: %d of %zu, %s\n", s.err_pc, prog->count, op_text(in->op)); 385 printf(" thread: block %u, thread %u (element %llu of the whole job)\n", block, thread, 386 (unsigned long long)fault_plan[0]); 387 int near = 0; uint64_t dist = UINT64_MAX; int past = 1; 388 uint64_t remaining = 0; 389 if (s.err == WS_E_MEM) { 390 #if CUDAPP_MIGRATION_PENDING_HELLO_HOST 391 for (int k = 0; k < 3; k++) { 392 uint64_t lo = s.ranges[k].lo, hi = s.ranges[k].hi, d; int pst; 393 if (fault_addr >= hi) { d = fault_addr - hi; pst = 1; } 394 else if (fault_addr + fault_bytes <= lo) { d = lo - (fault_addr + fault_bytes); pst = 0; } 395 else { d = 0; pst = 1; } /* starts inside, runs past the end */ 396 if (d < dist) { dist = d; near = k; past = pst; } 397 } 398 remaining = (s.ranges[near].hi - (s.ranges[near].lo + off)) / sizeof(float); 399 #else 400 uint64_t ranges[16] = {0}, nearest[16], nr = 0; 401 for (int k = 0; k < 3; k++) { ranges[k * 2] = s.ranges[k].lo; ranges[k * 2 + 1] = s.ranges[k].hi; } 402 ranges[6] = fault_addr; ranges[7] = fault_bytes; ranges[8] = off; 403 if (omega_hplan(&nr, 4, ranges, 16, nearest, 16) != OMEGA_OK || nr != 1) abort(); 404 near = (int)nearest[0]; dist = nearest[1]; past = (int)nearest[2]; 405 remaining = nearest[3]; 406 #endif 407 printf(" address: 0x%llx (%u bytes), %llu bytes %s buffer %s = [0x%llx, 0x%llx) (%zu bytes)\n", 408 (unsigned long long)fault_addr, fault_bytes, (unsigned long long)dist, past ? "past the end of" : "before the start of", 409 names[near], (unsigned long long)s.ranges[near].lo, (unsigned long long)s.ranges[near].hi, bytes); 410 } 411 printf(" simulator: %s\n", s.msg); 412 if (s.err == WS_E_MEM) 413 printf(" next: launch %u was given n = %u, and buffer %s holds %llu elements from this launch's first element.\n" 414 " Fix the launch or the buffer, run hello_gpu --sim until it passes, then run hello_gpu on the GPU.\n", 415 li, n, names[near], (unsigned long long)remaining); 416 else 417 printf(" next: the instruction above is where the program stopped; fix it and run hello_gpu --sim again.\n"); 418 free(fa); free(fb); free(wc); 419 return 1; 420 } 421 read_b += plan[4]; 422 wrote_b += plan[5]; 423 flops += n; 424 } 425 int rc = check(fa, fb, wc); 426 print_work(read_b, wrote_b, flops, 0); 427 print_sha("output", wc, bytes); 428 printf("%s\n", rc ? "FAIL" : "PASS"); 429 free(fa); free(fb); free(wc); free(extra); 430 return rc; 431 } 432 433 int main(int argc, char **argv) { 434 int sim = 0, bug = 0; 435 for (int i = 1; i < argc; i++) { 436 if (!strcmp(argv[i], "--sim")) sim = 1; 437 else if (!strcmp(argv[i], "--target=sm_86")) target_sm = 86; 438 else if (!strcmp(argv[i], "--target=sm_121")) target_sm = 121; 439 else if (!strcmp(argv[i], "--bug=past-end")) bug = 1; 440 else if (number_arg(argv[i], "--hold-ms=", 60000u, &hold_ms)) {} 441 #if CUDAPP_MIGRATION_PENDING_HELLO_CONTROL 442 else if (!strcmp(argv[i], "--bug=short")) bug = 2; 443 else if (number_arg(argv[i], "--d8-ballast-mib=", 4096u, &ballast_mib)) {} 444 else { printf("usage: hello_gpu [--sim] [--bug=short] [--hold-ms=N] [--d8-ballast-mib=N] | hello_gpu --sim --bug=past-end\n"); return 2; } 445 #else 446 else { printf("usage: hello_gpu [--target=sm_86|--target=sm_121] [--sim [--bug=past-end]] [--hold-ms=N]\n"); return 2; } 447 #endif 448 } 449 if (bug == 1 && !sim) { printf("--bug=past-end is only for --sim: on the GPU it would write past a buffer\n"); return 2; } 450 int rc = 1; 451 OmegaGpuMem code = { 0 }, a = { 0 }, b = { 0 }, c = { 0 }; 452 static BlackwellIRProgram prog; 453 454 printf("hello_gpu: c = a + b over %u floats %s, built with Omega's own kernel builder\n", N_TOTAL, 455 sim ? "on the host simulator (no GPU)" : "on the GPU"); 456 { /* the library this program linked must serve the API it was compiled against (API.md section 2) */ 457 unsigned lib = omega_runtime_api_version(); 458 printf("runtime API %u.%u (library), program built against %u.%u\n", lib >> 16, lib & 0xffffu, 459 OMEGA_RUNTIME_API_VERSION_MAJOR, OMEGA_RUNTIME_API_VERSION_MINOR); 460 if (lib >> 16 != OMEGA_RUNTIME_API_VERSION_MAJOR || (lib & 0xffffu) < OMEGA_RUNTIME_API_VERSION_MINOR || 461 (OMEGA_RUNTIME_API_VERSION_MAJOR == 0 && (lib & 0xffffu) != OMEGA_RUNTIME_API_VERSION_MINOR)) { 462 printf("FAIL: the linked CUDA++ library has runtime API %u.%u, this program needs %u.%u; rebuild it against " 463 "the library it links (make hello-gpu-build)\n", lib >> 16, lib & 0xffffu, 464 OMEGA_RUNTIME_API_VERSION_MAJOR, OMEGA_RUNTIME_API_VERSION_MINOR); 465 return 2; 466 } 467 } 468 double t0 = now_us(); 469 if (build_vecadd(&prog) != 0) { printf("FAIL: the kernel did not build\n"); return 1; } 470 { /* the machine code, encoded once here so its hash and build time can be printed (D10) */ 471 size_t need = omega_bw_program_code_bytes(&prog); 472 void *words = calloc(1, need); 473 size_t written = 0; 474 if (!words || omega_gpu_encode_program_target(&prog, target_sm, words, need, &written) != 0) { printf("FAIL: the kernel did not encode\n"); free(words); return 1; } 475 double t1 = now_us(); 476 printf("kernel built in %.0f us: %zu instructions, %u registers, sm_%u, no compiler run, no cache\n", t1 - t0, written / 16u, prog.regalloc.peak_gpr_usage, target_sm); 477 print_sha("machine code", words, written); 478 free(words); 479 } 480 if (sim) return run_sim(&prog, bug); 481 482 /* ---- Step 2: open the GPU. One process owns one device channel; the lock serialises threads. 483 * D8: resident memory is read just before and just after the open. */ 484 const uint64_t rss_before = resident_kib(); 485 void *extra = ballast(); 486 omega_gpu_session_lock(); 487 if (!omega_gpu_session_open()) { 488 printf("GPU not available (stage: %s)\nNOT_RUN\n", omega_gpu_session_last_error()); 489 omega_gpu_session_unlock(); 490 free(extra); 491 return 2; 492 } 493 const uint64_t rss_open = resident_kib(); 494 if (omega_gpu_session_target_sm() != target_sm) { 495 printf("NOT_RUN: requested sm_%u does not match opened device sm_%u\n", target_sm, omega_gpu_session_target_sm()); 496 rc = 2; goto done; 497 } 498 499 /* ---- Step 3: upload. The code buffer is written by the CPU and executed by the GPU. */ 500 size_t bytes = (size_t)N_TOTAL * sizeof(float), need = omega_bw_program_code_bytes(&prog); 501 size_t written = 0; 502 if (omega_gpu_session_alloc_code(need, &code) != 0 || omega_gpu_encode_program_target(&prog, target_sm, code.cpu, need, &written) != 0 || 503 omega_gpu_session_alloc(bytes, &a) != 0 || omega_gpu_session_alloc(bytes, &b) != 0 || omega_gpu_session_alloc(bytes, &c) != 0) { 504 printf("FAIL: could not set up buffers (stage: %s)\n", omega_gpu_session_last_error()); 505 goto done; 506 } 507 printf("kernel: %zu instructions, %u registers\n", written / 16u, prog.regalloc.peak_gpr_usage); 508 float *fa = a.cpu, *fb = b.cpu; 509 uint32_t *wc = c.cpu; 510 inputs(fa, fb, wc); 511 if (omega_gpu_session_sync_to_gpu(&code) || omega_gpu_session_sync_to_gpu(&a) || omega_gpu_session_sync_to_gpu(&b) || 512 omega_gpu_session_sync_to_gpu(&c)) { printf("FAIL: sync to GPU (stage: %s)\n", omega_gpu_session_last_error()); goto done; } 513 { /* D8: the process with its own buffers in place, before any launch */ 514 OmegaGpuAllocStats st; omega_gpu_session_alloc_stats(&st); 515 print_overhead(1, rss_before, rss_open, resident_kib(), 3u * (uint64_t)bytes + need, st.alloc_bytes, st.allocs); 516 hold(); 517 } 518 519 /* ---- Step 4: launch. The argument words land in the kernel's constant bank: three addresses (low word, 520 * high word) and n. Each launch is pointed at its own slice of the arrays. */ 521 uint32_t declared = omega_bw_gpr_declared(prog.regalloc.peak_gpr_usage); 522 uint64_t gpu_ns = 0; 523 for (uint32_t base = 0; base < N_TOTAL; base += CHUNK) { 524 uint64_t plan[16]; chunk_plan(base, bug, plan); 525 uint64_t off = plan[0]; 526 uint32_t n = (uint32_t)plan[1]; 527 uint32_t args[OMEGA_BW_CBANK_MATMUL_ARGS_WORDS] = { (uint32_t)(a.va + off), (uint32_t)((a.va + off) >> 32), 528 (uint32_t)(b.va + off), (uint32_t)((b.va + off) >> 32), (uint32_t)(c.va + off), (uint32_t)((c.va + off) >> 32), n }; 529 OmegaGpuLaunch L = { .code_va = code.va, .gpr_count = declared < 64 ? 64 : declared, .threads_x = THREADS, .threads_y = 1, 530 .grid_x = (uint32_t)plan[2], .grid_y = 1, .num_elements = n, 531 .args = args, .n_args = OMEGA_BW_CBANK_MATMUL_ARGS_WORDS, .timeout_ms = 10000, .target_sm = target_sm }; 532 uint64_t el = 0; 533 if (omega_gpu_session_launch(&L, &el, NULL) != 0) { printf("FAIL: launch at element %u (stage: %s)\n", base, omega_gpu_session_last_error()); goto done; } 534 gpu_ns += el; 535 } 536 if (omega_gpu_session_sync_to_cpu(&c) != 0) { printf("FAIL: sync to CPU (stage: %s)\n", omega_gpu_session_last_error()); goto done; } 537 538 /* ---- Step 5: check every element. Same IEEE single-precision add on both sides, so the bits must match. */ 539 rc = check(fa, fb, (const uint32_t *)wc); 540 /* vecadd reads a[i] and b[i] and writes c[i]: 8 bytes in, 4 out and one add per element */ 541 print_work(8ull * N_TOTAL, 4ull * N_TOTAL, N_TOTAL, (double)gpu_ns / 1e3); 542 print_sha("output", wc, bytes); 543 printf("%s\n", rc ? "FAIL" : "PASS"); 544 545 done: 546 if (code.cpu) omega_gpu_session_free(&code); 547 if (a.cpu) omega_gpu_session_free(&a); 548 if (b.cpu) omega_gpu_session_free(&b); 549 if (c.cpu) omega_gpu_session_free(&c); 550 omega_gpu_session_unlock(); 551 omega_gpu_session_close(); 552 free(extra); 553 return rc; 554 }