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
omega-mv / src / omega_gpu_attention_api.c
| 1 | /* SPDX-License-Identifier: Apache-2.0 |
| 2 | * Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | /* omega_gpu_attention_api.c: FB-1 cut 5 (2026-10-04). See the header. |
| 18 | * |
| 19 | * Layout: (1) kernel codegen on the BlackwellIR with the serialising scheduler |
| 20 | * of cut 4 (every instruction waits on everything still pending; slow and safe), |
| 21 | * extended with forward branches and more loops; (2) the launcher, cloned from |
| 22 | * cut 4's run_abc with a fourth buffer (block tables and context lengths), 16 |
| 23 | * argument words, and cut 1b's shader-cache invalidate; (3) the public entry |
| 24 | * points, which stage the referenced KV blocks per launch and apply the oracle's |
| 25 | * argument rules (dropped tokens past the table, negative table entries, zero |
| 26 | * context) on the host. |
| 27 | * |
| 28 | * One CTA per (query head, sequence), head_dim threads (64 or 128; the text below says 64, the |
| 29 | * constants scale with KSpec.hd). The context is walked in chunks of head_dim tokens: |
| 30 | * phase A thread t owns token base+t: block lookup, K dot q (f32 FFMA), s = dot * scale |
| 31 | * (scale folds 1/sqrt(d) and log2 e), s and the token's byte offset go to shared; |
| 32 | * reduce chunk max (SHFL.DOWN tree per warp, lane partials to shared, BAR.SYNC, 2 LDS), |
| 33 | * m_new = max(m, chunk max), alpha = EX2(m - m_new), p = EX2(s - m_new) to shared, |
| 34 | * chunk sum the same way, l = l * alpha + chunk sum; |
| 35 | * phase B thread d owns dimension d: acc = acc * alpha + sum over the chunk of p_t * V[t][d]. |
| 36 | * Then out[d] = acc * RCP(l). The first chunk sees m = -inf, so alpha = EX2(-inf) = 0 and |
| 37 | * the initial l and acc drop out (PTX ISA ex2.approx: ex2(-Inf) = +0). |
| 38 | * |
| 39 | * Shared memory (16 * head_dim bytes; hd 64: 1024 bytes, the QMD default): [0,4hd) q, [4hd,8hd) s then p, |
| 40 | * [8hd,12hd) token byte offsets, [12hd,16hd) warp partials for the reductions (hd 64: 0, 256, 512, |
| 41 | * 768; hd 128: 0, 512, 1024, 1536; the partials of warp w are read at 12hd + 128w). |
| 42 | */ |
| 43 | #include "omega_gpu_attention_api.h" |
| 44 | #include "omega_blackwell_codegen.h" |
| 45 | #include "omega_bw_om_ir.h" |
| 46 | #include "omega_native.h" |
| 47 | #include "omega_blackwell_qmd.h" |
| 48 | #include "omega_blackwell_submit.h" |
| 49 | #include "omega_gpu_session.h" |
| 50 | #include "omega_gpu_fmt.h" |
| 51 | #include "sha256.h" |
| 52 | #ifdef OMEGA_ATTN_DEBUG |
| 53 | #include <stdio.h> /* the debug trace only; never in the freestanding build */ |
| 54 | #endif |
| 55 | #include <string.h> |
| 56 | |
| 57 | /* ------------------------------------------------------------------ codegen */ |
| 58 | |
| 59 | /* A value first defined inside a loop may not be read after it before being redefined. */ |
| 60 | static int check_loop_invariant(const BlackwellIRProgram *prog, const uint64_t *meta) { |
| 61 | const OmegaRegAlloc *ra = &prog->regalloc; |
| 62 | for (size_t L = 0; L < meta[3]; L++) |
| 63 | for (int v = 0; v < ra->num_vregs; v++) { |
| 64 | int fd = ra->intervals[v].first_def; |
| 65 | if (fd < (int)meta[320 + 2 * L] || fd > (int)meta[321 + 2 * L]) continue; |
| 66 | for (size_t i = (size_t)(int)meta[321 + 2 * L] + 1; i < prog->count; i++) { |
| 67 | const BlackwellIRInsn *in = &prog->insns[i]; |
| 68 | if (in->src1_vreg == v || in->src2_vreg == v || in->src3_vreg == v) return -1; |
| 69 | if (in->dst_vreg == v && !in->is_uniform) break; |
| 70 | } |
| 71 | } |
| 72 | return 0; |
| 73 | } |
| 74 | |
| 75 | #define ARG_WORDS 16u |
| 76 | |
| 77 | /* divergent (omega #308 regression R2): 0 = production branch-free chunk loop; 1 = the |
| 78 | * lane-dependent "j >= ctx" branch restored inside a reconvergence region (BSSY/BSYNC) so |
| 79 | * the SHFL reductions run on a joined warp; 2 = the same with the BSYNC dropped (the |
| 80 | * 2026-10-04 bug shape, a negative control the host simulator must catch). */ |
| 81 | typedef struct { bool f32; uint32_t log2bs, log2gqa; int mutant; int divergent; uint32_t hd; int split; } KSpec; |
| 82 | /* split (cut F, 2026-10-12): -1 = direct output (the gqa f32 and rows callers; byte for byte the kernel before). |
| 83 | * 0..MAX_LOG2SPLIT = the paged path: 2^split CTAs share one (sequence, head). Each sequence derives its own split |
| 84 | * count from its own context (so its result never depends on the other sequences in the launch), every CTA writes |
| 85 | * an unnormalised partial (acc[hd], running max, running sum; an empty slice writes acc 0, max -inf) and the host |
| 86 | * combines them, also when split == 0. */ |
| 87 | |
| 88 | /* cut K (2026-10-12, GQA group): at head_dim 128 one CTA serves the GC query heads of one kv head, GC = |
| 89 | * min(2^log2gqa, 4), so every K and V byte of a launch is read once instead of once per query head. The KV |
| 90 | * pool is GPU-uncached (host-written), so the four CTAs of a GQA group were four DRAM reads of the same |
| 91 | * bytes: 21 MB per call at 1268 tokens, the memory ceiling (sc leg smoke-ctx-chunk: 152 us per call). |
| 92 | * Grid x is the head group (num_q_heads / GC CTAs per sequence and split). Shared memory: q, scores and |
| 93 | * warp partials per head, token offsets once. GC = 1 (every hd 64 kernel, hd 128 with gqa 1) emits exactly |
| 94 | * the program before this cut (digest fixtures). */ |
| 95 | static uint32_t heads_per_cta(uint32_t hd, uint32_t log2gqa) { return hd == 128u ? (1u << (log2gqa < 2u ? log2gqa : 2u)) : 1u; } |
| 96 | static uint32_t shared_bytes_for(uint32_t hd, uint32_t log2gqa) { return (3u * heads_per_cta(hd, log2gqa) + 1u) * hd * 4u; } |
| 97 | uint32_t omega_gpu_attention_heads_per_cta(uint32_t head_dim, uint32_t log2_gqa) { return heads_per_cta(head_dim, log2_gqa); } |
| 98 | |
| 99 | #define AT_GPR_BUDGET 96u /* cut K: the GQA-group hd 128 kernel carries four heads of running state (the matmul blocked kernels launch at 108) */ |
| 100 | |
| 101 | static int build_kernel(const KSpec *k, OmegaBlackwellKernel *kernel, BlackwellIRProgram **keep) { |
| 102 | BlackwellIRProgram *prog = omega_gpu_host_calloc(1, sizeof *prog); |
| 103 | if (!prog) return OMEGA_GPU_ATTN_CODEGEN_FAIL; |
| 104 | uint64_t spec[8] = {k->f32, k->log2bs, k->log2gqa, k->mutant, k->divergent, |
| 105 | k->hd, k->split >= 0, k->split >= 0 ? (uint64_t)k->split : 0}; |
| 106 | uint64_t *ins = omega_gpu_host_calloc(8192, sizeof *ins); |
| 107 | uint64_t meta[512] = {0}, emit_status = 1; |
| 108 | int rc = OMEGA_GPU_ATTN_CODEGEN_FAIL; |
| 109 | int valid = ins && omega2_cg_gpu_attn_emit(&emit_status, spec, 8, ins, 8192, meta, 512) == OMEGA_OK && |
| 110 | emit_status == 0 && meta[15] == 0 && omega_bw_ir_from_om(ins, meta, prog) == 0 && |
| 111 | check_loop_invariant(prog, meta) == 0; |
| 112 | omega_gpu_host_free(ins); |
| 113 | if (valid && prog->regalloc.peak_gpr_usage <= AT_GPR_BUDGET) { |
| 114 | size_t max_bytes = (size_t)BW_MAX_IR_INSNS * 16; |
| 115 | memset(kernel, 0, sizeof *kernel); |
| 116 | kernel->code = omega_gpu_host_alloc(max_bytes); |
| 117 | size_t emitted = 0; |
| 118 | if (kernel->code && omega_bw_encode_program(prog, kernel->code, max_bytes, &emitted) == 0) { |
| 119 | kernel->code_size = emitted; |
| 120 | kernel->insn_count = emitted / 16; |
| 121 | kernel->gpr_count = prog->regalloc.peak_gpr_usage; |
| 122 | kernel->uniform_gpr_count = prog->regalloc.peak_ugpr_usage; |
| 123 | sha256_hash(kernel->code, kernel->code_size, kernel->code_digest); |
| 124 | rc = OMEGA_GPU_ATTN_OK; |
| 125 | } else { |
| 126 | omega_gpu_host_free(kernel->code); kernel->code = NULL; |
| 127 | } |
| 128 | } |
| 129 | if (keep && rc == OMEGA_GPU_ATTN_OK) *keep = prog; else omega_gpu_host_free(prog); |
| 130 | return rc; |
| 131 | } |
| 132 | |
| 133 | /* --------------------------------------------------------- kernel cache */ |
| 134 | |
| 135 | /* One kernel per KSpec; the device copy is uploaded once and stays resident for |
| 136 | * the process (cut 4b). The IR program is kept for the host simulator. */ |
| 137 | static int g_mutant; |
| 138 | static int g_divergent; /* omega #308 R2 test hook: see KSpec.divergent */ |
| 139 | static bool g_dedupe = true; /* shared-prefix staging dedupe; false = legacy per-sequence staging (test hook) */ |
| 140 | typedef struct { int used; KSpec k; OmegaBlackwellKernel kernel; BlackwellIRProgram *prog; OmegaGpuMem code; } Slot; |
| 141 | static OmegaGpuAttnSim g_sim; |
| 142 | static Slot g_cache[16]; /* split variants (cut F) multiply the shapes in flight */ |
| 143 | static int g_split = -1; /* test hook: forced log2split (0..OMEGA_GPU_ATTN_MAX_LOG2SPLIT), -1 = chosen per launch from the context */ |
| 144 | static OmegaGpuScratch g_q, g_pool, g_tab, g_out; /* staging, grown to the high-water mark, reused per call */ |
| 145 | static OmegaGpuMem g_resident; /* the resident KV pool (omega_gpu_attention_pool_alloc); cpu NULL = none */ |
| 146 | static bool g_hooked; |
| 147 | #define LOCK() omega_gpu_session_lock() |
| 148 | #define UNLOCK() omega_gpu_session_unlock() |
| 149 | |
| 150 | void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim) { LOCK(); g_sim = sim; UNLOCK(); } |
| 151 | static uint32_t g_sim_shared_bytes; /* shared bytes the launcher would declare for the kernel the simulator is running */ |
| 152 | uint32_t omega_gpu_attention_test_shared_bytes(void) { return g_sim_shared_bytes; } |
| 153 | void omega_gpu_attention_test_set_dedupe(bool on) { LOCK(); g_dedupe = on; UNLOCK(); } |
| 154 | void omega_gpu_attention_test_set_split(int log2split) { LOCK(); g_split = (log2split >= 0 && log2split <= (int)OMEGA_GPU_ATTN_MAX_LOG2SPLIT) ? log2split : -1; UNLOCK(); } |
| 155 | |
| 156 | /* ---- resident KV pool (see the header) ---- */ |
| 157 | |
| 158 | static int dev_open_locked(void); |
| 159 | |
| 160 | /* The kernel computes block_id * block_stride + slot * token_stride + head offset in 32 bits before |
| 161 | * widening onto the 64-bit layer base: one layer slice (both planes, every token and head of the |
| 162 | * block) past the block's start must stay inside 32 bits. */ |
| 163 | static bool resident_fits(const OmegaGpuKvLayout *ly, uint32_t block_id) { |
| 164 | return ly->block_stride_bytes <= 0xffffffffull && |
| 165 | (uint64_t)block_id * ly->block_stride_bytes + ly->layer_stride_bytes <= 0xffffffffull; |
| 166 | } |
| 167 | bool omega_gpu_attention_test_resident_fits(const OmegaGpuKvLayout *layout, uint32_t block_id) { |
| 168 | return layout && resident_fits(layout, block_id); |
| 169 | } |
| 170 | |
| 171 | int omega_gpu_attention_pool_alloc(size_t bytes, void **cpu) { |
| 172 | if (!cpu || bytes == 0) return OMEGA_GPU_ATTN_BAD_ARGS; |
| 173 | *cpu = NULL; |
| 174 | LOCK(); |
| 175 | if (g_resident.cpu) { omega_gpu_session_set_error("attention pool: already allocated"); UNLOCK(); return OMEGA_GPU_ATTN_BAD_ARGS; } |
| 176 | if (g_sim) { |
| 177 | g_resident.cpu = omega_gpu_host_calloc(1, bytes); |
| 178 | if (!g_resident.cpu) { UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } |
| 179 | g_resident.va = (uintptr_t)g_resident.cpu; g_resident.size = bytes; |
| 180 | } else { |
| 181 | int rc = dev_open_locked(); |
| 182 | if (rc != OMEGA_GPU_ATTN_OK) { UNLOCK(); return rc; } |
| 183 | if (omega_gpu_session_alloc(bytes, &g_resident) != 0) { memset(&g_resident, 0, sizeof g_resident); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } |
| 184 | } |
| 185 | *cpu = g_resident.cpu; |
| 186 | UNLOCK(); |
| 187 | return OMEGA_GPU_ATTN_OK; |
| 188 | } |
| 189 | |
| 190 | void omega_gpu_attention_pool_free(void) { |
| 191 | LOCK(); |
| 192 | if (g_resident.cpu) { if (g_sim) omega_gpu_host_free(g_resident.cpu); else omega_gpu_session_free(&g_resident); } |
| 193 | memset(&g_resident, 0, sizeof g_resident); |
| 194 | UNLOCK(); |
| 195 | } |
| 196 | |
| 197 | static void cache_clear_locked(void) { |
| 198 | for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) |
| 199 | if (g_cache[i].used) { omega_gpu_host_free(g_cache[i].kernel.code); omega_gpu_host_free(g_cache[i].prog); omega_gpu_session_free(&g_cache[i].code); memset(&g_cache[i], 0, sizeof g_cache[i]); } |
| 200 | } |
| 201 | |
| 202 | void omega_gpu_attention_cache_clear(void) { |
| 203 | LOCK(); |
| 204 | cache_clear_locked(); |
| 205 | UNLOCK(); |
| 206 | } |
| 207 | |
| 208 | /* Called by the session (lock held, device still open) right before it closes. */ |
| 209 | static void on_session_close(void) { |
| 210 | cache_clear_locked(); |
| 211 | memset(&g_resident, 0, sizeof g_resident); /* the session's memory goes with it; the caller's mapping is dead */ |
| 212 | omega_gpu_session_scratch_free(&g_q); omega_gpu_session_scratch_free(&g_pool); |
| 213 | omega_gpu_session_scratch_free(&g_tab); omega_gpu_session_scratch_free(&g_out); |
| 214 | } |
| 215 | |
| 216 | void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m) { |
| 217 | LOCK(); |
| 218 | g_mutant = (int)m; |
| 219 | cache_clear_locked(); |
| 220 | UNLOCK(); |
| 221 | } |
| 222 | |
| 223 | /* Caller holds the lock. Builds the kernel if needed; uploads the device copy when |
| 224 | * `upload` (the chip path; the simulator never needs one). */ |
| 225 | static int kernel_for(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, int split, bool upload, Slot **out, bool *hit) { |
| 226 | KSpec k = { .f32 = f32, .log2bs = log2bs, .log2gqa = log2gqa, .mutant = g_mutant, .divergent = g_divergent, .hd = hd, .split = split }; |
| 227 | Slot *s = NULL; |
| 228 | for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) |
| 229 | 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 && g_cache[i].k.divergent == k.divergent && g_cache[i].k.hd == k.hd && g_cache[i].k.split == k.split) { /* field compare: memcmp would read struct padding */ |
| 230 | s = &g_cache[i]; *hit = true; break; |
| 231 | } |
| 232 | if (!s) { |
| 233 | OmegaBlackwellKernel kern; BlackwellIRProgram *kp = NULL; |
| 234 | int rc = build_kernel(&k, &kern, &kp); |
| 235 | if (rc != OMEGA_GPU_ATTN_OK) return rc; |
| 236 | size_t slot = 0; |
| 237 | for (size_t i = 0; i < sizeof g_cache / sizeof g_cache[0]; i++) if (!g_cache[i].used) { slot = i; break; } |
| 238 | s = &g_cache[slot]; |
| 239 | if (s->used) { omega_gpu_host_free(s->kernel.code); omega_gpu_host_free(s->prog); omega_gpu_session_free(&s->code); } /* full: evict slot 0 */ |
| 240 | memset(s, 0, sizeof *s); |
| 241 | s->used = 1; s->k = k; s->kernel = kern; s->prog = kp; |
| 242 | *hit = false; |
| 243 | } |
| 244 | if (upload && !s->code.cpu) { |
| 245 | if (omega_gpu_session_alloc_code(s->kernel.code_size, &s->code) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; |
| 246 | memcpy(s->code.cpu, s->kernel.code, s->kernel.code_size); |
| 247 | if (omega_gpu_session_sync_to_gpu(&s->code) != 0) { omega_gpu_session_free(&s->code); return OMEGA_GPU_ATTN_CHIP_FAIL; } |
| 248 | } |
| 249 | *out = s; |
| 250 | return OMEGA_GPU_ATTN_OK; |
| 251 | } |
| 252 | |
| 253 | int omega_gpu_attention_codegen_hd(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, uint32_t head_dim, OmegaBlackwellKernel *kernel) { |
| 254 | if (!kernel || log2_block_size > 16 || log2_gqa > 6) return OMEGA_GPU_ATTN_BAD_ARGS; |
| 255 | if (head_dim != 64u && head_dim != 128u) return OMEGA_GPU_ATTN_TOO_LARGE; |
| 256 | LOCK(); |
| 257 | KSpec k = { .f32 = kv_f32, .log2bs = log2_block_size, .log2gqa = log2_gqa, .mutant = g_mutant, .divergent = g_divergent, .hd = head_dim, .split = -1 }; |
| 258 | UNLOCK(); |
| 259 | return build_kernel(&k, kernel, NULL); |
| 260 | } |
| 261 | |
| 262 | int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, OmegaBlackwellKernel *kernel) { |
| 263 | return omega_gpu_attention_codegen_hd(kv_f32, log2_block_size, log2_gqa, OMEGA_GPU_ATTN_HEAD_DIM, kernel); |
| 264 | } |
| 265 | |
| 266 | const char *omega_gpu_attention_last_error(void) { return omega_gpu_session_last_error(); } |
| 267 | |
| 268 | /* ------------------------------------------------------------ launcher */ |
| 269 | |
| 270 | #define AT_POISON 0xffbadbadu |
| 271 | #define AT_WAIT_MS 600000ull |
| 272 | |
| 273 | static uint64_t now_ns(void) { return omega_gpu_session_now_ns(); } /* the platform clock (CLOCK_NS) */ |
| 274 | |
| 275 | typedef OmegaGpuAttnLaunch Launch; |
| 276 | |
| 277 | /* Caller holds the lock. Chip path: open the shared device on first use. */ |
| 278 | static int dev_open_locked(void) { |
| 279 | if (!g_hooked) { (void)omega_gpu_session_on_close(on_session_close); g_hooked = true; } |
| 280 | return omega_gpu_session_open() ? OMEGA_GPU_ATTN_OK : OMEGA_GPU_ATTN_CHIP_FAIL; |
| 281 | } |
| 282 | |
| 283 | /* Where a call stages the KV slice it is about to hand the kernel: straight into the |
| 284 | * device staging buffer on the chip path (one copy), a host buffer under the simulator. |
| 285 | * Caller holds the lock; the result is valid until the next staging call. */ |
| 286 | static void *stage_target(size_t bytes, void **host_tmp, int *fail_rc) { |
| 287 | *host_tmp = NULL; |
| 288 | *fail_rc = OMEGA_GPU_ATTN_CHIP_FAIL; |
| 289 | if (g_sim) { *host_tmp = omega_gpu_host_alloc(bytes ? bytes : 1); return *host_tmp; } |
| 290 | int r = omega_gpu_session_scratch(&g_pool, bytes); |
| 291 | if (r != 0) { if (r == OMEGA_GPU_SESSION_SCRATCH_RESERVED) *fail_rc = OMEGA_GPU_ATTN_TOO_LARGE; return NULL; } /* reserved bound exceeded: loud, no allocation */ |
| 292 | return g_pool.mem.cpu; |
| 293 | } |
| 294 | |
| 295 | /* One launch through the shared session (omega_gpu_session_launch: shader-cache |
| 296 | * invalidate, constant bank, QMD0/QMD1, first marker, L2_FLUSH_DIRTY, second marker), |
| 297 | * then readback and the poison scan. L->pool may already be the pool staging buffer. */ |
| 298 | static int run_launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) { |
| 299 | int sr = omega_gpu_session_scratch(&g_q, L->q_bytes); |
| 300 | if (!sr) sr = omega_gpu_session_scratch(&g_tab, L->tab_bytes); |
| 301 | if (!sr) sr = omega_gpu_session_scratch(&g_out, L->out_bytes); |
| 302 | if (!sr && !L->pool_va && L->pool != g_pool.mem.cpu) sr = omega_gpu_session_scratch(&g_pool, L->pool_bytes); |
| 303 | if (sr) return sr == OMEGA_GPU_SESSION_SCRATCH_RESERVED ? OMEGA_GPU_ATTN_TOO_LARGE : OMEGA_GPU_ATTN_CHIP_FAIL; |
| 304 | memcpy(g_q.mem.cpu, L->q, L->q_bytes); |
| 305 | if (!L->pool_va && L->pool != g_pool.mem.cpu) memcpy(g_pool.mem.cpu, L->pool, L->pool_bytes); |
| 306 | const uint64_t pool_va = L->pool_va ? L->pool_va : g_pool.mem.va; /* resident: the caller's KV, read in place */ |
| 307 | memcpy(g_tab.mem.cpu, L->tab, L->tab_bytes); |
| 308 | size_t out_words = L->out_bytes / 4; |
| 309 | uint32_t *out_dev = (uint32_t *)g_out.mem.cpu; |
| 310 | for (size_t i = 0; i < out_words; i++) out_dev[i] = AT_POISON; |
| 311 | /* the KV this launch reads: the staged pool, or the resident pool the caller wrote in place */ |
| 312 | if (omega_gpu_session_sync_to_gpu(&g_q.mem) != 0 || omega_gpu_session_sync_to_gpu(&g_tab.mem) != 0 || |
| 313 | omega_gpu_session_sync_to_gpu(&g_out.mem) != 0 || omega_gpu_session_sync_to_gpu(L->pool_va ? &g_resident : &g_pool.mem) != 0) |
| 314 | return OMEGA_GPU_ATTN_CHIP_FAIL; |
| 315 | |
| 316 | uint32_t args[ARG_WORDS]; |
| 317 | args[0] = (uint32_t)g_q.mem.va; args[1] = (uint32_t)(g_q.mem.va >> 32); |
| 318 | args[2] = (uint32_t)pool_va; args[3] = (uint32_t)(pool_va >> 32); |
| 319 | args[4] = (uint32_t)g_out.mem.va; args[5] = (uint32_t)(g_out.mem.va >> 32); |
| 320 | args[6] = (uint32_t)g_tab.mem.va; args[7] = (uint32_t)(g_tab.mem.va >> 32); |
| 321 | memcpy(&args[8], L->params, sizeof L->params); |
| 322 | OmegaGpuLaunch GL = { |
| 323 | .code_va = ks->code.va, .gpr_count = AT_GPR_BUDGET, .threads_x = ks->k.hd, .threads_y = 1, .shared_bytes = shared_bytes_for(ks->k.hd, ks->k.log2gqa), /* (3 GC + 1) arrays of hd words: 1024 B for hd 64, 2048 B for hd 128 gqa 1, 6656 B for hd 128 gqa 4 */ |
| 324 | .grid_x = L->grid_x, .grid_y = L->grid_y, .num_elements = out_words, |
| 325 | .args = args, .n_args = ARG_WORDS, .timeout_ms = AT_WAIT_MS, |
| 326 | }; |
| 327 | uint64_t elapsed = 0; uint32_t marker = 0; |
| 328 | if (omega_gpu_session_launch(&GL, &elapsed, &marker) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; |
| 329 | if (omega_gpu_session_sync_to_cpu(&g_out.mem) != 0) return OMEGA_GPU_ATTN_CHIP_FAIL; |
| 330 | |
| 331 | memcpy(L->out, g_out.mem.cpu, L->out_bytes); |
| 332 | uint32_t unwritten = 0; |
| 333 | for (size_t i = 0; i < out_words; i++) if (((uint32_t *)L->out)[i] == AT_POISON) unwritten++; |
| 334 | if (info) { |
| 335 | info->chip_calls++; |
| 336 | info->elapsed_ns += elapsed; |
| 337 | info->completion_marker = marker; |
| 338 | info->unwritten_words += unwritten; |
| 339 | info->threads_per_cta = ks->k.hd; |
| 340 | info->ctas_last_launch = L->grid_x * L->grid_y; |
| 341 | } |
| 342 | return unwritten ? OMEGA_GPU_ATTN_UNWRITTEN : OMEGA_GPU_ATTN_OK; |
| 343 | } |
| 344 | |
| 345 | /* Caller holds the lock. Accounts the launch's q / table / output traffic (the KV |
| 346 | * staging bytes are accounted where the slices are copied). */ |
| 347 | static int launch(const Slot *ks, const Launch *L, OmegaGpuAttnInfo *info) { |
| 348 | if (info) { |
| 349 | info->q_bytes += L->q_bytes; info->tab_bytes += L->tab_bytes; info->out_bytes += L->out_bytes; |
| 350 | info->kv_source = L->pool_va ? OMEGA_GPU_ATTN_KV_RESIDENT : OMEGA_GPU_ATTN_KV_STAGED; |
| 351 | } |
| 352 | if (g_sim) { g_sim_shared_bytes = shared_bytes_for(ks->k.hd, ks->k.log2gqa); return g_sim(ks->prog, L, info); } |
| 353 | return run_launch(ks, L, info); |
| 354 | } |
| 355 | |
| 356 | /* ---- opt-in serving reservation (see the header) ---- */ |
| 357 | |
| 358 | static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t *log2gqa); |
| 359 | static int log2_exact(uint32_t v, uint32_t *out); |
| 360 | |
| 361 | int omega_gpu_attention_reserve(uint32_t max_context, uint32_t max_seqs, uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t kv_block_size) { |
| 362 | uint32_t log2gqa, log2bs; |
| 363 | if (max_context == 0 || max_seqs == 0) { omega_gpu_session_set_error("attention reserve: zero bound"); return OMEGA_GPU_ATTN_BAD_ARGS; } |
| 364 | if (kv_block_size && log2_exact(kv_block_size, &log2bs) != 0) { omega_gpu_session_set_error("attention reserve: block size not a power of two"); return OMEGA_GPU_ATTN_BAD_ARGS; } |
| 365 | int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa); |
| 366 | if (rc != OMEGA_GPU_ATTN_OK) { omega_gpu_session_set_error("attention reserve: bad head shape"); return rc; } |
| 367 | /* KV staging, worst case over the two paths, per sequence: contiguous f32 holds both planes for max_context tokens |
| 368 | * (2 * ctx * kvh * hd * 4); paged bf16 stages whole blocks of both planes (round_up(ctx, block) * kvh * hd * 4), which |
| 369 | * is the larger one when max_context is under half a block. */ |
| 370 | size_t per_seq = 2u * max_context * (size_t)num_kv_heads * head_dim * 4u; |
| 371 | if (kv_block_size) { |
| 372 | size_t paged = ((size_t)max_context + kv_block_size - 1) / kv_block_size * kv_block_size * num_kv_heads * head_dim * 4u; |
| 373 | if (paged > per_seq) per_seq = paged; |
| 374 | } |
| 375 | const size_t pool = per_seq * max_seqs; |
| 376 | /* q rows for every sequence, and the output buffer sized for the paged path's partials of one launch |
| 377 | * (cut J: up to 2^MAX_LOG2SPLIT partials of head_dim + 2 words per (sequence, head), at most |
| 378 | * MAX_CTAS / num_q_heads sequences per launch; the rows reserve usually asks for more). */ |
| 379 | const size_t q_bytes = (size_t)max_seqs * num_q_heads * head_dim * 4u; |
| 380 | size_t launch_seqs = OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads; |
| 381 | if (launch_seqs == 0) launch_seqs = 1; |
| 382 | if (launch_seqs > max_seqs) launch_seqs = max_seqs; |
| 383 | const size_t partials = launch_seqs * num_q_heads * ((size_t)1u << OMEGA_GPU_ATTN_MAX_LOG2SPLIT) * ((size_t)head_dim + 2u) * 4u; |
| 384 | const size_t qo = q_bytes > partials ? q_bytes : partials; |
| 385 | const size_t tab = ((size_t)max_seqs * max_context + max_seqs) * 4u; |
| 386 | LOCK(); |
| 387 | rc = OMEGA_GPU_ATTN_OK; |
| 388 | if (g_sim) rc = OMEGA_GPU_ATTN_OK; /* the simulator stages in host memory: nothing to reserve */ |
| 389 | else if (dev_open_locked() != OMEGA_GPU_ATTN_OK) rc = OMEGA_GPU_ATTN_CHIP_FAIL; |
| 390 | else if (omega_gpu_session_scratch_reserve(&g_pool, pool) || omega_gpu_session_scratch_reserve(&g_q, q_bytes) || |
| 391 | omega_gpu_session_scratch_reserve(&g_out, qo) || omega_gpu_session_scratch_reserve(&g_tab, tab < 8 ? 8 : tab)) { |
| 392 | /* roll back this API's own buffers: a failed reserve leaves nothing flagged (growth allowed as before) */ |
| 393 | omega_gpu_session_scratch_unreserve(&g_pool); omega_gpu_session_scratch_unreserve(&g_q); |
| 394 | omega_gpu_session_scratch_unreserve(&g_out); omega_gpu_session_scratch_unreserve(&g_tab); |
| 395 | rc = OMEGA_GPU_ATTN_CHIP_FAIL; |
| 396 | } |
| 397 | UNLOCK(); |
| 398 | return rc; |
| 399 | } |
| 400 | |
| 401 | int omega_gpu_attention_reserve_rows(uint32_t max_rows, uint32_t num_q_heads, uint32_t head_dim) { |
| 402 | if (max_rows == 0 || num_q_heads == 0 || num_q_heads > OMEGA_GPU_ATTN_MAX_Q_HEADS || (head_dim != 64u && head_dim != 128u)) { |
| 403 | omega_gpu_session_set_error("attention reserve rows: bad bound"); |
| 404 | return OMEGA_GPU_ATTN_BAD_ARGS; |
| 405 | } |
| 406 | uint32_t per = OMEGA_GPU_ATTN_ROWS_MAX_CTAS / num_q_heads; |
| 407 | if (per == 0) per = 1; |
| 408 | if (per > max_rows) per = max_rows; |
| 409 | const size_t qo = (size_t)per * num_q_heads * head_dim * 4u, tab = (size_t)per * 8u; |
| 410 | LOCK(); |
| 411 | int rc = OMEGA_GPU_ATTN_OK; |
| 412 | if (g_sim) rc = OMEGA_GPU_ATTN_OK; |
| 413 | else if (dev_open_locked() != OMEGA_GPU_ATTN_OK) rc = OMEGA_GPU_ATTN_CHIP_FAIL; |
| 414 | else if ((qo > g_q.cap && omega_gpu_session_scratch_reserve(&g_q, qo)) || |
| 415 | (qo > g_out.cap && omega_gpu_session_scratch_reserve(&g_out, qo)) || |
| 416 | (tab > g_tab.cap && omega_gpu_session_scratch_reserve(&g_tab, tab))) |
| 417 | rc = OMEGA_GPU_ATTN_CHIP_FAIL; /* growth failed; whatever grew stays reserved at its larger size */ |
| 418 | UNLOCK(); |
| 419 | return rc; |
| 420 | } |
| 421 | void omega_gpu_attention_unreserve(void) { |
| 422 | LOCK(); |
| 423 | omega_gpu_session_scratch_unreserve(&g_pool); omega_gpu_session_scratch_unreserve(&g_q); |
| 424 | omega_gpu_session_scratch_unreserve(&g_out); omega_gpu_session_scratch_unreserve(&g_tab); |
| 425 | UNLOCK(); |
| 426 | } |
| 427 | |
| 428 | /* ------------------------------------------------------- public entries */ |
| 429 | |
| 430 | static void info_begin(OmegaGpuAttnInfo *info, const OmegaBlackwellKernel *k, bool hit) { |
| 431 | if (!info) return; |
| 432 | memset(info, 0, sizeof *info); |
| 433 | info->kernel_cache_hit = hit; |
| 434 | info->gpr_count = k->gpr_count; |
| 435 | info->insn_count = (uint32_t)k->insn_count; |
| 436 | omega_gpu_fmt(info->target_chip, sizeof info->target_chip, "NVIDIA DGX Spark (Grace Blackwell GB10)"); |
| 437 | info->sm_architecture = 121; |
| 438 | } |
| 439 | static uint32_t f2u(float f) { uint32_t u; memcpy(&u, &f, 4); return u; } |
| 440 | static int log2_exact(uint32_t v, uint32_t *out) { |
| 441 | if (v == 0 || (v & (v - 1))) return -1; |
| 442 | uint32_t l = 0; while ((1u << l) != v) l++; |
| 443 | *out = l; return 0; |
| 444 | } |
| 445 | /* log2(e) / sqrt(head_dim) with the square roots as literals (8 and 11.313708498984761 = sqrt(128), both exactly what sqrt() returns): |
| 446 | * the library must not need libm (omegatool links without -lm; a constant head_dim folded sqrt away, a runtime one does not). */ |
| 447 | static float score_scale(uint32_t hd) { return (float)(1.4426950408889634 / (hd == 128u ? 11.313708498984761 : 8.0)); } |
| 448 | |
| 449 | /* Common head-shape checks; returns log2 of the gqa ratio. */ |
| 450 | static int check_heads(uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, uint32_t *log2gqa) { |
| 451 | if (num_q_heads == 0 || num_kv_heads == 0 || head_dim == 0) return OMEGA_GPU_ATTN_BAD_ARGS; |
| 452 | if ((head_dim != 64u && head_dim != 128u) || num_q_heads > OMEGA_GPU_ATTN_MAX_Q_HEADS) return OMEGA_GPU_ATTN_TOO_LARGE; |
| 453 | if (num_q_heads % num_kv_heads != 0 || log2_exact(num_q_heads / num_kv_heads, log2gqa) != 0) return OMEGA_GPU_ATTN_BAD_ARGS; |
| 454 | return OMEGA_GPU_ATTN_OK; |
| 455 | } |
| 456 | |
| 457 | /* Common prologue of every chip entry (lock held on success): device, kernel, info. */ |
| 458 | static int begin(bool f32, uint32_t log2bs, uint32_t log2gqa, uint32_t hd, int split, Slot **ks, OmegaGpuAttnInfo *info) { |
| 459 | LOCK(); |
| 460 | int rc = g_sim ? OMEGA_GPU_ATTN_OK : dev_open_locked(); |
| 461 | bool hit = false; |
| 462 | if (rc == OMEGA_GPU_ATTN_OK) rc = kernel_for(f32, log2bs, log2gqa, hd, split, !g_sim, ks, &hit); |
| 463 | if (rc != OMEGA_GPU_ATTN_OK) { UNLOCK(); return rc; } |
| 464 | info_begin(info, &(*ks)->kernel, hit); |
| 465 | return OMEGA_GPU_ATTN_OK; |
| 466 | } |
| 467 | |
| 468 | int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache, |
| 469 | uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads, |
| 470 | uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) { |
| 471 | uint64_t t0 = now_ns(); |
| 472 | if (!q || !k_cache || !v_cache || !out) return OMEGA_GPU_ATTN_BAD_ARGS; |
| 473 | uint32_t log2gqa; |
| 474 | int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa); |
| 475 | if (rc != OMEGA_GPU_ATTN_OK) return rc; |
| 476 | if (seq_len > OMEGA_GPU_ATTN_MAX_GQA_CTX) return OMEGA_GPU_ATTN_TOO_LARGE; |
| 477 | const uint32_t HD = head_dim; |
| 478 | size_t n_out = (size_t)num_q_heads * HD; |
| 479 | 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; } |
| 480 | Slot *ks = NULL; |
| 481 | const uint32_t log2bs = 12; /* one block of 4096 slots */ |
| 482 | rc = begin(true, log2bs, log2gqa, HD, -1, &ks, info); |
| 483 | if (rc != OMEGA_GPU_ATTN_OK) return rc; |
| 484 | size_t plane = (size_t)seq_len * num_kv_heads * HD * 4; |
| 485 | void *host_tmp = NULL; |
| 486 | int stage_rc; |
| 487 | uint8_t *pool = stage_target(2 * plane, &host_tmp, &stage_rc); |
| 488 | if (!pool) { UNLOCK(); return stage_rc; } |
| 489 | memcpy(pool, k_cache, plane); |
| 490 | memcpy(pool + plane, v_cache, plane); |
| 491 | if (info) { info->kv_bytes_staged += 2 * plane; info->kv_bytes_naive += 2 * plane; info->kv_blocks_logical += 1; info->kv_blocks_unique += 1; } /* one contiguous pseudo-block */ |
| 492 | uint32_t tab[2] = { 0, seq_len }; /* table row {0}, then the context length at byte 4 */ |
| 493 | Launch L = { |
| 494 | .q = q, .q_bytes = n_out * 4, .pool = pool, .pool_bytes = 2 * plane, .tab = tab, .tab_bytes = sizeof tab, |
| 495 | .out = out, .out_bytes = n_out * 4, .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = 1, |
| 496 | .params = { 1, f2u(score_scale(HD)), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, 4 } |
| 497 | }; |
| 498 | rc = launch(ks, &L, info); |
| 499 | omega_gpu_host_free(host_tmp); |
| 500 | UNLOCK(); |
| 501 | if (info) info->call_ns = now_ns() - t0; |
| 502 | return rc; |
| 503 | } |
| 504 | |
| 505 | /* Rows per launch of the rows path: the CTA bound, then (under a reservation) what the q buffer holds. Caller holds the lock. */ |
| 506 | static uint32_t rows_per_launch(uint32_t num_rows, uint32_t num_q_heads, size_t row_bytes) { |
| 507 | uint32_t per = OMEGA_GPU_ATTN_ROWS_MAX_CTAS / num_q_heads; |
| 508 | if (per == 0) per = 1; |
| 509 | if (per > num_rows) per = num_rows; |
| 510 | if (!g_sim && g_q.reserved && g_q.cap >= row_bytes) { |
| 511 | size_t fit = g_q.cap / row_bytes; |
| 512 | if (fit < per) per = (uint32_t)fit; |
| 513 | } |
| 514 | return per; |
| 515 | } |
| 516 | |
| 517 | int omega_gpu_gqa_attention_rows_f32(const float *q, const float *k_cache, const float *v_cache, |
| 518 | uint32_t base_len, uint32_t num_rows, uint32_t num_q_heads, |
| 519 | uint32_t num_kv_heads, uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) { |
| 520 | uint64_t t0 = now_ns(); |
| 521 | if (!q || !k_cache || !v_cache || !out || num_rows == 0) return OMEGA_GPU_ATTN_BAD_ARGS; |
| 522 | uint32_t log2gqa; |
| 523 | int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa); |
| 524 | if (rc != OMEGA_GPU_ATTN_OK) return rc; |
| 525 | if ((uint64_t)base_len + num_rows > OMEGA_GPU_ATTN_MAX_GQA_CTX) return OMEGA_GPU_ATTN_TOO_LARGE; |
| 526 | const uint32_t HD = head_dim, total = base_len + num_rows; |
| 527 | const size_t row = (size_t)num_q_heads * HD; |
| 528 | Slot *ks = NULL; |
| 529 | const uint32_t log2bs = 12; /* one block of 4096 slots, as the single-row call */ |
| 530 | rc = begin(true, log2bs, log2gqa, HD, -1, &ks, info); |
| 531 | if (rc != OMEGA_GPU_ATTN_OK) return rc; |
| 532 | /* the whole context (every row's keys are a prefix of it) staged once */ |
| 533 | size_t plane = (size_t)total * num_kv_heads * HD * 4; |
| 534 | void *host_tmp = NULL; |
| 535 | int stage_rc; |
| 536 | uint8_t *pool = stage_target(2 * plane, &host_tmp, &stage_rc); |
| 537 | if (!pool) { UNLOCK(); return stage_rc; } |
| 538 | memcpy(pool, k_cache, plane); |
| 539 | memcpy(pool + plane, v_cache, plane); |
| 540 | if (info) { info->kv_bytes_staged += 2 * plane; info->kv_bytes_naive += (uint64_t)num_rows * 2 * plane; info->kv_blocks_logical += num_rows; info->kv_blocks_unique += 1; } |
| 541 | const uint32_t per = rows_per_launch(num_rows, num_q_heads, row * 4); |
| 542 | /* table of one launch: per block ids (all 0: the one staged block), then per context lengths */ |
| 543 | uint32_t *tab = omega_gpu_host_calloc(2 * (size_t)per, sizeof *tab); |
| 544 | if (!tab) { omega_gpu_host_free(host_tmp); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } |
| 545 | for (uint32_t r0 = 0; r0 < num_rows && rc == OMEGA_GPU_ATTN_OK; r0 += per) { |
| 546 | const uint32_t nr = num_rows - r0 < per ? num_rows - r0 : per; |
| 547 | for (uint32_t i = 0; i < nr; i++) { tab[i] = 0; tab[nr + i] = base_len + r0 + i + 1; } |
| 548 | Launch L = { |
| 549 | .q = q + (size_t)r0 * row, .q_bytes = (size_t)nr * row * 4, .pool = pool, .pool_bytes = 2 * plane, |
| 550 | .tab = tab, .tab_bytes = (size_t)2 * nr * 4, .out = out + (size_t)r0 * row, .out_bytes = (size_t)nr * row * 4, |
| 551 | .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = nr, |
| 552 | .params = { 1, f2u(score_scale(HD)), (uint32_t)(2 * plane), num_kv_heads * HD * 4, (uint32_t)plane, HD * 4, num_q_heads, nr * 4 } |
| 553 | }; |
| 554 | rc = launch(ks, &L, info); |
| 555 | } |
| 556 | omega_gpu_host_free(tab); |
| 557 | omega_gpu_host_free(host_tmp); |
| 558 | UNLOCK(); |
| 559 | if (info) info->call_ns = now_ns() - t0; |
| 560 | return rc; |
| 561 | } |
| 562 | |
| 563 | /* Paged path shared by the single and batched entries. tables[s] has n_blocks[s] entries |
| 564 | * (already filtered of negatives), ctx[s] the context length. */ |
| 565 | /* cut F: a sequence's own split count from its context alone (the kernel computes the same): log2 of the largest |
| 566 | * power of two <= min(2^MAX_LOG2SPLIT, chunks), chunks = ceil(ctx / HD) (cut J: one whole chunk per split; cut F took two). */ |
| 567 | static uint32_t own_log2split(uint32_t ctx, uint32_t HD) { |
| 568 | uint32_t x = (ctx + HD - 1) / HD, l = 0; |
| 569 | while (l < OMEGA_GPU_ATTN_MAX_LOG2SPLIT && (2u << l) <= x) l++; |
| 570 | return l; |
| 571 | } |
| 572 | |
| 573 | /* 2^x in float without the math library (the engine archive also links where there is none): round x to the |
| 574 | * nearest integer n, 2^f on f in [-0.5, 0.5] by the Cephes exp2f polynomial, scale by 2^n through the exponent |
| 575 | * bits. x <= -127 (so also -inf, an empty split) is 0. The combine only passes x <= 0. */ |
| 576 | static float host_exp2(float x) { |
| 577 | if (x <= -127.0f) return 0.0f; |
| 578 | if (x > 127.0f) x = 127.0f; |
| 579 | int n = (int)(x + (x < 0.0f ? -0.5f : 0.5f)); |
| 580 | const float f = x - (float)n; |
| 581 | float px = 1.535336188319500e-4f; |
| 582 | px = px * f + 1.339887440266574e-3f; |
| 583 | px = px * f + 9.618437357674640e-3f; |
| 584 | px = px * f + 5.550332471162809e-2f; |
| 585 | px = px * f + 2.402264791363012e-1f; |
| 586 | px = px * f + 6.931472028550421e-1f; |
| 587 | px = 1.0f + f * px; |
| 588 | if (n < -126) { px *= 0.5f; n = -126; } |
| 589 | union { uint32_t u; float f; } sc; |
| 590 | sc.u = (uint32_t)(n + 127) << 23; |
| 591 | return px * sc.f; |
| 592 | } |
| 593 | |
| 594 | /* cut F: fold the per-split partials of each (sequence, head) row into out. w_s = 2^(M_s - max M): the kernel's |
| 595 | * running max and sum live in the log2 domain (scale carries log2 e, MUFU.EX2). A row whose every split is empty |
| 596 | * (context 0) is 0. */ |
| 597 | static void combine_splits(const float *part, float *out, size_t rows, uint32_t S, uint32_t HD) { |
| 598 | const size_t pw = (size_t)HD + 2; |
| 599 | for (size_t r = 0; r < rows; r++) { |
| 600 | const float *p = part + r * S * pw; |
| 601 | float *o = out + r * HD; |
| 602 | float mx = -__builtin_inff(); |
| 603 | for (uint32_t s = 0; s < S; s++) if (p[s * pw + HD] > mx) mx = p[s * pw + HD]; |
| 604 | if (!(mx > -__builtin_inff())) { memset(o, 0, (size_t)HD * 4); continue; } |
| 605 | float w[1u << OMEGA_GPU_ATTN_MAX_LOG2SPLIT], lsum = 0.0f; |
| 606 | for (uint32_t s = 0; s < S; s++) { w[s] = host_exp2(p[s * pw + HD] - mx); lsum += w[s] * p[s * pw + HD + 1]; } |
| 607 | const float inv = 1.0f / lsum; |
| 608 | for (uint32_t d = 0; d < HD; d++) { |
| 609 | float a = 0.0f; |
| 610 | for (uint32_t s = 0; s < S; s++) a += w[s] * p[s * pw + d]; |
| 611 | o[d] = a * inv; |
| 612 | } |
| 613 | } |
| 614 | } |
| 615 | |
| 616 | static int paged_core(const float *q, const uint8_t *pool, const OmegaGpuKvLayout *ly, |
| 617 | const uint32_t *const *tables, const uint32_t *n_blocks, const uint32_t *ctx, |
| 618 | uint32_t num_seqs, uint32_t layer_idx, uint32_t num_q_heads, uint32_t num_kv_heads, |
| 619 | uint32_t head_dim, float *out, OmegaGpuAttnInfo *info) { |
| 620 | uint64_t t0 = now_ns(); |
| 621 | uint32_t log2gqa, log2bs; |
| 622 | int rc = check_heads(num_q_heads, num_kv_heads, head_dim, &log2gqa); |
| 623 | if (rc != OMEGA_GPU_ATTN_OK) return rc; |
| 624 | const uint32_t HD = head_dim; |
| 625 | if (!ly || layer_idx >= ly->num_layers || log2_exact(ly->block_size, &log2bs) != 0) return OMEGA_GPU_ATTN_BAD_ARGS; |
| 626 | /* the oracle addresses heads as kv_head * head_dim * 2 inside a token: the layout must agree */ |
| 627 | if (ly->head_stride_bytes != HD * 2 || ly->token_stride_bytes != (uint64_t)num_kv_heads * HD * 2 || |
| 628 | ly->kv_plane_stride_bytes != (uint64_t)ly->block_size * ly->token_stride_bytes || |
| 629 | ly->layer_stride_bytes != 2 * ly->kv_plane_stride_bytes || ly->block_stride_bytes < (uint64_t)ly->num_layers * ly->layer_stride_bytes) |
| 630 | return OMEGA_GPU_ATTN_BAD_ARGS; |
| 631 | size_t row = (size_t)num_q_heads * HD; |
| 632 | /* effective context per sequence and block id range check */ |
| 633 | uint32_t *eff = omega_gpu_host_calloc(num_seqs ? num_seqs : 1, sizeof *eff); |
| 634 | if (!eff) return OMEGA_GPU_ATTN_CHIP_FAIL; |
| 635 | for (uint32_t s = 0; s < num_seqs; s++) { |
| 636 | uint64_t cap = (uint64_t)n_blocks[s] * ly->block_size; |
| 637 | eff[s] = (uint32_t)(ctx[s] < cap ? ctx[s] : cap); |
| 638 | for (uint32_t b = 0; b < n_blocks[s]; b++) { |
| 639 | uint64_t id = tables[s][b]; |
| 640 | if (id >= ly->num_blocks || id * ly->block_stride_bytes + (uint64_t)(layer_idx + 1) * ly->layer_stride_bytes > ly->pool_bytes) { omega_gpu_host_free(eff); return OMEGA_GPU_ATTN_BAD_ARGS; } |
| 641 | } |
| 642 | } |
| 643 | uint32_t seqs_per_launch = OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads; |
| 644 | if (seqs_per_launch == 0) seqs_per_launch = 1; |
| 645 | /* cut F: split each (sequence, head) over 2^log2split CTAs along the context: at least one whole chunk per |
| 646 | * split, from the longest context in the call, within the split launch bound (the test hook forces it). */ |
| 647 | uint32_t log2split = 0; |
| 648 | if (g_split >= 0) log2split = (uint32_t)g_split; |
| 649 | else for (uint32_t s = 0; s < num_seqs; s++) { uint32_t l = own_log2split(eff[s], HD); if (l > log2split) log2split = l; } |
| 650 | while (log2split && ((uint64_t)num_q_heads * seqs_per_launch << log2split) > OMEGA_GPU_ATTN_SPLIT_MAX_CTAS) log2split--; |
| 651 | const uint32_t S = 1u << log2split; |
| 652 | float *part = omega_gpu_host_alloc((size_t)seqs_per_launch * num_q_heads * S * (HD + 2) * 4); /* the partials of one launch */ |
| 653 | if (!part) { omega_gpu_host_free(eff); return OMEGA_GPU_ATTN_CHIP_FAIL; } |
| 654 | Slot *ks = NULL; |
| 655 | rc = begin(false, log2bs, log2gqa, HD, (int)log2split, &ks, info); |
| 656 | if (rc != OMEGA_GPU_ATTN_OK) { omega_gpu_host_free(eff); omega_gpu_host_free(part); return rc; } |
| 657 | uint32_t maxb = 1; |
| 658 | for (uint32_t s = 0; s < num_seqs; s++) if (n_blocks[s] > maxb) maxb = n_blocks[s]; |
| 659 | /* Resident pool (2026-10-12): the caller's pool IS omega's allocation. Read it in place when the |
| 660 | * layout fits the allocation and every referenced block passes the 32-bit fit rule; else stage. */ |
| 661 | bool resident = g_resident.cpu && (const void *)pool == g_resident.cpu && ly->pool_bytes <= g_resident.size; |
| 662 | for (uint32_t s = 0; resident && s < num_seqs; s++) { |
| 663 | uint32_t need = eff[s] ? (eff[s] + ly->block_size - 1) / ly->block_size : 0; |
| 664 | for (uint32_t b = 0; b < need; b++) if (!resident_fits(ly, tables[s][b])) { resident = false; break; } |
| 665 | } |
| 666 | /* Dedupe map: physical block id -> staged slot of the current launch (-1 = not staged yet), |
| 667 | * plus the list of ids touched by the launch (in slot order) so the reset is O(unique). */ |
| 668 | int32_t *slot_of = NULL; uint32_t *touched = NULL; |
| 669 | if (g_dedupe && !resident) { |
| 670 | size_t nb = ly->num_blocks ? ly->num_blocks : 1; |
| 671 | slot_of = omega_gpu_host_alloc(nb * sizeof *slot_of); |
| 672 | touched = omega_gpu_host_alloc(nb * sizeof *touched); |
| 673 | if (!slot_of || !touched) { omega_gpu_host_free(slot_of); omega_gpu_host_free(touched); omega_gpu_host_free(eff); UNLOCK(); return OMEGA_GPU_ATTN_CHIP_FAIL; } |
| 674 | memset(slot_of, 0xff, nb * sizeof *slot_of); /* every entry -1 */ |
| 675 | } |
| 676 | for (uint32_t s0 = 0; s0 < num_seqs && rc == OMEGA_GPU_ATTN_OK; s0 += seqs_per_launch) { |
| 677 | uint32_t ns = num_seqs - s0 < seqs_per_launch ? num_seqs - s0 : seqs_per_launch; |
| 678 | /* logical references: every sequence's blocks up to its (truncated) context */ |
| 679 | uint32_t total = 0; |
| 680 | for (uint32_t s = 0; s < ns; s++) total += eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0; |
| 681 | uint32_t *tab = omega_gpu_host_calloc((size_t)ns * maxb + ns, sizeof *tab); |
| 682 | if (!tab) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; } |
| 683 | if (resident) { |
| 684 | /* the table carries the physical ids; the kernel's block stride is the pool's; the layer |
| 685 | * base is the chip address of this layer's slice of block 0 */ |
| 686 | for (uint32_t s = 0; s < ns; s++) { |
| 687 | uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0; |
| 688 | for (uint32_t b = 0; b < need; b++) tab[(size_t)s * maxb + b] = tables[s0 + s][b]; |
| 689 | tab[(size_t)ns * maxb + s] = eff[s0 + s]; |
| 690 | } |
| 691 | if (info) { info->kv_blocks_logical += total; info->kv_bytes_naive += (uint64_t)total * ly->layer_stride_bytes; } |
| 692 | Launch L = { |
| 693 | .q = q + (size_t)s0 * row, .q_bytes = (size_t)ns * row * 4, |
| 694 | .pool = (const uint8_t *)pool + (size_t)layer_idx * ly->layer_stride_bytes, .pool_bytes = 0, |
| 695 | .tab = tab, .tab_bytes = ((size_t)ns * maxb + ns) * 4, |
| 696 | .out = part, .out_bytes = (size_t)ns * num_q_heads * S * (HD + 2) * 4, |
| 697 | .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = ns * S, |
| 698 | .params = { maxb, f2u(score_scale(HD)), (uint32_t)ly->block_stride_bytes, (uint32_t)ly->token_stride_bytes, |
| 699 | (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 }, |
| 700 | .pool_va = g_resident.va + (uint64_t)layer_idx * ly->layer_stride_bytes, |
| 701 | }; |
| 702 | rc = launch(ks, &L, info); |
| 703 | if (rc == OMEGA_GPU_ATTN_OK) combine_splits(part, out + (size_t)s0 * row, (size_t)ns * num_q_heads, S, HD); |
| 704 | omega_gpu_host_free(tab); |
| 705 | continue; |
| 706 | } |
| 707 | /* pass 1: assign staged slots. Dedupe keys on the PHYSICAL block id (not the table |
| 708 | * position): a CoW prefix block shared by several branches gets one slot. Each |
| 709 | * sequence's compact table keeps its own block order and truncated context. */ |
| 710 | uint32_t g = 0; |
| 711 | for (uint32_t s = 0; s < ns; s++) { |
| 712 | uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0; |
| 713 | for (uint32_t b = 0; b < need; b++) { |
| 714 | uint32_t id = tables[s0 + s][b]; |
| 715 | if (g_dedupe) { |
| 716 | if (slot_of[id] < 0) { slot_of[id] = (int32_t)g; touched[g] = id; g++; } |
| 717 | tab[(size_t)s * maxb + b] = (uint32_t)slot_of[id]; |
| 718 | } else { |
| 719 | tab[(size_t)s * maxb + b] = g++; /* legacy: one slot per reference */ |
| 720 | } |
| 721 | } |
| 722 | tab[(size_t)ns * maxb + s] = eff[s0 + s]; |
| 723 | } |
| 724 | uint64_t staged_bytes = (uint64_t)(g ? g : 1) * ly->layer_stride_bytes; |
| 725 | if (staged_bytes > 0xffffffffull) { omega_gpu_host_free(tab); rc = OMEGA_GPU_ATTN_TOO_LARGE; break; } |
| 726 | void *host_tmp = NULL; |
| 727 | int stage_rc; |
| 728 | uint8_t *staged = stage_target((size_t)staged_bytes, &host_tmp, &stage_rc); |
| 729 | if (!staged) { omega_gpu_host_free(tab); rc = stage_rc; break; } |
| 730 | /* pass 2: copy each staged slot's (physical block, layer) slice exactly once */ |
| 731 | if (g_dedupe) { |
| 732 | for (uint32_t u = 0; u < g; u++) { |
| 733 | const uint8_t *src = pool + (size_t)touched[u] * ly->block_stride_bytes + (size_t)layer_idx * ly->layer_stride_bytes; |
| 734 | memcpy(staged + (size_t)u * ly->layer_stride_bytes, src, (size_t)ly->layer_stride_bytes); |
| 735 | slot_of[touched[u]] = -1; /* reset for the next launch */ |
| 736 | } |
| 737 | } else { |
| 738 | uint32_t w = 0; |
| 739 | for (uint32_t s = 0; s < ns; s++) { |
| 740 | uint32_t need = eff[s0 + s] ? (eff[s0 + s] + ly->block_size - 1) / ly->block_size : 0; |
| 741 | for (uint32_t b = 0; b < need; b++, w++) { |
| 742 | const uint8_t *src = pool + (size_t)tables[s0 + s][b] * ly->block_stride_bytes + (size_t)layer_idx * ly->layer_stride_bytes; |
| 743 | memcpy(staged + (size_t)w * ly->layer_stride_bytes, src, (size_t)ly->layer_stride_bytes); |
| 744 | } |
| 745 | } |
| 746 | } |
| 747 | if (info) { |
| 748 | info->kv_blocks_logical += total; info->kv_blocks_unique += g; |
| 749 | info->kv_bytes_staged += (uint64_t)g * ly->layer_stride_bytes; |
| 750 | info->kv_bytes_naive += (uint64_t)total * ly->layer_stride_bytes; |
| 751 | } |
| 752 | Launch L = { |
| 753 | .q = q + (size_t)s0 * row, .q_bytes = (size_t)ns * row * 4, .pool = staged, .pool_bytes = (size_t)staged_bytes, |
| 754 | .tab = tab, .tab_bytes = ((size_t)ns * maxb + ns) * 4, |
| 755 | .out = part, .out_bytes = (size_t)ns * num_q_heads * S * (HD + 2) * 4, |
| 756 | .grid_x = num_q_heads / heads_per_cta(HD, log2gqa), .grid_y = ns * S, |
| 757 | .params = { maxb, f2u(score_scale(HD)), (uint32_t)ly->layer_stride_bytes, (uint32_t)ly->token_stride_bytes, |
| 758 | (uint32_t)ly->kv_plane_stride_bytes, (uint32_t)ly->head_stride_bytes, num_q_heads, ns * maxb * 4 } |
| 759 | }; |
| 760 | rc = launch(ks, &L, info); |
| 761 | if (rc == OMEGA_GPU_ATTN_OK) combine_splits(part, out + (size_t)s0 * row, (size_t)ns * num_q_heads, S, HD); |
| 762 | omega_gpu_host_free(host_tmp); omega_gpu_host_free(tab); |
| 763 | } |
| 764 | UNLOCK(); |
| 765 | omega_gpu_host_free(eff); omega_gpu_host_free(slot_of); omega_gpu_host_free(touched); omega_gpu_host_free(part); |
| 766 | if (info) info->call_ns = now_ns() - t0; |
| 767 | return rc; |
| 768 | } |
| 769 | |
| 770 | int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout, |
| 771 | const uint32_t *block_ids, uint32_t num_block_ids, |
| 772 | uint32_t context_len, uint32_t layer_idx, |
| 773 | uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, |
| 774 | float *out, OmegaGpuAttnInfo *info) { |
| 775 | if (!q || !pool || !layout || !out || (num_block_ids && !block_ids)) return OMEGA_GPU_ATTN_BAD_ARGS; |
| 776 | const uint32_t *tables[1] = { block_ids }; |
| 777 | uint32_t nb[1] = { num_block_ids }, cx[1] = { context_len }; |
| 778 | return paged_core(q, pool, layout, tables, nb, cx, 1, layer_idx, num_q_heads, num_kv_heads, head_dim, out, info); |
| 779 | } |
| 780 | |
| 781 | int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout, |
| 782 | const int32_t *block_tables, const int32_t *context_lens, |
| 783 | uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx, |
| 784 | uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, |
| 785 | float *out, OmegaGpuAttnInfo *info) { |
| 786 | if (!q || !pool || !layout || !out || !block_tables || !context_lens || num_seqs == 0) return OMEGA_GPU_ATTN_BAD_ARGS; |
| 787 | /* the oracle's rules: ctx <= 0 -> 0; a table row past the array -> empty; negatives removed */ |
| 788 | uint32_t **tables = omega_gpu_host_calloc(num_seqs, sizeof *tables); |
| 789 | uint32_t *nb = omega_gpu_host_calloc(num_seqs, sizeof *nb), *cx = omega_gpu_host_calloc(num_seqs, sizeof *cx); |
| 790 | if (!tables || !nb || !cx) { omega_gpu_host_free(tables); omega_gpu_host_free(nb); omega_gpu_host_free(cx); return OMEGA_GPU_ATTN_CHIP_FAIL; } |
| 791 | int rc = OMEGA_GPU_ATTN_OK; |
| 792 | for (uint32_t s = 0; s < num_seqs; s++) { |
| 793 | cx[s] = context_lens[s] > 0 ? (uint32_t)context_lens[s] : 0; |
| 794 | tables[s] = omega_gpu_host_calloc(max_blocks_per_seq ? max_blocks_per_seq : 1, sizeof **tables); |
| 795 | if (!tables[s]) { rc = OMEGA_GPU_ATTN_CHIP_FAIL; break; } |
| 796 | for (uint32_t b = 0; b < max_blocks_per_seq; b++) { |
| 797 | int32_t v = block_tables[(size_t)s * max_blocks_per_seq + b]; |
| 798 | if (v >= 0) tables[s][nb[s]++] = (uint32_t)v; |
| 799 | } |
| 800 | } |
| 801 | if (rc == OMEGA_GPU_ATTN_OK) |
| 802 | rc = paged_core(q, pool, layout, (const uint32_t *const *)tables, nb, cx, num_seqs, layer_idx, num_q_heads, num_kv_heads, head_dim, out, info); |
| 803 | for (uint32_t s = 0; s < num_seqs; s++) omega_gpu_host_free(tables[s]); |
| 804 | omega_gpu_host_free(tables); omega_gpu_host_free(nb); omega_gpu_host_free(cx); |
| 805 | return rc; |
| 806 | } |
| 807 | |
| 808 | static const char *const k_mutant_names[OMEGA_GPU_ATTN_MUTANT_COUNT] = { |
| 809 | "none", "NO_MAX", "KV_HEAD", "SLOT", "NO_RESCALE", "Q_ROW", "OUT_ROW" |
| 810 | }; |
| 811 | _Static_assert(sizeof k_mutant_names / sizeof k_mutant_names[0] == OMEGA_GPU_ATTN_MUTANT_COUNT, "mutant name table"); |
| 812 | |
| 813 | const char *omega_gpu_attention_mutant_name(OmegaGpuAttnMutant m) { |
| 814 | return (m >= 0 && m < OMEGA_GPU_ATTN_MUTANT_COUNT && k_mutant_names[m]) ? k_mutant_names[m] : "?"; |
| 815 | } |
| 816 | |
| 817 | const char *omega_gpu_attention_rc_name(int rc) { |
| 818 | switch (rc) { |
| 819 | case OMEGA_GPU_ATTN_OK: return "OK"; |
| 820 | case OMEGA_GPU_ATTN_BAD_ARGS: return "BAD_ARGS"; |
| 821 | case OMEGA_GPU_ATTN_TOO_LARGE: return "TOO_LARGE"; |
| 822 | case OMEGA_GPU_ATTN_CODEGEN_FAIL: return "CODEGEN_FAIL"; |
| 823 | case OMEGA_GPU_ATTN_CHIP_FAIL: return "CHIP_FAIL"; |
| 824 | case OMEGA_GPU_ATTN_UNWRITTEN: return "UNWRITTEN"; |
| 825 | default: return "UNKNOWN"; |
| 826 | } |
| 827 | } |
| 828 | |
| 829 | /* omega #308 R2 test hook: 0 production, 1 lane-dependent branch inside a reconvergence |
| 830 | * region, 2 the same with the BSYNC dropped (negative control). Clears the kernel cache. */ |
| 831 | void omega_gpu_attention_test_set_divergent(int mode) { |
| 832 | LOCK(); |
| 833 | g_divergent = (mode < 0 || mode > 2) ? 0 : mode; |
| 834 | cache_clear_locked(); |
| 835 | UNLOCK(); |
| 836 | } |