← Back to C-Kernel-Engine Docs Doxygen Source Documentation
Loading...
Searching...
No Matches
deltanet_chunked_bf16.c
Go to the documentation of this file.
1/*
2 * Chunked BF16 gated DeltaNet with a persistent FP32 recurrent state.
3 * The provider uses 64-token temporal blocks and FP32 BLAS products.
4 */
5#ifndef _GNU_SOURCE
6#define _GNU_SOURCE
7#endif
8
9#include "bf16_utils.h"
10#include "ckernel_engine.h"
11
12#include <dlfcn.h>
13#include <math.h>
14#include <pthread.h>
15#include <stdbool.h>
16#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19
20#if defined(__clang__)
21#pragma clang fp contract(off)
22#elif defined(__GNUC__)
23#pragma GCC optimize("fp-contract=off")
24#endif
25
26enum { CHUNK = 64, HEAD_WIDTH = 128, MATRIX = CHUNK * HEAD_WIDTH };
28
29typedef struct {
30 float query[MATRIX], key[MATRIX], value_beta[MATRIX], key_beta[MATRIX];
31 float weighted_key[MATRIX], decay[TEMPORAL], decay_input[TEMPORAL];
32 float transform[TEMPORAL], value[MATRIX], cumulative_key[MATRIX];
33 float weighted_query[MATRIX], value_new[MATRIX], previous_value[MATRIX];
34 float history[MATRIX], query_key[TEMPORAL], local[MATRIX];
35 float final_key[MATRIX], update[STATE];
36 float cumulative_gate[CHUNK], gate_exp[CHUNK], final_delta[CHUNK], final_exp[CHUNK];
37} chunk_workspace;
38
39_Static_assert(sizeof(chunk_workspace) == 558080, "DeltaNet map workspace size");
40
41typedef void (*sgemm_fn)(
42 const char *, const char *, const int *, const int *, const int *,
43 const float *, const float *, const int *, const float *, const int *,
44 const float *, float *, const int *);
45typedef void (*strsm_fn)(const char *, const char *, const char *, const char *,
46 const int *, const int *, const float *, const float *, const int *,
47 float *, const int *);
48typedef void (*vsexp_fn)(int, const float *, float *);
49
50static pthread_once_t bind_once = PTHREAD_ONCE_INIT;
54
60
61static void bind_math(void)
62{
63 const char *library = getenv("CK_MKL_LIBRARY");
64 void *handle = library && *library ? dlopen(library, RTLD_NOW | RTLD_LOCAL) : RTLD_DEFAULT;
65 if (!handle && library && *library)
66 return;
67 sgemm = (sgemm_fn)dlsym(handle, "sgemm_");
68 strsm = (strsm_fn)dlsym(handle, "strsm_");
69 vsexp = (vsexp_fn)dlsym(handle, "vsExp");
70}
71
72static void matmul(int rows, int columns, int depth, const float *a, const float *b,
73 int transpose_a, int transpose_b, float *c)
74{
75 const char ta = transpose_a ? 'T' : 'N';
76 const char tb = transpose_b ? 'T' : 'N';
77 const int lda = transpose_a ? rows : depth;
78 const int ldb = transpose_b ? depth : columns;
79 const float one = 1.0f, zero = 0.0f;
80 /* Fortran BLAS uses column-major storage. Exchange operands and axes. */
81 sgemm(&tb, &ta, &columns, &rows, &depth, &one, b, &ldb, a, &lda,
82 &zero, c, &columns);
83}
84
85static float bf16_round(float x)
86{
88}
89
90static float reduce_previous_rows(const float *matrix, int row, int column)
91{
92 const float *coefficients = matrix + row * CHUNK;
93 if ((row < 8 && column < (row / 4) * 4) || (row >= 32 && column < 32)) {
94 float blocks = 0.0f, sum = 0.0f;
95 for (int i = 0; i < row; ++i) {
96 if (i > column)
97 sum += coefficients[i] * matrix[i * CHUNK + column];
98 if (i % 16 == 15) {
99 blocks += sum;
100 sum = 0.0f;
101 }
102 }
103 return sum + blocks;
104 }
105
106 /* CPU outer sum uses four interleaved accumulators for the remaining columns. */
107 float partials[4] = {0};
108 const int complete = (row / 4) * 4;
109 for (int i = column + 1; i < complete; ++i)
110 partials[i % 4] += coefficients[i] * matrix[i * CHUNK + column];
111 for (int i = complete > column ? complete : column + 1; i < row; ++i)
112 partials[0] += coefficients[i] * matrix[i * CHUNK + column];
113 return ((partials[0] + partials[1]) + partials[2]) + partials[3];
114}
115
116static void temporal_transform(chunk_workspace *w, bool inverse)
117{
118 vsexp(CHUNK, w->cumulative_gate, w->gate_exp);
119 for (int row = 0; row < CHUNK; ++row) {
120 w->final_delta[row] = w->cumulative_gate[CHUNK - 1] - w->cumulative_gate[row];
121 for (int column = 0; column < CHUNK; ++column)
122 w->decay_input[row * CHUNK + column] = column <= row
123 ? w->cumulative_gate[row] - w->cumulative_gate[column] : 0.0f;
124 }
125 vsexp(TEMPORAL, w->decay_input, w->decay);
126 vsexp(CHUNK, w->final_delta, w->final_exp);
127 matmul(CHUNK, CHUNK, HEAD_WIDTH, w->key_beta, w->key, 0, 1, w->transform);
128
129 for (int row = 0; row < CHUNK; ++row) {
130 for (int column = 0; column < CHUNK; ++column) {
131 const int offset = row * CHUNK + column;
132 if (column > row)
133 w->decay[offset] = 0.0f;
134 float value = inverse ? -w->transform[offset] : w->transform[offset];
135 w->transform[offset] = column < row ? value * w->decay[offset] : 0.0f;
136 }
137 }
138 if (!inverse)
139 return;
140 /* Updating columns left to right keeps each row coefficient needed for
141 later columns intact until its final use. */
142 for (int row = 1; row < CHUNK; ++row)
143 for (int column = 0; column < row; ++column)
144 w->transform[row * CHUNK + column] += reduce_previous_rows(w->transform, row, column);
145 for (int row = 0; row < CHUNK; ++row)
146 w->transform[row * CHUNK + row] = 1.0f;
147}
148
149static void solve_lower_unit(const float *matrix, const float *rhs, float *result)
150{
151 const char side = 'R', upper = 'U', trans = 'N', unit = 'U';
152 const int width = HEAD_WIDTH, rows = CHUNK;
153 const float one = 1.0f;
154 memcpy(result, rhs, MATRIX * sizeof(float));
155 /* Row-major LX = B is the column-major right-side solve X^T L^T = B^T. */
156 strsm(&side, &upper, &trans, &unit, &width, &rows, &one, matrix, &rows,
157 result, &width);
158}
159
160static void apply_chunk(chunk_workspace *w, float *state, bool solve)
161{
162 temporal_transform(w, !solve);
163 for (int row = 0; row < CHUNK; ++row) {
164 for (int d = 0; d < HEAD_WIDTH; ++d) {
165 const int at = row * HEAD_WIDTH + d;
166 w->weighted_key[at] = w->key_beta[at] * w->gate_exp[row];
167 w->weighted_query[at] = w->query[at] * w->gate_exp[row];
168 w->final_key[at] = w->key[at] * w->final_exp[row];
169 }
170 }
171 if (solve) {
172 solve_lower_unit(w->transform, w->value_beta, w->value);
173 solve_lower_unit(w->transform, w->weighted_key, w->cumulative_key);
174 } else {
175 matmul(CHUNK, HEAD_WIDTH, CHUNK, w->transform, w->value_beta, 0, 0, w->value);
176 matmul(CHUNK, HEAD_WIDTH, CHUNK, w->transform, w->weighted_key, 0, 0, w->cumulative_key);
177 }
178 matmul(CHUNK, HEAD_WIDTH, HEAD_WIDTH, w->cumulative_key, state, 0, 0, w->previous_value);
179 for (int i = 0; i < MATRIX; ++i)
180 w->value_new[i] = w->value[i] - w->previous_value[i];
181
182 matmul(CHUNK, HEAD_WIDTH, HEAD_WIDTH, w->weighted_query, state, 0, 0, w->history);
183 matmul(CHUNK, CHUNK, HEAD_WIDTH, w->query, w->key, 0, 1, w->query_key);
184 for (int i = 0; i < TEMPORAL; ++i)
185 w->query_key[i] *= w->decay[i];
186 matmul(CHUNK, HEAD_WIDTH, CHUNK, w->query_key, w->value_new, 0, 0, w->local);
187
188 matmul(HEAD_WIDTH, HEAD_WIDTH, CHUNK, w->final_key, w->value_new, 1, 0, w->update);
189 for (int i = 0; i < STATE; ++i)
190 state[i] = state[i] * w->gate_exp[CHUNK - 1] + w->update[i];
191}
192
194 const float *q, const float *k, const float *v, const float *packed_qkv,
195 const float *g, const float *beta, const float *state_in, float *state_out,
196 float *out, void *workspace, int rows, int heads, int groups, int width, float eps,
197 chunk_profile profile)
198{
199 const bool bf16_qk = profile == BF16_QK_BETA_INVERSE;
200 const bool bf16_beta = profile != FP32_QK_BETA_INVERSE;
201 const bool solve = profile == FP32_QK_BF16_BETA_SOLVE;
202 pthread_once(&bind_once, bind_math);
203 if (!sgemm || !vsexp || !q || !k || !v || !g || !beta ||
204 (solve && !strsm) || (bf16_qk && !packed_qkv) ||
205 !state_in || !state_out || !out || !workspace || rows < 1 || heads < 1 ||
206 groups < 1 || heads % groups || width != HEAD_WIDTH) {
207 fprintf(stderr, "HARD KERNEL CONTRACT FAULT: chunked DeltaNet requires MKL sgemm_ and vsExp, strsm_ for the triangular profile, 128-wide heads and valid buffers\n");
208 abort();
209 }
210
211 chunk_workspace *w = workspace;
212 const int repeat = heads / groups;
213 const size_t compact_row = (size_t)groups * HEAD_WIDTH;
214 const size_t value_row = (size_t)heads * HEAD_WIDTH;
215 const size_t packed_row = 2 * compact_row + value_row;
216 const size_t vector_limit = (size_t)rows * heads / 32 * 32;
217 const size_t boundary_row = vector_limit / heads;
218 const int boundary_head = (int)(vector_limit % heads);
219 const int boundary_group = boundary_head / repeat;
220 const int mixed_group = bf16_qk ? boundary_head % repeat : 0;
221 const float scale = (float)(1.0 / sqrt((double)HEAD_WIDTH));
222 float scalar_q[HEAD_WIDTH], scalar_k[HEAD_WIDTH];
223 if (mixed_group) {
224 const float *raw = packed_qkv + boundary_row * packed_row + (size_t)boundary_group * HEAD_WIDTH;
225 memcpy(scalar_q, raw, sizeof(scalar_q));
226 memcpy(scalar_k, raw + compact_row, sizeof(scalar_k));
227 /* The repeated group can straddle the vector end of BF16 rsqrt. */
229 scalar_q, scalar_k, 1, HEAD_WIDTH, HEAD_WIDTH, 1, HEAD_WIDTH, eps);
230 }
231
232 for (int head = 0; head < heads; ++head) {
233 const int group = head / repeat;
234 const size_t compact_offset = (size_t)group * HEAD_WIDTH;
235 const size_t head_offset = (size_t)head * HEAD_WIDTH;
236 const float *initial = state_in + (size_t)head * STATE;
237 float *state = state_out + (size_t)head * STATE;
238 if (state != initial)
239 memcpy(state, initial, STATE * sizeof(float));
240 for (int start = 0; start < rows;) {
241 const int valid = rows - start < CHUNK ? rows - start : CHUNK;
242 double cumulative = 0.0;
243 for (int row = 0; row < CHUNK; ++row) {
244 const size_t token = (size_t)start + row;
245 const int present = row < valid;
246 const size_t gate_index = token * heads + head;
247 if (present)
248 cumulative += g[gate_index];
249 w->cumulative_gate[row] = (float)cumulative;
250 float factor = present ? 1.0f / (1.0f + expf(-beta[gate_index])) : 0.0f;
251 if (bf16_beta)
252 factor = bf16_round(factor);
253 const int scalar = mixed_group && token == boundary_row &&
254 group == boundary_group && head >= boundary_head;
255 for (int d = 0; d < HEAD_WIDTH; ++d) {
256 const int at = row * HEAD_WIDTH + d;
257 const size_t compact = token * compact_row + compact_offset + d;
258 const size_t expanded = token * value_row + head_offset + d;
259 w->query[at] = present ? (scalar ? scalar_q[d] : q[compact]) * scale : 0.0f;
260 w->key[at] = present ? (scalar ? scalar_k[d] : k[compact]) : 0.0f;
261 w->value_beta[at] = present ? v[expanded] * factor : 0.0f;
262 w->key_beta[at] = w->key[at] * factor;
263 }
264 }
265 apply_chunk(w, state, solve);
266 for (int row = 0; row < valid; ++row) {
267 float *destination = out + ((size_t)start + row) * value_row + head_offset;
268 for (int d = 0; d < HEAD_WIDTH; ++d) {
269 const int at = row * HEAD_WIDTH + d;
270 destination[d] = bf16_round(w->history[at] + w->local[at]);
271 }
272 }
273 start += valid;
274 }
275 }
276}
277
279 const float *q, const float *k, const float *v, const float *packed_qkv,
280 const float *g, const float *beta, const float *state_in, float *state_out,
281 float *out, void *workspace, int rows, int heads, int groups, int width, float eps)
282{
283 gated_deltanet_chunked_prefill(q, k, v, packed_qkv, g, beta, state_in, state_out,
284 out, workspace, rows, heads, groups, width, eps, BF16_QK_BETA_INVERSE);
285}
286
288 const float *q, const float *k, const float *v, const float *g, const float *beta,
289 const float *state_in, float *state_out, float *out, void *workspace,
290 int rows, int heads, int groups, int width)
291{
292 gated_deltanet_chunked_prefill(q, k, v, NULL, g, beta, state_in, state_out,
293 out, workspace, rows, heads, groups, width, 0.0f, FP32_QK_BETA_INVERSE);
294}
295
297 const float *q, const float *k, const float *v, const float *g, const float *beta,
298 const float *state_in, float *state_out, float *out, void *workspace,
299 int rows, int heads, int groups, int width)
300{
301 gated_deltanet_chunked_prefill(q, k, v, NULL, g, beta, state_in, state_out,
302 out, workspace, rows, heads, groups, width, 0.0f, FP32_QK_BF16_BETA_SOLVE);
303}
#define RTLD_DEFAULT
static uint16_t float_to_bf16(float f)
Definition bf16_utils.h:90
static float bf16_to_float(uint16_t v)
Definition bf16_utils.h:38
void recurrent_qk_l2_norm_pytorch_bf16_storage(float *q, float *k, int rows, int q_dim, int k_dim, int expanded_heads, int head_dim, float eps)
static float reduce_previous_rows(const float *matrix, int row, int column)
static strsm_fn strsm
static vsexp_fn vsexp
void(* sgemm_fn)(const char *, const char *, const int *, const int *, const int *, const float *, const float *, const int *, const float *, const int *, const float *, float *, const int *)
static void temporal_transform(chunk_workspace *w, bool inverse)
static void apply_chunk(chunk_workspace *w, float *state, bool solve)
static void solve_lower_unit(const float *matrix, const float *rhs, float *result)
void(* strsm_fn)(const char *, const char *, const char *, const char *, const int *, const int *, const float *, const float *, const int *, float *, const int *)
static void matmul(int rows, int columns, int depth, const float *a, const float *b, int transpose_a, int transpose_b, float *c)
static sgemm_fn sgemm
void gated_deltanet_chunked_bf16_prefill_forward(const float *q, const float *k, const float *v, const float *packed_qkv, const float *g, const float *beta, const float *state_in, float *state_out, float *out, void *workspace, int rows, int heads, int groups, int width, float eps)
static void bind_math(void)
static pthread_once_t bind_once
@ FP32_QK_BETA_INVERSE
@ BF16_QK_BETA_INVERSE
@ FP32_QK_BF16_BETA_SOLVE
void gated_deltanet_chunked_fp32_qk_beta_prefill_forward(const float *q, const float *k, const float *v, const float *g, const float *beta, const float *state_in, float *state_out, float *out, void *workspace, int rows, int heads, int groups, int width)
void(* vsexp_fn)(int, const float *, float *)
static void gated_deltanet_chunked_prefill(const float *q, const float *k, const float *v, const float *packed_qkv, const float *g, const float *beta, const float *state_in, float *state_out, float *out, void *workspace, int rows, int heads, int groups, int width, float eps, chunk_profile profile)
void gated_deltanet_chunked_fp32_qk_triangular_prefill_forward(const float *q, const float *k, const float *v, const float *g, const float *beta, const float *state_in, float *state_out, float *out, void *workspace, int rows, int heads, int groups, int width)
static float bf16_round(float x)
static int valid(const uint16_t *p, size_t elements)
const char * token
Definition tokenizer.h:308
uint32_t start
Definition utf8.c:214