Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/src/omega_gpu_attention_api.h # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / src / omega_gpu_attention_api.h` 290 lines ยท 20358 bytes Raw Blame History 1 #ifndef OMEGA_GPU_ATTENTION_API_H 2 #define OMEGA_GPU_ATTENTION_API_H 3 /* 4 * omega_gpu_attention_api: native (no CUDA) decode attention for the AIEN 5 * inference stack (FB-1 cut 5, 2026-10-04). 6 * 7 * Two kernel families, one query per (sequence, query head), generated by our 8 * own codegen (src/omega_blackwell_codegen.c IR) and launched through the same 9 * chip-proven sequence as cuts 1b and 4: every buffer GPU-uncached (nvos.h 10 * NVOS32_ATTR2_GPU_CACHEABLE: system memory cached by the GPU is not coherent 11 * with CPU mappings), shader caches invalidated before the launch (clcec0.h 12 * NVCEC0_INVALIDATE_SHADER_CACHES, cut 1b finding), first marker, 13 * L2_FLUSH_DIRTY, second marker (C3 tail), poison-filled output scanned for 14 * unwritten words after readback. 15 * 16 * The math follows aien-sovereign-core crates/aien-inference-abi/src/backend.rs 17 * (ReferenceCpuBackend / TensorBackend defaults), read 2026-10-04 at main `8b5caed`: 18 * gqa_attention(out, q, k_cache, v_cache, seq_len, num_q_heads, num_kv_heads, head_dim) 19 * k_cache / v_cache are f32 [seq_len][num_kv_heads][head_dim]; query head h reads 20 * kv head h / (num_q_heads / num_kv_heads); score = (q . k) / sqrt(head_dim); 21 * softmax over all seq_len tokens (no mask: one query attends to the whole history); 22 * out[h] = sum_t softmax_t v_t. seq_len == 0 writes zeros. 23 * paged_attention(out, q, pool, block_ids, context_len, layer_idx, ...) 24 * the KV pool is bf16 in aien-kv-cache's canonical layout (KvLayout strides in 25 * bytes: block, layer, kv plane (0 = K, 1 = V), token, head); token t lives in 26 * block_ids[t / block_size] at slot t % block_size; tokens whose block index is 27 * past the end of block_ids are dropped; context_len == 0 or no blocks writes zeros. 28 * paged_attention_batch: per sequence s, context_lens[s] <= 0 means 0, the block 29 * table row is block_tables[s*max_blocks .. (s+1)*max_blocks] (empty if that row 30 * runs past the array), negative entries are removed (the rest close up). 31 * 32 * Chip math: scores in f32 (FFMA over the head), online softmax per chunk of 33 * head_dim tokens: running max (FMNMX), p = EX2((s - m) * log2 e) folded into the 34 * score scale, rescale factor alpha = EX2(m_old - m_new), f32 sums, final MUFU.RCP. 35 * bf16 K is read as 32-bit pairs (LDG.E) and widened by a 16-bit shift (bf16 is 36 * the top half of an f32); bf16 V by LDG.E.U16 and the same shift. f32 K/V are 37 * read directly. Tolerances are stated and justified in tests/gpu_attention_test.c. 38 * 39 * Launch envelope: at most OMEGA_GPU_ATTN_MAX_CTAS / num_q_heads sequences per launch (investigation 40 * I42, same as cuts 1b and 4): grid = (num_q_heads, sequences per launch * context splits); the paged 41 * path adds up to 2^OMEGA_GPU_ATTN_MAX_LOG2SPLIT context splits per (sequence, head) within 42 * OMEGA_GPU_ATTN_SPLIT_MAX_CTAS (cut F, the rows path proved 1024 CTAs on the chip). 43 * Shared memory: the QMD declares 16 * head_dim bytes (clcec0qmd.h SHARED_MEMORY_SIZE_SHIFTED7, 44 * src/omega_blackwell_qmd.c word 36); the kernel uses exactly 4 arrays of head_dim words: 45 * 1024 bytes for head_dim 64 (TinyLlama, Llama-3.2-1B; the QMD default) and 2048 bytes for 46 * head_dim 128 (Qwen3-4B; GB10 parity PASS 126/0 at `7dd92dc`, evidence/FB1-CUT5-HD128-`7dd92dc`). 47 * head_dim is a kernel parameter (64 or 128): threads per CTA = head_dim = chunk size, one warp 48 * partial per 32 threads in the softmax reductions. 49 * 50 * Staging: the host copies q, the referenced KV blocks' layer slice, the (compacted, 51 * renumbered) block tables and the context lengths into GPU-uncached staging buffers 52 * for each launch and copies the result back. The kernel itself walks the block 53 * table. Resident pool (2026-10-12): a paged call whose pool pointer is the allocation 54 * omega_gpu_attention_pool_alloc returned reads the KV in place instead (no staging; see 55 * that declaration for the one rule). Since the attention hardening cut 56 * (2026-10-04) a launch stages each physical block's layer slice once however many 57 * sequences of the batch reference it (shared CoW prefixes), and OmegaGpuAttnInfo 58 * reports the bytes staged against the per-sequence (naive) figure. 59 * 60 * Cut 4b (2026-10-04): the device, channel and launch scratch are the process-wide 61 * session shared with the matmul and elementwise APIs (omega_gpu_session.h): one 62 * open per process instead of one per call (~40 ms), kernels resident after first 63 * use, staging buffers reused at their high-water mark (the KV slice is written 64 * straight into the device staging buffer). Calls serialise on one lock. 65 */ 66 #include 67 #include 68 #include 69 #include "omega_blackwell_matmul.h" /* OmegaBlackwellKernel */ 70 #ifdef __cplusplus 71 extern "C" { 72 #endif 73 74 enum { 75 OMEGA_GPU_ATTN_OK = 0, 76 OMEGA_GPU_ATTN_BAD_ARGS = -1, /* NULL pointer, zero dimension, head mapping or block id out of range */ 77 OMEGA_GPU_ATTN_TOO_LARGE = -2, /* head_dim not in {64, 128}, num_q_heads > 64, context past the envelope */ 78 OMEGA_GPU_ATTN_CODEGEN_FAIL = -3, /* our codegen refused or exceeded the register budget */ 79 OMEGA_GPU_ATTN_CHIP_FAIL = -4, /* device open, alloc, submit, marker or release failed */ 80 OMEGA_GPU_ATTN_UNWRITTEN = -5 /* output words still equal to their poison after the run */ 81 }; 82 83 #define OMEGA_GPU_ATTN_HEAD_DIM 64u /* the original head_dim; threads per CTA = head_dim (one thread per dimension / per token of a chunk) */ 84 #define OMEGA_GPU_ATTN_HEAD_DIM_128 128u /* the second supported head_dim (Qwen3-4B) */ 85 #define OMEGA_GPU_ATTN_MAX_CTAS 64u 86 /* Cut F (2026-10-12): a paged call splits each (sequence, head) over up to 2^MAX_LOG2SPLIT CTAs along the context 87 * (whole chunks each, at least one chunk per split since cut J, 2026-10-12, which also raised the cap from 8 to 16: at 88 * 1268 tokens the busiest CTA went from three chunks to two; the launch takes the largest count in the batch) within 89 * SPLIT_MAX_CTAS CTAs per launch (the rows path proved 1024 on the chip); the CTAs write unnormalised partials 90 * (acc[head_dim], running max, running sum) that the host combines, also when the split is 1 (the gqa f32 and rows 91 * kernels keep the direct output and are byte for byte the ones before). Each sequence picks its own split count 92 * from its own context, so a result never depends on the other sequences in a launch. */ 93 #define OMEGA_GPU_ATTN_MAX_LOG2SPLIT 4u 94 #define OMEGA_GPU_ATTN_SPLIT_MAX_CTAS 1024u 95 #define OMEGA_GPU_ATTN_MAX_Q_HEADS 64u 96 #define OMEGA_GPU_ATTN_MAX_GQA_CTX 4096u /* contiguous path: one block of 2^12 slots */ 97 98 /* Mirror of aien-kv-cache KvLayoutDesc (crates/aien-kv-cache/src/lib.rs, main `8b5caed`), 99 * field for field, strides in bytes. */ 100 typedef struct { 101 uint64_t block_stride_bytes; 102 uint64_t layer_stride_bytes; 103 uint64_t kv_plane_stride_bytes; 104 uint64_t token_stride_bytes; 105 uint64_t head_stride_bytes; 106 uint64_t pool_bytes; 107 uint32_t num_blocks; 108 uint32_t num_layers; 109 uint32_t block_size; /* must be a power of two (the kernel shifts and masks) */ 110 } OmegaGpuKvLayout; 111 112 typedef struct { 113 uint32_t chip_calls; /* launches made */ 114 uint64_t elapsed_ns; /* sum of submit-to-second-marker over the launches */ 115 uint64_t call_ns; /* wall time of the whole API call (staging, launches, copy-out) */ 116 uint32_t completion_marker; /* first marker word of the last launch */ 117 uint32_t unwritten_words; /* poison words left in the outputs (0 on OK) */ 118 uint32_t gpr_count, insn_count; 119 bool kernel_cache_hit; /* the kernel was already generated */ 120 uint32_t ctas_last_launch, threads_per_cta; 121 char target_chip[64]; 122 uint32_t sm_architecture; 123 /* Appended (attention hardening cut, 2026-10-04): transfer accounting for the call. 124 * Existing field order above is ABI; sovereign-core mirrors this struct field for field. */ 125 uint64_t kv_bytes_staged; /* KV layer-slice bytes actually copied into staging (sum over launches) */ 126 uint64_t kv_bytes_naive; /* what per-sequence staging would have copied (every sequence its own blocks) */ 127 uint32_t kv_blocks_logical; /* block references summed over sequences, truncated to each context */ 128 uint32_t kv_blocks_unique; /* distinct (physical block, layer) slices staged, summed over launches */ 129 uint64_t q_bytes, tab_bytes, out_bytes; /* q, block-table/context and result traffic (sum over launches) */ 130 uint32_t kv_source; /* OMEGA_GPU_ATTN_KV_STAGED (slices copied per call) or OMEGA_GPU_ATTN_KV_RESIDENT (read in place) */ 131 } OmegaGpuAttnInfo; 132 #define OMEGA_GPU_ATTN_KV_STAGED 0u 133 #define OMEGA_GPU_ATTN_KV_RESIDENT 1u 134 135 /* Contiguous f32 KV (TensorBackend::gqa_attention). q and out: [num_q_heads][head_dim]. */ 136 int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache, 137 uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads, 138 uint32_t head_dim, float *out, OmegaGpuAttnInfo *info); 139 140 /* Contiguous f32 KV, many query rows in one call (the prompt read, 2026-10-12). q and out are 141 * [num_rows][num_q_heads][head_dim]; k_cache and v_cache hold base_len + num_rows tokens as 142 * [token][num_kv_heads][head_dim]. Row i attends over the first base_len + i + 1 tokens (causal: 143 * its own token and everything before it). The KV is staged once per call; the rows go to the 144 * chip in launches of up to OMEGA_GPU_ATTN_ROWS_MAX_CTAS / num_q_heads rows (grid y = row, the 145 * same kernel as omega_gpu_gqa_attention_f32, so one row per launch is bit-identical to that 146 * call). Under a serving reservation the rows per launch are also bounded by the q buffer 147 * omega_gpu_attention_reserve_rows sized. base_len + num_rows <= OMEGA_GPU_ATTN_MAX_GQA_CTX. */ 148 #define OMEGA_GPU_ATTN_ROWS_MAX_CTAS 1024u 149 int omega_gpu_gqa_attention_rows_f32(const float *q, const float *k_cache, const float *v_cache, 150 uint32_t base_len, uint32_t num_rows, uint32_t num_q_heads, 151 uint32_t num_kv_heads, uint32_t head_dim, float *out, 152 OmegaGpuAttnInfo *info); 153 154 /* Paged bf16 KV (TensorBackend::paged_attention). pool points at the pool base. */ 155 int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout, 156 const uint32_t *block_ids, uint32_t num_block_ids, 157 uint32_t context_len, uint32_t layer_idx, 158 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, 159 float *out, OmegaGpuAttnInfo *info); 160 161 /* Batched (TensorBackend::paged_attention_batch). block_tables: [num_seqs][max_blocks_per_seq] i32 162 * (negative = none), context_lens: [num_seqs] i32. q and out: [num_seqs][num_q_heads][head_dim]. */ 163 int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout, 164 const int32_t *block_tables, const int32_t *context_lens, 165 uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx, 166 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, 167 float *out, OmegaGpuAttnInfo *info); 168 169 /* Resident KV pool (2026-10-12). One GPU-uncached, host-visible allocation of `bytes` that the caller 170 * writes its paged bf16 KV into directly (sovereign-core's pool buffer). A paged call whose `pool` 171 * pointer is this allocation reads the KV in place: nothing is staged, the block table carries the 172 * physical block ids and the kernel's block stride is the layout's block stride. The kernel forms 173 * block_id * block_stride + the in-block offsets in 32 bits, so a call takes the resident path only 174 * when block_stride_bytes and, for every block it references, block_id * block_stride_bytes + 175 * layer_stride_bytes fit in 32 bits, and the layout's pool_bytes fit the allocation; otherwise that 176 * call stages exactly as before. OmegaGpuAttnInfo.kv_source says which path ran. One pool per 177 * process: a second alloc is refused (BAD_ARGS) until omega_gpu_attention_pool_free. The alloc opens 178 * the session (CHIP_FAIL carries the driver text in omega_gpu_attention_last_error()); under the host 179 * simulator it is plain host memory. The caller must not free the pool while a call is in flight. */ 180 int omega_gpu_attention_pool_alloc(size_t bytes, void **cpu); 181 void omega_gpu_attention_pool_free(void); 182 183 const char *omega_gpu_attention_rc_name(int rc); 184 void omega_gpu_attention_cache_clear(void); 185 186 /* OPT-IN serving reservation (omega_gpu_reserve_serving in omega_gpu_serving.h calls this). Allocates the KV staging 187 * pool (2 planes f32, 8 KiB per token at 8 kv heads x 128), q, output and table buffers once for contexts up to 188 * max_context and up to max_seqs sequences per call. A later call that fits never allocates; one that does not 189 * returns OMEGA_GPU_ATTN_TOO_LARGE ("serving reservation exceeded" in omega_gpu_attention_last_error()) and asks the 190 * driver for nothing. Never called = behaviour unchanged. The f32 contiguous path still refuses contexts past 191 * OMEGA_GPU_ATTN_MAX_GQA_CTX on its own. kv_block_size (power of two, 0 = no paged use) sizes the pool for the paged bf16 192 * path too: it stages whole blocks, so under half a block of context it needs more than the f32 formula. The pool is 193 * sized in BYTES for the larger of the two paths: the paged path therefore admits up to about 2 x max_context tokens 194 * (whole blocks of the same bytes); what it refuses is a call whose staging exceeds the reserved bytes. max_seqs is 195 * checked per launch chunk (the batched call splits sequences into chunks of 64 / num_q_heads), so a call with more 196 * sequences than max_seqs succeeds when every chunk fits. A paged or batched call refused on a LATER chunk has already 197 * written the outputs of the earlier chunks: treat TOO_LARGE as "output incomplete". If the reserve fails part way it 198 * rolls back: none of this API's buffers stays flagged. 0 on success, else an OMEGA_GPU_ATTN_* code. */ 199 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); 200 /* Grows the reservation's q, output and table buffers (never shrinks them) so that 201 * omega_gpu_gqa_attention_rows_f32 can send min(max_rows, OMEGA_GPU_ATTN_ROWS_MAX_CTAS / num_q_heads) 202 * rows per launch. The KV staging pool is untouched: the rows of one call share one staged context, 203 * which omega_gpu_attention_reserve already sized for max_context tokens. Call it after 204 * omega_gpu_attention_reserve (omega_gpu_reserve_serving does, with its max_rows). Without it the 205 * rows path still works under a reservation, in launches of as many rows as the q buffer holds. */ 206 int omega_gpu_attention_reserve_rows(uint32_t max_rows, uint32_t num_q_heads, uint32_t head_dim); 207 void omega_gpu_attention_unreserve(void); 208 209 /* Stage name of the most recent CHIP_FAIL ("" if none), shared with the other GPU APIs 210 * (omega_gpu_session_last_error); an open failure carries the driver text. */ 211 const char *omega_gpu_attention_last_error(void); 212 213 /* Test hooks. Mutants are deliberately wrong kernels the parity test must catch; 214 * never set in production. */ 215 typedef enum { 216 OMEGA_GPU_ATTN_MUTANT_NONE = 0, 217 OMEGA_GPU_ATTN_MUTANT_NO_MAX, /* softmax without the running-max subtraction (overflows for large scores) */ 218 OMEGA_GPU_ATTN_MUTANT_KV_HEAD, /* reads kv head (h / ratio) ^ 1 */ 219 OMEGA_GPU_ATTN_MUTANT_SLOT, /* K read from slot (t + 1) % block_size while V keeps slot t (K/V mismatch) */ 220 OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, /* the accumulator is not rescaled when the max moves between chunks */ 221 /* Head-wiring mutants (attention hardening cut, 2026-10-04). Both swap the rows of 222 * query heads h and h ^ 1, so they need num_q_heads even (>= 2); never run them on a 223 * one-head shape (row h ^ 1 of the last sequence would be past the buffer). */ 224 OMEGA_GPU_ATTN_MUTANT_Q_ROW, /* q loaded from query-head row h ^ 1 (kv head and output row stay h) */ 225 OMEGA_GPU_ATTN_MUTANT_OUT_ROW, /* the correct result for head h stored in flattened output row h ^ 1 */ 226 OMEGA_GPU_ATTN_MUTANT_COUNT /* one past the last mutant: every battery enumerates 1 .. COUNT-1 */ 227 } OmegaGpuAttnMutant; 228 void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m); 229 230 /* TEST ONLY (omega #308 regression R2). 0 = production branch-free chunk loop; 1 = the 231 * lane-dependent j >= ctx branch restored inside a BSSY/BSYNC reconvergence region; 232 * 2 = that kernel with the BSYNC dropped (negative control: the host simulator must refuse 233 * it). Clears the kernel cache. */ 234 void omega_gpu_attention_test_set_divergent(int mode); 235 /* "none", "NO_MAX", ... ; "?" past COUNT. The table is checked against COUNT at compile time. */ 236 const char *omega_gpu_attention_mutant_name(OmegaGpuAttnMutant m); 237 238 /* Generate a kernel without launching (host tests, nvdisasm listings). 239 * log2_block_size: shift for token -> block; log2_gqa: shift for query head -> kv head. */ 240 int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, 241 OmegaBlackwellKernel *kernel); 242 243 /* The same with an explicit head_dim (64 or 128; anything else is TOO_LARGE). The 4-argument 244 * omega_gpu_attention_codegen above is head_dim 64 and emits the same bytes as before head_dim 128 existed. */ 245 int omega_gpu_attention_codegen_hd(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, uint32_t head_dim, 246 OmegaBlackwellKernel *kernel); 247 248 /* One launch as the launcher sees it (test hook below). Pointers are host buffers; 249 * params are the eight argument words after the four buffer addresses: 250 * max_blocks, scale bits, block stride, token stride, kv plane stride, head stride, 251 * num_q_heads, context-array byte offset. */ 252 typedef struct { 253 const void *q; size_t q_bytes; 254 const void *pool; size_t pool_bytes; 255 const void *tab; size_t tab_bytes; 256 void *out; size_t out_bytes; 257 uint32_t grid_x, grid_y; 258 uint32_t params[8]; 259 uint64_t pool_va; /* resident pool: chip address of the layer base (`pool` is its host mapping, pool_bytes 0); 0 = stage `pool` */ 260 } OmegaGpuAttnLaunch; 261 262 /* Host simulator hook (tests): when set, every launch runs the allocated IR program 263 * through `sim` instead of the chip. Lets the whole battery run on the host first 264 * (review before chip time). The program is post register allocation. */ 265 struct BlackwellIRProgramTag; 266 typedef int (*OmegaGpuAttnSim)(const void *prog /* const BlackwellIRProgram * */, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info); 267 void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim); 268 /* The shared memory the launcher declares for the kernel the simulator is running (set before each simulated launch). */ 269 uint32_t omega_gpu_attention_test_shared_bytes(void); 270 /* Query heads one CTA serves (cut K): hd 128 groups min(2^log2_gqa, 4) heads of one kv head; hd 64 keeps one head per CTA. */ 271 uint32_t omega_gpu_attention_heads_per_cta(uint32_t head_dim, uint32_t log2_gqa); 272 273 /* Shared-prefix staging dedupe (attention hardening cut, 2026-10-04): within one launch 274 * every (physical block, layer) slice referenced by the batch is staged once, keyed by the 275 * physical block id, and every sequence's compact table points at that one staged slot. 276 * On by default. `false` selects the legacy per-sequence staging (every sequence copies 277 * its own blocks), kept as the reference fallback and as the negative control of the 278 * staging-byte tests. Test hook; never cleared in production. */ 279 void omega_gpu_attention_test_set_dedupe(bool on); 280 /* Test hook: force the context split (log2, 0 = one CTA per head) on every paged call; -1 = automatic. */ 281 void omega_gpu_attention_test_set_split(int log2split); 282 283 /* The resident pool's per-block fit rule (see omega_gpu_attention_pool_alloc), exposed so the 284 * 4 GiB edge can be checked without allocating a 4 GiB pool. Test hook. */ 285 bool omega_gpu_attention_test_resident_fits(const OmegaGpuKvLayout *layout, uint32_t block_id); 286 287 #ifdef __cplusplus 288 } 289 #endif 290 #endif /* OMEGA_GPU_ATTENTION_API_H */