interplane.Get Omega
Read in your language

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

branch main Branches Tags History

omega-mv / evidence / FB1-CUT5-b016322 / omega_gpu_attention_api.h

161 lines · 9114 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 (this cut): the host copies q, the referenced KV blocks' layer slice, the
46 * (compacted, renumbered) block tables and the context lengths into GPU-uncached
47 * buffers for each launch and copies the result back. The kernel itself walks the
48 * block table; a resident pool handle is a later cut.
49 */
50#include <stdbool.h>
51#include <stddef.h>
52#include <stdint.h>
53#include "omega_blackwell_matmul.h" /* OmegaBlackwellKernel */
54#ifdef __cplusplus
55extern "C" {
56#endif
57
58enum {
59 OMEGA_GPU_ATTN_OK = 0,
60 OMEGA_GPU_ATTN_BAD_ARGS = -1, /* NULL pointer, zero dimension, head mapping or block id out of range */
61 OMEGA_GPU_ATTN_TOO_LARGE = -2, /* head_dim != 64, num_q_heads > 64, context past the envelope */
62 OMEGA_GPU_ATTN_CODEGEN_FAIL = -3, /* our codegen refused or exceeded the register budget */
63 OMEGA_GPU_ATTN_CHIP_FAIL = -4, /* device open, alloc, submit, marker or release failed */
64 OMEGA_GPU_ATTN_UNWRITTEN = -5 /* output words still equal to their poison after the run */
65};
66
67#define OMEGA_GPU_ATTN_HEAD_DIM 64u /* threads per CTA = head_dim (one thread per dimension / per token of a chunk) */
68#define OMEGA_GPU_ATTN_MAX_CTAS 64u
69#define OMEGA_GPU_ATTN_MAX_Q_HEADS 64u
70#define OMEGA_GPU_ATTN_MAX_GQA_CTX 4096u /* contiguous path: one block of 2^12 slots */
71
72/* Mirror of aien-kv-cache KvLayoutDesc (crates/aien-kv-cache/src/lib.rs, main 8b5caed),
73 * field for field, strides in bytes. */
74typedef struct {
75 uint64_t block_stride_bytes;
76 uint64_t layer_stride_bytes;
77 uint64_t kv_plane_stride_bytes;
78 uint64_t token_stride_bytes;
79 uint64_t head_stride_bytes;
80 uint64_t pool_bytes;
81 uint32_t num_blocks;
82 uint32_t num_layers;
83 uint32_t block_size; /* must be a power of two (the kernel shifts and masks) */
84} OmegaGpuKvLayout;
85
86typedef struct {
87 uint32_t chip_calls; /* launches made */
88 uint64_t elapsed_ns; /* sum of submit-to-second-marker over the launches */
89 uint64_t call_ns; /* wall time of the whole API call (staging, launches, copy-out) */
90 uint32_t completion_marker; /* first marker word of the last launch */
91 uint32_t unwritten_words; /* poison words left in the outputs (0 on OK) */
92 uint32_t gpr_count, insn_count;
93 bool kernel_cache_hit; /* the kernel was already generated */
94 uint32_t ctas_last_launch, threads_per_cta;
95 char target_chip[64];
96 uint32_t sm_architecture;
97} OmegaGpuAttnInfo;
98
99/* Contiguous f32 KV (TensorBackend::gqa_attention). q and out: [num_q_heads][head_dim]. */
100int omega_gpu_gqa_attention_f32(const float *q, const float *k_cache, const float *v_cache,
101 uint32_t seq_len, uint32_t num_q_heads, uint32_t num_kv_heads,
102 uint32_t head_dim, float *out, OmegaGpuAttnInfo *info);
103
104/* Paged bf16 KV (TensorBackend::paged_attention). pool points at the pool base. */
105int omega_gpu_paged_attention_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
106 const uint32_t *block_ids, uint32_t num_block_ids,
107 uint32_t context_len, uint32_t layer_idx,
108 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
109 float *out, OmegaGpuAttnInfo *info);
110
111/* Batched (TensorBackend::paged_attention_batch). block_tables: [num_seqs][max_blocks_per_seq] i32
112 * (negative = none), context_lens: [num_seqs] i32. q and out: [num_seqs][num_q_heads][head_dim]. */
113int omega_gpu_paged_attention_batch_bf16(const float *q, const void *pool, const OmegaGpuKvLayout *layout,
114 const int32_t *block_tables, const int32_t *context_lens,
115 uint32_t max_blocks_per_seq, uint32_t num_seqs, uint32_t layer_idx,
116 uint32_t num_q_heads, uint32_t num_kv_heads, uint32_t head_dim,
117 float *out, OmegaGpuAttnInfo *info);
118
119const char *omega_gpu_attention_rc_name(int rc);
120void omega_gpu_attention_cache_clear(void);
121
122/* Test hooks. Mutants are deliberately wrong kernels the parity test must catch;
123 * never set in production. */
124typedef enum {
125 OMEGA_GPU_ATTN_MUTANT_NONE = 0,
126 OMEGA_GPU_ATTN_MUTANT_NO_MAX, /* softmax without the running-max subtraction (overflows for large scores) */
127 OMEGA_GPU_ATTN_MUTANT_KV_HEAD, /* reads kv head (h / ratio) ^ 1 */
128 OMEGA_GPU_ATTN_MUTANT_SLOT, /* K read from slot (t + 1) % block_size while V keeps slot t (K/V mismatch) */
129 OMEGA_GPU_ATTN_MUTANT_NO_RESCALE /* the accumulator is not rescaled when the max moves between chunks */
130} OmegaGpuAttnMutant;
131void omega_gpu_attention_test_set_mutant(OmegaGpuAttnMutant m);
132
133/* Generate a kernel without launching (host tests, nvdisasm listings).
134 * log2_block_size: shift for token -> block; log2_gqa: shift for query head -> kv head. */
135int omega_gpu_attention_codegen(bool kv_f32, uint32_t log2_block_size, uint32_t log2_gqa,
136 OmegaBlackwellKernel *kernel);
137
138/* One launch as the launcher sees it (test hook below). Pointers are host buffers;
139 * params are the eight argument words after the four buffer addresses:
140 * max_blocks, scale bits, block stride, token stride, kv plane stride, head stride,
141 * num_q_heads, context-array byte offset. */
142typedef struct {
143 const void *q; size_t q_bytes;
144 const void *pool; size_t pool_bytes;
145 const void *tab; size_t tab_bytes;
146 void *out; size_t out_bytes;
147 uint32_t grid_x, grid_y;
148 uint32_t params[8];
149} OmegaGpuAttnLaunch;
150
151/* Host simulator hook (tests): when set, every launch runs the allocated IR program
152 * through `sim` instead of the chip. Lets the whole battery run on the host first
153 * (review before chip time). The program is post register allocation. */
154struct BlackwellIRProgramTag;
155typedef int (*OmegaGpuAttnSim)(const void *prog /* const BlackwellIRProgram * */, const OmegaGpuAttnLaunch *L, OmegaGpuAttnInfo *info);
156void omega_gpu_attention_test_set_simulator(OmegaGpuAttnSim sim);
157
158#ifdef __cplusplus
159}
160#endif
161#endif /* OMEGA_GPU_ATTENTION_API_H */