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/evidence/FB1-CUT5-HD128-7dd92dc/FB1-CUT5-7dd92dc/omega_gpu_attention_api.h # 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 / evidence / FB1-CUT5-HD128-7dd92dc / FB1-CUT5-7dd92dc / omega_gpu_attention_api.h` 214 lines · 13310 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 CTAs per launch (investigation 40 * I42, same as cuts 1b and 4): grid = (num_q_heads, sequences per launch). 41 * Shared memory: the QMD declares 16 * head_dim bytes (clcec0qmd.h SHARED_MEMORY_SIZE_SHIFTED7, 42 * src/omega_blackwell_qmd.c word 36); the kernel uses exactly 4 arrays of head_dim words: 43 * 1024 bytes for head_dim 64 (TinyLlama, Llama-3.2-1B; the QMD default) and 2048 bytes for 44 * head_dim 128 (Qwen3-4B, CPU phase: host simulators only, GB10 parity NOT_RUN). head_dim is a 45 * kernel parameter (64 or 128): threads per CTA = head_dim = chunk size, one warp partial per 46 * 32 threads in the softmax reductions. 47 * 48 * Staging: the host copies q, the referenced KV blocks' layer slice, the (compacted, 49 * renumbered) block tables and the context lengths into GPU-uncached staging buffers 50 * for each launch and copies the result back. The kernel itself walks the block 51 * table; a resident pool handle is a later cut. Since the attention hardening cut 52 * (2026-10-04) a launch stages each physical block's layer slice once however many 53 * sequences of the batch reference it (shared CoW prefixes), and OmegaGpuAttnInfo 54 * reports the bytes staged against the per-sequence (naive) figure. 55 * 56 * Cut 4b (2026-10-04): the device, channel and launch scratch are the process-wide 57 * session shared with the matmul and elementwise APIs (omega_gpu_session.h): one 58 * open per process instead of one per call (~40 ms), kernels resident after first 59 * use, staging buffers reused at their high-water mark (the KV slice is written 60 * straight into the device staging buffer). Calls serialise on one lock. 61 */ 62 #include 63 #include 64 #include 65 #include "omega_blackwell_matmul.h" /* OmegaBlackwellKernel */ 66 #ifdef __cplusplus 67 extern "C" { 68 #endif 69 70 enum { 71 OMEGA_GPU_ATTN_OK = 0, 72 OMEGA_GPU_ATTN_BAD_ARGS = -1, /* NULL pointer, zero dimension, head mapping or block id out of range */ 73 OMEGA_GPU_ATTN_TOO_LARGE = -2, /* head_dim not in {64, 128}, num_q_heads > 64, context past the envelope */ 74 OMEGA_GPU_ATTN_CODEGEN_FAIL = -3, /* our codegen refused or exceeded the register budget */ 75 OMEGA_GPU_ATTN_CHIP_FAIL = -4, /* device open, alloc, submit, marker or release failed */ 76 OMEGA_GPU_ATTN_UNWRITTEN = -5 /* output words still equal to their poison after the run */ 77 }; 78 79 #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) */ 80 #define OMEGA_GPU_ATTN_HEAD_DIM_128 128u /* the second supported head_dim (Qwen3-4B) */ 81 #define OMEGA_GPU_ATTN_MAX_CTAS 64u 82 #define OMEGA_GPU_ATTN_MAX_Q_HEADS 64u 83 #define OMEGA_GPU_ATTN_MAX_GQA_CTX 4096u /* contiguous path: one block of 2^12 slots */ 84 85 /* Mirror of aien-kv-cache KvLayoutDesc (crates/aien-kv-cache/src/lib.rs, main `8b5caed`), 86 * field for field, strides in bytes. */ 87 typedef struct { 88 uint64_t block_stride_bytes; 89 uint64_t layer_stride_bytes; 90 uint64_t kv_plane_stride_bytes; 91 uint64_t token_stride_bytes; 92 uint64_t head_stride_bytes; 93 uint64_t pool_bytes; 94 uint32_t num_blocks; 95 uint32_t num_layers; 96 uint32_t block_size; /* must be a power of two (the kernel shifts and masks) */ 97 } OmegaGpuKvLayout; 98 99 typedef struct { 100 uint32_t chip_calls; /* launches made */ 101 uint64_t elapsed_ns; /* sum of submit-to-second-marker over the launches */ 102 uint64_t call_ns; /* wall time of the whole API call (staging, launches, copy-out) */ 103 uint32_t completion_marker; /* first marker word of the last launch */ 104 uint32_t unwritten_words; /* poison words left in the outputs (0 on OK) */ 105 uint32_t gpr_count, insn_count; 106 bool kernel_cache_hit; /* the kernel was already generated */ 107 uint32_t ctas_last_launch, threads_per_cta; 108 char target_chip[64]; 109 uint32_t sm_architecture; 110 /* Appended (attention hardening cut, 2026-10-04): transfer accounting for the call. 111 * Existing field order above is ABI; sovereign-core mirrors this struct field for field. */ 112 uint64_t kv_bytes_staged; /* KV layer-slice bytes actually copied into staging (sum over launches) */ 113 uint64_t kv_bytes_naive; /* what per-sequence staging would have copied (every sequence its own blocks) */ 114 uint32_t kv_blocks_logical; /* block references summed over sequences, truncated to each context */ 115 uint32_t kv_blocks_unique; /* distinct (physical block, layer) slices staged, summed over launches */ 116 uint64_t q_bytes, tab_bytes, out_bytes; /* q, block-table/context and result traffic (sum over launches) */ 117 uint32_t kv_source; /* OMEGA_GPU_ATTN_KV_STAGED; a resident pool is a later cut */ 118 } OmegaGpuAttnInfo; 119 #define OMEGA_GPU_ATTN_KV_STAGED 0u 120 121 /* Contiguous f32 KV (TensorBackend::gqa_attention). q and out: [num_q_heads][head_dim]. */ 122 int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache, 123 uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads, 124 uint32_t head_dim, float *out, OmegaGpuAttnInfo *info); 125 126 /* Paged bf16 KV (TensorBackend::paged_attention). pool points at the pool base. */ 127 int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout, 128 const uint32_t *block_ids, uint32_t num_block_ids, 129 uint32_t context_len, uint32_t layer_idx, 130 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, 131 float *out, OmegaGpuAttnInfo *info); 132 133 /* Batched (TensorBackend::paged_attention_batch). block_tables: [num_seqs][max_blocks_per_seq] i32 134 * (negative = none), context_lens: [num_seqs] i32. q and out: [num_seqs][num_q_heads][head_dim]. */ 135 int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout, 136 const int32_t *block_tables, const int32_t *context_lens, 137 uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx, 138 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim, 139 float *out, OmegaGpuAttnInfo *info); 140 141 const char *omega_gpu_attention_rc_name(int rc); 142 void omega_gpu_attention_cache_clear(void); 143 144 /* Stage name of the most recent CHIP_FAIL ("" if none), shared with the other GPU APIs 145 * (omega_gpu_session_last_error); an open failure carries the driver text. */ 146 const char *omega_gpu_attention_last_error(void); 147 148 /* Test hooks. Mutants are deliberately wrong kernels the parity test must catch; 149 * never set in production. */ 150 typedef enum { 151 OMEGA_GPU_ATTN_MUTANT_NONE = 0, 152 OMEGA_GPU_ATTN_MUTANT_NO_MAX, /* softmax without the running-max subtraction (overflows for large scores) */ 153 OMEGA_GPU_ATTN_MUTANT_KV_HEAD, /* reads kv head (h / ratio) ^ 1 */ 154 OMEGA_GPU_ATTN_MUTANT_SLOT, /* K read from slot (t + 1) % block_size while V keeps slot t (K/V mismatch) */ 155 OMEGA_GPU_ATTN_MUTANT_NO_RESCALE, /* the accumulator is not rescaled when the max moves between chunks */ 156 /* Head-wiring mutants (attention hardening cut, 2026-10-04). Both swap the rows of 157 * query heads h and h ^ 1, so they need num_q_heads even (>= 2); never run them on a 158 * one-head shape (row h ^ 1 of the last sequence would be past the buffer). */ 159 OMEGA_GPU_ATTN_MUTANT_Q_ROW, /* q loaded from query-head row h ^ 1 (kv head and output row stay h) */ 160 OMEGA_GPU_ATTN_MUTANT_OUT_ROW, /* the correct result for head h stored in flattened output row h ^ 1 */ 161 OMEGA_GPU_ATTN_MUTANT_COUNT /* one past the last mutant: every battery enumerates 1 .. COUNT-1 */ 162 } OmegaGpuAttnMutant; 163 void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m); 164 165 /* TEST ONLY (omega #308 regression R2). 0 = production branch-free chunk loop; 1 = the 166 * lane-dependent j >= ctx branch restored inside a BSSY/BSYNC reconvergence region; 167 * 2 = that kernel with the BSYNC dropped (negative control: the host simulator must refuse 168 * it). Clears the kernel cache. */ 169 void omega_gpu_attention_test_set_divergent(int mode); 170 /* "none", "NO_MAX", ... ; "?" past COUNT. The table is checked against COUNT at compile time. */ 171 const char *omega_gpu_attention_mutant_name(OmegaGpuAttnMutant m); 172 173 /* Generate a kernel without launching (host tests, nvdisasm listings). 174 * log2_block_size: shift for token -> block; log2_gqa: shift for query head -> kv head. */ 175 int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, 176 OmegaBlackwellKernel *kernel); 177 178 /* The same with an explicit head_dim (64 or 128; anything else is TOO_LARGE). The 4-argument 179 * omega_gpu_attention_codegen above is head_dim 64 and emits the same bytes as before head_dim 128 existed. */ 180 int omega_gpu_attention_codegen_hd(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa, uint32_t head_dim, 181 OmegaBlackwellKernel *kernel); 182 183 /* One launch as the launcher sees it (test hook below). Pointers are host buffers; 184 * params are the eight argument words after the four buffer addresses: 185 * max_blocks, scale bits, block stride, token stride, kv plane stride, head stride, 186 * num_q_heads, context-array byte offset. */ 187 typedef struct { 188 const void *q; size_t q_bytes; 189 const void *pool; size_t pool_bytes; 190 const void *tab; size_t tab_bytes; 191 void *out; size_t out_bytes; 192 uint32_t grid_x, grid_y; 193 uint32_t params[8]; 194 } OmegaGpuAttnLaunch; 195 196 /* Host simulator hook (tests): when set, every launch runs the allocated IR program 197 * through `sim` instead of the chip. Lets the whole battery run on the host first 198 * (review before chip time). The program is post register allocation. */ 199 struct BlackwellIRProgramTag; 200 typedef int (*OmegaGpuAttnSim)(const void *prog /* const BlackwellIRProgram * */, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info); 201 void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim); 202 203 /* Shared-prefix staging dedupe (attention hardening cut, 2026-10-04): within one launch 204 * every (physical block, layer) slice referenced by the batch is staged once, keyed by the 205 * physical block id, and every sequence's compact table points at that one staged slot. 206 * On by default. `false` selects the legacy per-sequence staging (every sequence copies 207 * its own blocks), kept as the reference fallback and as the negative control of the 208 * staging-byte tests. Test hook; never cleared in production. */ 209 void omega_gpu_attention_test_set_dedupe(bool on); 210 211 #ifdef __cplusplus 212 } 213 #endif 214 #endif /* OMEGA_GPU_ATTENTION_API_H */