← Back to C-Kernel-Engine Docs Doxygen Source Documentation
Loading...
Searching...
No Matches
linear_rows_bf16_checked.c
Go to the documentation of this file.
1#ifndef _GNU_SOURCE
2#define _GNU_SOURCE
3#endif
4
5#include <dlfcn.h>
6#include <limits.h>
7#include <pthread.h>
8#include <stdlib.h>
9#include <string.h>
10#include <math.h>
11#include <stddef.h>
12#include <stdint.h>
13#include <stdatomic.h>
14
15#include "bf16_utils.h"
16#include "checked_parallel.h"
17
18#if defined(__x86_64__) && (defined(__GNUC__) || defined(__clang__))
19#include <immintrin.h>
20#define CK_ORDERED_AVX2 __attribute__((target("avx2,fma")))
21#endif
22
23static int region_valid(const uint16_t *ptr, size_t elements)
24{
25 return ptr && (uintptr_t)ptr % _Alignof(uint16_t) == 0 &&
26 elements <= SIZE_MAX / sizeof(uint16_t) &&
27 (uintptr_t)ptr <= UINTPTR_MAX - elements * sizeof(uint16_t);
28}
29
30static int overlap(const uint16_t *a, size_t a_count,
31 const uint16_t *b, size_t b_count)
32{
33 return (uintptr_t)a < (uintptr_t)b + b_count * sizeof(uint16_t) &&
34 (uintptr_t)b < (uintptr_t)a + a_count * sizeof(uint16_t);
35}
36
37struct ordered_projection {
38 const uint16_t *input, *weight, *bias;
39 const double *wide_row;
40 uint16_t *stage;
41 size_t rows, input_width, output_width;
42 int avx2;
43 atomic_int failed;
44};
45
46static int stage_ordered_row(struct ordered_projection *p, size_t row, size_t start,
47 size_t lanes, const double *sums)
48{
49 for (size_t j = 0; j < lanes; ++j) {
50 double sum = sums[j];
51 if (p->bias) sum += bf16_to_float(p->bias[start + j]);
52 const uint16_t value = float_to_bf16((float)sum);
53 if ((value & 0x7f80u) == 0x7f80u) {
54 atomic_store_explicit(&p->failed, 1, memory_order_relaxed);
55 return -1;
56 }
57 p->stage[row * p->output_width + start + j] = value;
58 }
59 return 0;
60}
61
62#ifdef CK_ORDERED_AVX2
63static CK_ORDERED_AVX2 __m256d ordered_bf16x4(__m128i x)
64{
65 return _mm256_cvtps_pd(_mm_castsi128_ps(_mm_slli_epi32(_mm_cvtepu16_epi32(x),16)));
66}
67
68static CK_ORDERED_AVX2 int ordered_weights_finite(const uint16_t *w, size_t n)
69{
70 const __m256i exp = _mm256_set1_epi16(0x7f80);
71 size_t i = 0;
72 for (; n-i >= 16; i += 16) {
73 const __m256i value = _mm256_loadu_si256((const __m256i *)(w+i));
74 if (_mm256_movemask_epi8(_mm256_cmpeq_epi16(_mm256_and_si256(value,exp),exp)))
75 return 0;
76 }
77 for (; i < n; ++i)
78 if ((w[i] & 0x7f80u) == 0x7f80u)
79 return 0;
80 return 1;
81}
82
83// Transpose four adjacent K values so each FP64 lane owns one output.
84static inline CK_ORDERED_AVX2 __attribute__((always_inline))
85int ordered_cols(const uint16_t *w, size_t k_count, __m256d lanes[4], int check)
86{
87 const __m128i w0 = _mm_loadl_epi64((const __m128i *)w);
88 const __m128i w1 = _mm_loadl_epi64((const __m128i *)(w+k_count));
89 const __m128i w2 = _mm_loadl_epi64((const __m128i *)(w+2*k_count));
90 const __m128i w3 = _mm_loadl_epi64((const __m128i *)(w+3*k_count));
91 const __m128i ab = _mm_unpacklo_epi16(w0,w1), cd = _mm_unpacklo_epi16(w2,w3);
92 if (check) {
93 const __m128i exp = _mm_set1_epi16(0x7f80);
94 const __m128i bad_ab = _mm_cmpeq_epi16(_mm_and_si128(ab,exp),exp);
95 const __m128i bad_cd = _mm_cmpeq_epi16(_mm_and_si128(cd,exp),exp);
96 if (_mm_movemask_epi8(_mm_or_si128(bad_ab,bad_cd)))
97 return 0;
98 }
99 const __m128i lo = _mm_unpacklo_epi32(ab,cd), hi = _mm_unpackhi_epi32(ab,cd);
100 lanes[0] = ordered_bf16x4(lo);
101 lanes[1] = ordered_bf16x4(_mm_srli_si128(lo,8));
102 lanes[2] = ordered_bf16x4(hi);
103 lanes[3] = ordered_bf16x4(_mm_srli_si128(hi,8));
104 return 1;
105}
106
107static inline CK_ORDERED_AVX2 __attribute__((always_inline))
108int store_avx2_row(const struct ordered_projection *p, size_t start, size_t row, __m256d sum)
109{
110 double sums[4];
111 _mm256_storeu_pd(sums,sum);
112 for (size_t j = 0; j < 4; ++j) {
113 const double value = sums[j] + (p->bias ? bf16_to_float(p->bias[start+j]) : 0.0);
114 const uint16_t out = float_to_bf16((float)value);
115 if ((out & 0x7f80u) == 0x7f80u)
116 return 0;
117 p->stage[row*p->output_width+start+j] = out;
118 }
119 return 1;
120}
121
122static inline CK_ORDERED_AVX2 __attribute__((always_inline))
123int project_avx2_rows(const struct ordered_projection *p, size_t start, size_t row, size_t rows)
124{
125 const size_t k_count = p->input_width;
126 const uint16_t *w = p->weight + start*k_count;
127 const uint16_t *x = p->input+row*k_count;
128 __m256d acc[8];
129 for (size_t r = 0; r < rows; ++r)
130 acc[r] = _mm256_setzero_pd();
131 size_t k = 0;
132 for (; k_count-k >= 4; k += 4) {
133 __m256d lanes[4];
134 ordered_cols(w+k,k_count,lanes,0);
135 // BF16 products are exactly representable in FP64, including subnormals.
136 for (size_t i = 0; i < 4; ++i)
137 for (size_t r = 0; r < rows; ++r)
138 acc[r] = _mm256_fmadd_pd(_mm256_set1_pd(bf16_to_float(x[r*k_count+k+i])),lanes[i],acc[r]);
139 }
140 for (; k < k_count; ++k) {
141 const __m256d lanes = _mm256_set_pd(bf16_to_float(w[3*k_count+k]),bf16_to_float(w[2*k_count+k]),
142 bf16_to_float(w[k_count+k]),bf16_to_float(w[k]));
143 for (size_t r = 0; r < rows; ++r)
144 acc[r] = _mm256_fmadd_pd(_mm256_set1_pd(bf16_to_float(x[r*k_count+k])),lanes,acc[r]);
145 }
146 for (size_t r = 0; r < rows; ++r)
147 if (!store_avx2_row(p,start,row+r,acc[r]))
148 return 0;
149 return 1;
150}
151
152static CK_ORDERED_AVX2 int project_four_avx2(const struct ordered_projection *p, size_t start)
153{
154 const size_t k_count = p->input_width;
155 if (!ordered_weights_finite(p->weight+start*k_count,4*k_count))
156 return 0;
157 size_t row = 0;
158 for (; p->rows-row >= 8; row += 8)
159 if (!project_avx2_rows(p,start,row,8))
160 return 0;
161 for (; p->rows-row >= 4; row += 4)
162 if (!project_avx2_rows(p,start,row,4))
163 return 0;
164 if (p->rows-row >= 2) {
165 if (!project_avx2_rows(p,start,row,2))
166 return 0;
167 row += 2;
168 }
169 return row == p->rows || project_avx2_rows(p,start,row,1);
170}
171
172static inline CK_ORDERED_AVX2 __attribute__((always_inline))
173int project_avx2_single_pair(const struct ordered_projection *p, size_t start, int widened)
174{
175 const size_t k_count = p->input_width;
176 const uint16_t *w = p->weight + start*k_count, *z = w+4*k_count;
177 __m256d a = _mm256_setzero_pd(), b = a;
178 size_t k = 0;
179 for (; k_count-k >= 4; k += 4) {
180 __m256d lo[4], hi[4];
181 if (!ordered_cols(w+k,k_count,lo,1) || !ordered_cols(z+k,k_count,hi,1))
182 return 0;
183 for (size_t i = 0; i < 4; ++i) {
184 const __m256d x = _mm256_set1_pd(widened ? p->wide_row[k+i] : bf16_to_float(p->input[k+i]));
185 a = _mm256_fmadd_pd(x,lo[i],a);
186 b = _mm256_fmadd_pd(x,hi[i],b);
187 }
188 }
189 for (; k < k_count; ++k) {
190 for (size_t j = 0; j < 8; ++j)
191 if ((w[j*k_count+k] & 0x7f80u) == 0x7f80u)
192 return 0;
193 const __m256d x = _mm256_set1_pd(widened ? p->wide_row[k] : bf16_to_float(p->input[k]));
194 const __m256d lo = _mm256_set_pd(bf16_to_float(w[3*k_count+k]),bf16_to_float(w[2*k_count+k]),
195 bf16_to_float(w[k_count+k]),bf16_to_float(w[k]));
196 const __m256d hi = _mm256_set_pd(bf16_to_float(z[3*k_count+k]),bf16_to_float(z[2*k_count+k]),
197 bf16_to_float(z[k_count+k]),bf16_to_float(z[k]));
198 a = _mm256_fmadd_pd(x,lo,a);
199 b = _mm256_fmadd_pd(x,hi,b);
200 }
201 return store_avx2_row(p,start,0,a) && store_avx2_row(p,start+4,0,b);
202}
203#endif
204
205static void project_ordered_tiles(size_t begin, size_t end, void *opaque)
206{
207 struct ordered_projection *p = opaque;
208 const size_t k_count = p->input_width, n = p->output_width;
209 for (size_t tile = begin; tile < end; ++tile) {
210 const size_t start = tile * 4;
211 const size_t lanes = n - start >= 4 ? 4 : n - start;
212 const uint16_t *w = p->weight + start * k_count;
213#ifdef CK_ORDERED_AVX2
214 if (p->avx2 && lanes == 4) {
215 if (!project_four_avx2(p,start)) {
216 atomic_store_explicit(&p->failed, 1, memory_order_relaxed);
217 return;
218 }
219 continue;
220 }
221#endif
222 for (size_t i = 0; i < lanes * k_count; ++i)
223 if ((w[i] & 0x7f80u) == 0x7f80u) {
224 atomic_store_explicit(&p->failed, 1, memory_order_relaxed);
225 return;
226 }
227 size_t row = 0;
228 if (lanes == 4) {
229 for (; row + 1 < p->rows; row += 2) {
230 const uint16_t *first = p->input + row * k_count;
231 const uint16_t *second = first + k_count;
232 double first_sums[4] = {0}, second_sums[4] = {0};
233 // Reuse decoded weights across two rows while preserving ascending K order.
234 for (size_t k = 0; k < k_count; ++k) {
235 const double a = bf16_to_float(first[k]);
236 const double b = bf16_to_float(second[k]);
237 for (size_t j = 0; j < 4; ++j) {
238 const double weight = bf16_to_float(w[j * k_count + k]);
239 first_sums[j] += a * weight;
240 second_sums[j] += b * weight;
241 }
242 }
243 if (stage_ordered_row(p, row, start, 4, first_sums) ||
244 stage_ordered_row(p, row + 1, start, 4, second_sums)) return;
245 }
246 }
247 for (; row < p->rows; ++row) {
248 const uint16_t *x = p->input + row * k_count;
249 double sums[4] = {0};
250 if (lanes == 4) {
251 // Products are exact in FP64. Each lane still accumulates in ascending K order.
252 for (size_t k = 0; k < k_count; ++k) {
253 const double value = bf16_to_float(x[k]);
254 for (size_t j = 0; j < 4; ++j)
255 sums[j] += value * (double)bf16_to_float(w[j * k_count + k]);
256 }
257 } else {
258 for (size_t j = 0; j < lanes; ++j)
259 for (size_t k = 0; k < k_count; ++k)
260 sums[j] += (double)bf16_to_float(x[k]) * bf16_to_float(w[j * k_count + k]);
261 }
262 if (stage_ordered_row(p, row, start, lanes, sums)) return;
263 }
264 }
265}
266
267#ifdef CK_ORDERED_AVX2
268enum { ORDERED_PANEL_N = 16, ORDERED_PANEL_K = 128, ORDERED_PANEL_M = 64 };
269
270/* Vector lanes own distinct outputs. Each output keeps its ascending K chain. */
271static __attribute__((target("avx512f")))
272void project_avx512_panel_rows(const uint16_t *input, size_t k_count, size_t rows, size_t ks,
273 double packed[][ORDERED_PANEL_N], double sums[][ORDERED_PANEL_N])
274{
275 size_t r = 0;
276 for (; rows - r >= 4; r += 4) {
277 __m512d lo[4], hi[4];
278 for (size_t i = 0; i < 4; ++i) {
279 lo[i] = _mm512_loadu_pd(sums[r + i]);
280 hi[i] = _mm512_loadu_pd(sums[r + i] + 8);
281 }
282 for (size_t k = 0; k < ks; ++k) {
283 const __m512d low_weights = _mm512_loadu_pd(packed[k]);
284 const __m512d high_weights = _mm512_loadu_pd(packed[k] + 8);
285 for (size_t i = 0; i < 4; ++i) {
286 const __m512d x = _mm512_set1_pd(bf16_to_float(input[(r + i) * k_count + k]));
287 lo[i] = _mm512_fmadd_pd(x, low_weights, lo[i]);
288 hi[i] = _mm512_fmadd_pd(x, high_weights, hi[i]);
289 }
290 }
291 for (size_t i = 0; i < 4; ++i) {
292 _mm512_storeu_pd(sums[r + i], lo[i]);
293 _mm512_storeu_pd(sums[r + i] + 8, hi[i]);
294 }
295 }
296 for (; r < rows; ++r) {
297 __m512d lo = _mm512_loadu_pd(sums[r]);
298 __m512d hi = _mm512_loadu_pd(sums[r] + 8);
299 for (size_t k = 0; k < ks; ++k) {
300 const __m512d x = _mm512_set1_pd(bf16_to_float(input[r * k_count + k]));
301 lo = _mm512_fmadd_pd(x, _mm512_loadu_pd(packed[k]), lo);
302 hi = _mm512_fmadd_pd(x, _mm512_loadu_pd(packed[k] + 8), hi);
303 }
304 _mm512_storeu_pd(sums[r], lo);
305 _mm512_storeu_pd(sums[r] + 8, hi);
306 }
307}
308
309static CK_ORDERED_AVX2 int project_avx2_panel(const struct ordered_projection *p, size_t start)
310{
311 const size_t k_count = p->input_width;
312 const uint16_t *w = p->weight + start*k_count;
313 if (!ordered_weights_finite(w, ORDERED_PANEL_N*k_count))
314 return 0;
315 const int use_avx512 = __builtin_cpu_supports("avx512f");
316 double packed[ORDERED_PANEL_K][ORDERED_PANEL_N];
317 double sums[ORDERED_PANEL_M][ORDERED_PANEL_N];
318 for (size_t row = 0; row < p->rows; row += ORDERED_PANEL_M) {
319 const size_t rows = p->rows-row < ORDERED_PANEL_M ? p->rows-row : ORDERED_PANEL_M;
320 memset(sums, 0, rows*sizeof(*sums));
321 // Bound storage per worker while reusing converted weights across the row block.
322 for (size_t base = 0; base < k_count; base += ORDERED_PANEL_K) {
323 const size_t ks = k_count-base < ORDERED_PANEL_K ? k_count-base : ORDERED_PANEL_K;
324 size_t k = 0;
325 for (; ks-k >= 4; k += 4)
326 for (size_t g = 0; g < 4; ++g) {
327 __m256d cols[4];
328 ordered_cols(w+g*4*k_count+base+k,k_count,cols,0);
329 for (size_t t = 0; t < 4; ++t)
330 _mm256_storeu_pd(packed[k+t]+g*4,cols[t]);
331 }
332 for (; k < ks; ++k)
333 for (size_t j = 0; j < ORDERED_PANEL_N; ++j)
334 packed[k][j] = bf16_to_float(w[j*k_count+base+k]);
335 if (use_avx512) {
336 project_avx512_panel_rows(p->input + row * k_count + base, k_count, rows, ks, packed, sums);
337 continue;
338 }
339 for (size_t r = 0; r < rows; r += 2) {
340 const int second = r+1 < rows;
341 const uint16_t *x = p->input+(row+r)*k_count+base;
342 const uint16_t *y = second ? x+k_count : x;
343 __m256d a[4], b[4];
344 for (size_t j = 0; j < 4; ++j) {
345 a[j] = _mm256_loadu_pd(sums[r]+j*4);
346 b[j] = _mm256_loadu_pd(sums[r+(size_t)second]+j*4);
347 }
348 for (size_t t = 0; t < ks; ++t) {
349 const __m256d xv = _mm256_set1_pd(bf16_to_float(x[t]));
350 const __m256d yv = _mm256_set1_pd(bf16_to_float(y[t]));
351 for (size_t j = 0; j < 4; ++j) {
352 const __m256d v = _mm256_loadu_pd(packed[t]+j*4);
353 a[j] = _mm256_fmadd_pd(xv,v,a[j]);
354 b[j] = _mm256_fmadd_pd(yv,v,b[j]);
355 }
356 }
357 for (size_t j = 0; j < 4; ++j) {
358 _mm256_storeu_pd(sums[r]+j*4,a[j]);
359 if (second) _mm256_storeu_pd(sums[r+1]+j*4,b[j]);
360 }
361 }
362 }
363 for (size_t r = 0; r < rows; ++r)
364 for (size_t j = 0; j < 4; ++j)
365 if (!store_avx2_row(p,start+j*4,row+r,_mm256_loadu_pd(sums[r]+j*4)))
366 return 0;
367 }
368 return 1;
369}
370
371static void project_avx2_panels(size_t begin, size_t end, void *opaque)
372{
373 struct ordered_projection *p = opaque;
374 for (size_t tile = begin; tile < end; ++tile) {
375 const size_t start = tile*ORDERED_PANEL_N;
376 if (p->output_width-start < ORDERED_PANEL_N) {
377 project_ordered_tiles(start/4,(p->output_width-1)/4+1,p);
378 } else if (!project_avx2_panel(p,start)) {
379 atomic_store_explicit(&p->failed,1,memory_order_relaxed);
380 return;
381 }
382 }
383}
384
385static CK_ORDERED_AVX2 void project_avx2_single_pairs(size_t begin, size_t end, void *opaque)
386{
387 struct ordered_projection *p = opaque;
388 for (size_t tile = begin; tile < end; ++tile) {
389 if (p->output_width-tile*8 < 8) {
390 project_ordered_tiles(tile*2,(p->output_width-1)/4+1,p);
391 } else if (!(p->wide_row ? project_avx2_single_pair(p,tile*8,1)
392 : project_avx2_single_pair(p,tile*8,0))) {
393 atomic_store_explicit(&p->failed,1,memory_order_relaxed);
394 return;
395 }
396 }
397}
398
399enum { ORDERED_WIDE_ROW_MAX = 2048 };
400
401/* Share the exact BF16-to-FP64 expansion across all synchronous output jobs. */
402static CK_ORDERED_AVX2 void project_avx2_widened_row(struct ordered_projection *p, size_t tiles, int grain)
403{
404 double wide_row[ORDERED_WIDE_ROW_MAX];
405 for (size_t k = 0; k < p->input_width; ++k)
406 wide_row[k] = bf16_to_float(p->input[k]);
407 p->wide_row = wide_row;
408 ck_checked_parallel_for(tiles, grain, project_avx2_single_pairs, p);
409 p->wide_row = NULL;
410}
411#endif
412
413/* Ascending FP64 reduction, narrowed through FP32 to BF16 RNE on publication. */
415 const uint16_t *input, size_t input_elements,
416 const uint16_t *weight, size_t weight_elements,
417 const uint16_t *bias, size_t bias_elements,
418 uint16_t *output, size_t output_elements,
419 uint16_t *staged, size_t staged_elements,
420 size_t rows, size_t input_width, size_t output_width)
421{
422 if (!rows || !input_width || !output_width ||
423 rows > SIZE_MAX / input_width || output_width > SIZE_MAX / input_width ||
424 rows > SIZE_MAX / output_width) return -2;
425 const size_t in_count = rows * input_width;
426 const size_t w_count = output_width * input_width;
427 const size_t out_count = rows * output_width;
428 if (input_elements < in_count || weight_elements < w_count ||
429 output_elements < out_count || staged_elements < out_count ||
430 (bias && bias_elements < output_width)) return -2;
431 if (!region_valid(input, input_elements) || !region_valid(weight, weight_elements) ||
432 !region_valid(output, output_elements) || !region_valid(staged, staged_elements) ||
433 overlap(output, output_elements, input, input_elements) ||
434 overlap(output, output_elements, weight, weight_elements) ||
435 overlap(output, output_elements, staged, staged_elements) ||
436 overlap(staged, staged_elements, input, input_elements) ||
437 overlap(staged, staged_elements, weight, weight_elements)) return -1;
438 if (bias) {
439 if (!region_valid(bias, bias_elements) ||
440 overlap(output, output_elements, bias, bias_elements) ||
441 overlap(staged, staged_elements, bias, bias_elements)) return -1;
442 for (size_t o = 0; o < output_width; ++o)
443 if (!isfinite(bf16_to_float(bias[o]))) return -1;
444 }
445 for (size_t i = 0; i < in_count; ++i)
446 if (!isfinite(bf16_to_float(input[i]))) return -1;
447 int avx2 = 0;
448#ifdef CK_ORDERED_AVX2
449 avx2 = input_width >= 8 && __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma");
450#endif
451 struct ordered_projection work = {input, weight, bias, NULL, staged, rows, input_width, output_width, avx2, 0};
452 size_t tiles = (output_width - 1) / 4 + 1;
454 int grain = 4;
455#ifdef CK_ORDERED_AVX2
456 if (avx2 && rows == 1 && output_width >= 8) {
457 tiles = (output_width - 1) / 8 + 1;
458 project = project_avx2_single_pairs;
459 grain = 2;
460 } else if (avx2 && rows >= 16 && input_width >= 128 && output_width >= 256) {
461 tiles = (output_width-1)/ORDERED_PANEL_N+1;
462 project = project_avx2_panels;
463 grain = 1;
464 }
465 if (project == project_avx2_single_pairs && w_count >= (1u << 19) &&
466 input_width <= ORDERED_WIDE_ROW_MAX)
467 project_avx2_widened_row(&work, tiles, grain);
468 else
469#endif
470 if (w_count >= (1u << 19))
471 ck_checked_parallel_for(tiles, grain, project, &work);
472 else
473 project(0, tiles, &work);
474 if (atomic_load_explicit(&work.failed, memory_order_relaxed)) return -1;
475 memcpy(output, staged, out_count * sizeof(*output));
476 return 0;
477}
478
480 const uint16_t *input, size_t input_elements,
481 const uint16_t *weight, size_t weight_elements,
482 uint16_t *output, size_t output_elements,
483 uint16_t *staged, size_t staged_elements,
484 size_t rows, size_t input_width, size_t output_width)
485{
486 return linear_rows_bf16_checked(input, input_elements, weight, weight_elements,
487 NULL, 0, output, output_elements, staged, staged_elements,
488 rows, input_width, output_width);
489}
490
492 const uint16_t *input, size_t input_elements,
493 const uint16_t *weight, size_t weight_elements,
494 const uint16_t *bias, size_t bias_elements,
495 uint16_t *output, size_t output_elements,
496 uint16_t *staged, size_t staged_elements,
497 size_t rows, size_t input_width, size_t output_width)
498{
499 if (!bias) return -1;
500 return linear_rows_bf16_checked(input, input_elements, weight, weight_elements,
501 bias, bias_elements, output, output_elements, staged, staged_elements,
502 rows, input_width, output_width);
503}
504
505typedef void (*ck_dgemm_fn)(const char *, const char *, const int *, const int *, const int *,
506 const double *, const double *, const int *, const double *,
507 const int *, const double *, double *, const int *);
508
509static pthread_once_t dgemm_once = PTHREAD_ONCE_INIT;
511
512static void bind_dgemm(void)
513{
514 const char *path = getenv("CK_BLAS_LIBRARY");
515 void *library = path && *path ? dlopen(path, RTLD_NOW | RTLD_LOCAL) : RTLD_DEFAULT;
516 if (path && *path && !library)
517 return;
518 void *symbol = dlsym(library, "dgemm_");
519 _Static_assert(sizeof(symbol) == sizeof(dgemm), "dgemm_ function pointer size");
520 memcpy(&dgemm, &symbol, sizeof(dgemm));
521}
522
524 const uint16_t *input, size_t input_elements, const uint16_t *weight, size_t weight_elements,
525 uint16_t *output, size_t output_elements, uint16_t *staged, size_t staged_elements,
526 double *work, size_t work_elements, size_t rows, size_t input_width, size_t output_width)
527{
528 if (!rows || !input_width || !output_width || rows > INT_MAX ||
529 input_width > INT_MAX || output_width > INT_MAX ||
530 rows > SIZE_MAX / input_width || output_width > SIZE_MAX / input_width ||
531 rows > SIZE_MAX / output_width)
532 return -2;
533 const size_t a = rows * input_width, b = output_width * input_width, c = rows * output_width;
534 if (a > SIZE_MAX - b || a + b > SIZE_MAX - c)
535 return -2;
536 const size_t work_count = a + b + c;
537 if (a > input_elements || b > weight_elements || c > output_elements ||
538 c > staged_elements || work_count > work_elements || !work ||
539 (uintptr_t)work % _Alignof(double) || work_count > SIZE_MAX / sizeof(double))
540 return -2;
541 const size_t work_bits = work_count * (sizeof(double) / sizeof(uint16_t));
542 const uint16_t *work_region = (const uint16_t*)work;
543 if (!region_valid(input, a) || !region_valid(weight, b) ||
544 !region_valid(output, c) || !region_valid(staged, c) ||
545 !region_valid(work_region, work_bits) ||
546 overlap(output, c, input, a) || overlap(output, c, weight, b) ||
547 overlap(staged, c, input, a) || overlap(staged, c, weight, b) ||
548 overlap(output, c, staged, c) ||
549 overlap(work_region, work_bits, input, a) || overlap(work_region, work_bits, weight, b) ||
550 overlap(work_region, work_bits, staged, c) || overlap(work_region, work_bits, output, c))
551 return -1;
552 pthread_once(&dgemm_once, bind_dgemm);
553 if (!dgemm)
554 return -4;
555 double *matrix_a = work, *matrix_b = work + a, *matrix_c = work + a + b;
556 for (size_t i = 0; i < a; ++i) {
557 matrix_a[i] = bf16_to_float(input[i]);
558 if (!isfinite(matrix_a[i]))
559 return -3;
560 }
561 for (size_t i = 0; i < b; ++i) {
562 matrix_b[i] = bf16_to_float(weight[i]);
563 if (!isfinite(matrix_b[i]))
564 return -3;
565 }
566 const char trans = 'T', no_trans = 'N';
567 const int m = (int)rows, n = (int)output_width, k = (int)input_width;
568 const double one = 1.0, zero = 0.0;
569 dgemm(&trans, &no_trans, &n, &m, &k, &one, matrix_b, &k, matrix_a, &k, &zero, matrix_c, &n);
570 for (size_t i = 0; i < c; ++i) {
571 staged[i] = float_to_bf16((float)matrix_c[i]);
572 if (!isfinite(bf16_to_float(staged[i])))
573 return -3;
574 }
575 memcpy(output, staged, c * sizeof(*output));
576 return 0;
577}
578
579typedef void (*ck_bf16_gemm_fn)(int, int, int, int, int, int, float,
580 const uint16_t *, int, const uint16_t *, int, float, float *, int);
581
582static pthread_once_t bf16_gemm_once = PTHREAD_ONCE_INIT;
584
585static void bind_bf16_gemm(void)
586{
587 const char *path = getenv("CK_BLAS_LIBRARY");
588 void *library = path && *path ? dlopen(path, RTLD_NOW | RTLD_LOCAL) : RTLD_DEFAULT;
589 if (path && *path && !library)
590 return;
591 void *symbol = dlsym(library, "cblas_gemm_bf16bf16f32");
592 _Static_assert(sizeof(symbol) == sizeof(bf16_gemm), "CBLAS function pointer size");
593 memcpy(&bf16_gemm, &symbol, sizeof(bf16_gemm));
594}
595
597 const uint16_t *input, size_t input_elements, const uint16_t *weight, size_t weight_elements,
598 uint16_t *output, size_t output_elements, float *work, size_t work_elements,
599 size_t rows, size_t input_width, size_t output_width)
600{
601 if (!rows || !input_width || !output_width || rows > INT_MAX ||
602 input_width > INT_MAX || output_width > INT_MAX ||
603 rows > SIZE_MAX / input_width || output_width > SIZE_MAX / input_width ||
604 rows > SIZE_MAX / output_width)
605 return -2;
606 const size_t a = rows * input_width, b = output_width * input_width, c = rows * output_width;
607 if (a > input_elements || b > weight_elements || c > output_elements || c > work_elements ||
608 !work || (uintptr_t)work % _Alignof(float) || c > SIZE_MAX / sizeof(float))
609 return -2;
610 const uint16_t *work_region = (const uint16_t *)work;
611 const size_t work_bits = c * (sizeof(float) / sizeof(uint16_t));
612 if (!region_valid(input, a) || !region_valid(weight, b) || !region_valid(output, c) ||
613 !region_valid(work_region, work_bits) || overlap(output, c, input, a) ||
614 overlap(output, c, weight, b) || overlap(work_region, work_bits, input, a) ||
615 overlap(work_region, work_bits, weight, b) || overlap(work_region, work_bits, output, c))
616 return -1;
617 for (size_t i = 0; i < a; ++i)
618 if (!isfinite(bf16_to_float(input[i]))) return -3;
619 for (size_t i = 0; i < b; ++i)
620 if (!isfinite(bf16_to_float(weight[i]))) return -3;
621 pthread_once(&bf16_gemm_once, bind_bf16_gemm);
622 if (!bf16_gemm)
623 return -4;
624
625 enum { ROW_MAJOR = 101, NO_TRANSPOSE = 111, TRANSPOSE = 112 };
626 const int m = (int)rows, n = (int)output_width, k = (int)input_width;
627 bf16_gemm(ROW_MAJOR, NO_TRANSPOSE, TRANSPOSE, m, n, k,
628 1.0f, input, k, weight, k, 0.0f, work, n);
629 for (size_t i = 0; i < c; ++i)
630 if (!isfinite(bf16_to_float(float_to_bf16(work[i])))) return -3;
631 for (size_t i = 0; i < c; ++i)
632 output[i] = float_to_bf16(work[i]);
633 return 0;
634}
635
636#if defined(__x86_64__) && defined(__GNUC__)
637#include <immintrin.h>
638
639struct packed_projection {
640 const uint16_t *input, *weight;
641 uint16_t *stage;
642 size_t rows, channels, width, chunk;
643 atomic_int failed;
644};
645
646__attribute__((target("avx512f,avx512bf16")))
647static void project_packed_bf16(size_t begin, size_t end, void *opaque)
648{
649 struct packed_projection *p = opaque;
650 const uint16_t *input = p->input;
651 uint16_t *stage = p->stage;
652 const size_t rows = p->rows, channels = p->channels, width = p->width, chunk = p->chunk;
653 const size_t pairs = width / 2;
654 enum { ROW_TILE = 6 };
655 for (size_t tile = begin; tile < end; ++tile) {
656 const size_t n = tile * 16;
657 const uint16_t *block = p->weight + n * width;
658 for (size_t i = 0; i < 16 * width; ++i)
659 if ((block[i] & 0x7f80u) == 0x7f80u) {
660 atomic_store_explicit(&p->failed, 1, memory_order_relaxed);
661 return;
662 }
663 for (size_t r = 0; r < rows; r += ROW_TILE) {
664 const size_t valid = rows - r < ROW_TILE ? rows - r : ROW_TILE;
665 __m512 sums[ROW_TILE] = {0};
666 for (size_t start = 0; start < pairs;) {
667 __m512 part[ROW_TILE] = {0};
668 const size_t stop = pairs - start < chunk ? pairs : start + chunk;
669 for (size_t k = start; k < stop; ++k) {
670 const __m512bh y = (__m512bh)_mm512_loadu_si512(block + 32 * k);
671 for (size_t t = 0; t < valid; ++t) {
672 int32_t pair;
673 memcpy(&pair, input + (r + t) * width + 2 * k, sizeof(pair));
674 const __m512bh x = (__m512bh)_mm512_set1_epi32(pair);
675 part[t] = _mm512_dpbf16_ps(part[t], x, y);
676 }
677 }
678 for (size_t t = 0; t < valid; ++t) {
679 sums[t] = _mm512_add_ps(sums[t], part[t]);
680 }
681 start = stop;
682 }
683 for (size_t t = 0; t < valid; ++t) {
684 const __m256bh narrowed = _mm512_cvtneps_pbh(sums[t]);
685 _mm256_storeu_si256((void *)(stage + (r + t) * channels + n),
686 (__m256i)narrowed);
687 }
688 }
689 }
690}
691#endif
692
694 const uint16_t *input, size_t input_elements, const uint16_t *weight,
695 size_t weight_elements, uint16_t *output, size_t output_elements,
696 uint16_t *staged, size_t staged_elements, size_t rows, size_t input_width,
697 size_t output_width, size_t pair_chunk)
698{
699 if (!rows || !input_width || !output_width || input_width % 2 ||
700 output_width % 16 || !pair_chunk || pair_chunk > input_width / 2 ||
701 rows > SIZE_MAX / input_width || output_width > SIZE_MAX / input_width ||
702 rows > SIZE_MAX / output_width)
703 return -2;
704 const size_t in = rows * input_width, w = output_width * input_width, out = rows * output_width;
705 if (input_elements < in || weight_elements < w || output_elements < out || staged_elements < out ||
706 !region_valid(input, in) || !region_valid(weight, w) ||
707 !region_valid(output, out) || !region_valid(staged, out) ||
708 overlap(output, out, input, in) || overlap(output, out, weight, w) ||
709 overlap(output, out, staged, out) || overlap(staged, out, input, in) ||
710 overlap(staged, out, weight, w))
711 return -2;
712#if defined(__x86_64__) && defined(__GNUC__)
713 if (!__builtin_cpu_supports("avx512bf16"))
714 return -4;
715#else
716 return -4;
717#endif
718 for (size_t i = 0; i < in; ++i)
719 if (!isfinite(bf16_to_float(input[i]))) return -3;
720#if defined(__x86_64__) && defined(__GNUC__)
721 struct packed_projection work = {input, weight, staged, rows, output_width, input_width, pair_chunk, 0};
722 const size_t tiles = output_width / 16;
723 if (w >= (1u << 19))
724 ck_checked_parallel_for(tiles, 4, project_packed_bf16, &work);
725 else
726 project_packed_bf16(0, tiles, &work);
727 if (atomic_load_explicit(&work.failed, memory_order_relaxed)) return -3;
728#endif
729 for (size_t i = 0; i < out; ++i)
730 if (!isfinite(bf16_to_float(staged[i]))) return -3;
731 memcpy(output, staged, out * sizeof(*output));
732 return 0;
733}
734
735/* Indexed projection of token rows. Each bank matrix is [input, output].
736 * Widen BF16 products before reduction, then round the dot and bias stages
737 * independently. The caller may mix or repeat bank IDs in any row order. */
739 const uint16_t *input, size_t input_elements, const int32_t *indices,
740 size_t index_elements, const uint16_t *weight, size_t weight_elements,
741 const uint16_t *bias, size_t bias_elements, uint16_t *output,
742 size_t output_elements, uint16_t *staged, size_t staged_elements,
743 size_t rows, size_t input_width, size_t output_width, size_t banks)
744{
745 if (!rows || !input_width || !output_width || !banks ||
746 rows > SIZE_MAX / input_width || rows > SIZE_MAX / output_width ||
747 banks > SIZE_MAX / input_width || banks * input_width > SIZE_MAX / output_width)
748 return -2;
749
750 const size_t in = rows * input_width, out = rows * output_width;
751 const size_t b = banks * output_width, w = b * input_width;
752 if (input_elements < in || index_elements < rows || weight_elements < w ||
753 bias_elements < b || output_elements < out || staged_elements < out)
754 return -2;
755
756 if (!region_valid(input, in) || !region_valid(weight, w) || !region_valid(bias, b) ||
757 !region_valid(output, out) || !region_valid(staged, out) ||
758 !indices || (uintptr_t)indices % _Alignof(int32_t) ||
759 rows > (UINTPTR_MAX - (uintptr_t)indices) / sizeof(*indices))
760 return -2;
761
762 const uint16_t *ids = (const uint16_t *)(const void *)indices;
763 const size_t id_words = rows * (sizeof(*indices) / sizeof(*ids));
764 if (overlap(output, out, staged, out) || overlap(output, out, input, in) ||
765 overlap(output, out, weight, w) || overlap(output, out, bias, b) ||
766 overlap(output, out, ids, id_words) || overlap(staged, out, input, in) ||
767 overlap(staged, out, weight, w) || overlap(staged, out, bias, b) ||
768 overlap(staged, out, ids, id_words))
769 return -2;
770
771 for (size_t r = 0; r < rows; ++r) {
772 if (indices[r] < 0 || (size_t)indices[r] >= banks)
773 return -2;
774 }
775 for (size_t r = 0; r < rows; ++r) {
776 const size_t bank = (size_t)indices[r];
777 const uint16_t *matrix = weight + bank * input_width * output_width;
778 const uint16_t *row = input + r * input_width;
779 for (size_t o = 0; o < output_width; ++o) {
780 double sum = 0.0;
781 for (size_t i = 0; i < input_width; ++i) {
782 volatile double product =
783 (double)bf16_to_float(row[i]) * bf16_to_float(matrix[i * output_width + o]);
784 sum += product;
785 }
786 const float dot = bf16_to_float(float_to_bf16((float)sum));
787 const uint16_t result = float_to_bf16(dot + bf16_to_float(bias[bank * output_width + o]));
788 if (!isfinite(dot) || !isfinite(bf16_to_float(result)))
789 return -3;
790 staged[r * output_width + o] = result;
791 }
792 }
793 memcpy(output, staged, out * sizeof(*output));
794 return 0;
795}
static double dot(const float *a, const float *b, size_t n)
#define RTLD_DEFAULT
static int product(size_t a, size_t b, size_t *out)
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(* ck_checked_range_fn)(size_t begin, size_t end, void *args)
static void ck_checked_parallel_for(size_t count, int grain, ck_checked_range_fn fn, void *args)
static int valid(const uint16_t *p, size_t elements)
static pthread_once_t dgemm_once
int ck_linear_rows_bias_bf16_checked(const uint16_t *input, size_t input_elements, const uint16_t *weight, size_t weight_elements, const uint16_t *bias, size_t bias_elements, uint16_t *output, size_t output_elements, uint16_t *staged, size_t staged_elements, size_t rows, size_t input_width, size_t output_width)
static void bind_dgemm(void)
int ck_indexed_linear_rows_bf16_checked(const uint16_t *input, size_t input_elements, const int32_t *indices, size_t index_elements, const uint16_t *weight, size_t weight_elements, const uint16_t *bias, size_t bias_elements, uint16_t *output, size_t output_elements, uint16_t *staged, size_t staged_elements, size_t rows, size_t input_width, size_t output_width, size_t banks)
static int linear_rows_bf16_checked(const uint16_t *input, size_t input_elements, const uint16_t *weight, size_t weight_elements, const uint16_t *bias, size_t bias_elements, uint16_t *output, size_t output_elements, uint16_t *staged, size_t staged_elements, size_t rows, size_t input_width, size_t output_width)
static int stage_ordered_row(struct ordered_projection *p, size_t row, size_t start, size_t lanes, const double *sums)
static int region_valid(const uint16_t *ptr, size_t elements)
int ck_linear_rows_bf16_blas_checked(const uint16_t *input, size_t input_elements, const uint16_t *weight, size_t weight_elements, uint16_t *output, size_t output_elements, uint16_t *staged, size_t staged_elements, double *work, size_t work_elements, size_t rows, size_t input_width, size_t output_width)
static ck_dgemm_fn dgemm
void(* ck_dgemm_fn)(const char *, const char *, const int *, const int *, const int *, const double *, const double *, const int *, const double *, const int *, const double *, double *, const int *)
static ck_bf16_gemm_fn bf16_gemm
int ck_linear_rows_bf16_cblas_checked(const uint16_t *input, size_t input_elements, const uint16_t *weight, size_t weight_elements, uint16_t *output, size_t output_elements, float *work, size_t work_elements, size_t rows, size_t input_width, size_t output_width)
int ck_linear_rows_bf16_checked(const uint16_t *input, size_t input_elements, const uint16_t *weight, size_t weight_elements, uint16_t *output, size_t output_elements, uint16_t *staged, size_t staged_elements, size_t rows, size_t input_width, size_t output_width)
static pthread_once_t bf16_gemm_once
int ck_linear_rows_bf16_packed_checked(const uint16_t *input, size_t input_elements, const uint16_t *weight, size_t weight_elements, uint16_t *output, size_t output_elements, uint16_t *staged, size_t staged_elements, size_t rows, size_t input_width, size_t output_width, size_t pair_chunk)
void(* ck_bf16_gemm_fn)(int, int, int, int, int, int, float, const uint16_t *, int, const uint16_t *, int, float, float *, int)
static void bind_bf16_gemm(void)
static void project_ordered_tiles(size_t begin, size_t end, void *opaque)
static int overlap(const uint16_t *a, size_t a_count, const uint16_t *b, size_t b_count)
static int project(const uint16_t *input, const uint16_t *weight, uint16_t *out, size_t rows, size_t in_width, size_t out_width, projection_workspace work)
const int32_t * ids
Definition tokenizer.h:447
__attribute__((visibility("default"))) CKTokenizer *ck_tokenizer_create(CKTokenizerType type)
uint32_t end
Definition utf8.c:215
uint32_t start
Definition utf8.c:214