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