← Back to C-Kernel-Engine Docs Doxygen Source Documentation
Loading...
Searching...
No Matches
window_qkv_split_checked.c
Go to the documentation of this file.
1#include <stddef.h>
2#include <stdint.h>
3#include <string.h>
4
5static int valid(const uint16_t *p, size_t bytes)
6{
7 return p && (uintptr_t)p % sizeof(*p) == 0 && (uintptr_t)p <= UINTPTR_MAX - bytes;
8}
9
10static int overlaps(const uint16_t *a, size_t na, const uint16_t *b, size_t nb)
11{
12 return (uintptr_t)a < (uintptr_t)b + nb && (uintptr_t)b < (uintptr_t)a + na;
13}
14
15int ck_window_qkv_split_bf16_checked(const uint16_t *packed, uint16_t *query, uint16_t *key,
16 uint16_t *value, size_t packed_elements, size_t plane_elements,
17 size_t windows, size_t tokens, size_t heads, size_t channels)
18{
19 if (!windows || windows > 384 || !tokens || tokens > 4096 ||
20 !heads || heads > 32 || !channels || channels > 128 || windows * heads > 384 ||
21 windows * heads * tokens > 64 * 64 * 64)
22 return -2;
23 const size_t width = heads * channels, elements = windows * tokens * width;
24 if (plane_elements != elements || packed_elements != 3 * elements)
25 return -2;
26 const size_t bytes = elements * sizeof(*query), packed_bytes = 3 * bytes;
27 uint16_t *outputs[] = {query, key, value};
28 if (!valid(packed, packed_bytes))
29 return -1;
30 for (size_t i = 0; i < 3; ++i) {
31 if (!valid(outputs[i], bytes) || overlaps(outputs[i], bytes, packed, packed_bytes))
32 return -1;
33 for (size_t j = 0; j < i; ++j)
34 if (overlaps(outputs[i], bytes, outputs[j], bytes))
35 return -1;
36 }
37 // Packed rows hold [Q,K,V][head,channel]; a plane is one (window, head).
38 for (size_t w = 0; w < windows; ++w) {
39 for (size_t h = 0; h < heads; ++h) {
40 for (size_t t = 0; t < tokens; ++t) {
41 const size_t src = (w * tokens + t) * 3 * width + h * channels;
42 const size_t dst = ((w * heads + h) * tokens + t) * channels;
43 for (size_t i = 0; i < 3; ++i)
44 memcpy(outputs[i] + dst, packed + src + i * width, channels * sizeof(*packed));
45 }
46 }
47 }
48 return 0;
49}
int ck_window_qkv_split_bf16_checked(const uint16_t *packed, uint16_t *query, uint16_t *key, uint16_t *value, size_t packed_elements, size_t plane_elements, size_t windows, size_t tokens, size_t heads, size_t channels)
static int valid(const uint16_t *p, size_t bytes)
static int overlaps(const uint16_t *a, size_t na, const uint16_t *b, size_t nb)