okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaRestore the DeepSeek V4.1 engine and CPU tests removed upstream8ac8ce32e

main
24.9 KiB519 linesraw
1// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
3// src/ds4/ds4_vision.cu - DeepSeek-V4.1's vision tower (see ds4_vision.cuh).
4//
5// One encode, N patches on a gh x gw grid:
6//   patchify (the reference's (x / 255 - 0.5) / 0.5, BF16) -> x = patch_embed(patches)               FP32 [N][1024]
7//   per block, its weights in slot (b % 2) while block b + 1's copy runs:
8//     xn = norm1(x); qkv = rope(wqkv(xn) + bias)                       (rows in pieces of rb_: the FP32 GEMM output)
9//     per query piece of qb_ rows, per head: S = Q K^T / 8 (FP32), P = softmax(S) (BF16), O[:, head] = P V;
10//       x[piece] += wo(O) + bias
11//     xn = norm2(x); per row piece: x += w2(silu(gate) * up), gate | up = w1(xn)
12//   xn = norm(x); the 3 x 3 unfold; GELU(w1 + b1); w2 + b2 -> BF16 rows (the aligner's weights stream in pieces too)
13#include "ds4_vision.cuh"
14
15#include <cublas_v2.h>
16#include "ds4_numerics.cuh"
17#include <cuda_runtime.h>
18
19#include <algorithm>
20#include <cfloat>
21#include <cmath>
22#include <cstring>
23
24namespace strata::ds4 {
25namespace {
26
27#define VK(call)                                                                      \
28    do {                                                                              \
29        cudaError_t e_ = (call);                                                      \
30        if (e_ != cudaSuccess) {                                                      \
31            err = std::string("vision: ") + #call + ": " + cudaGetErrorString(e_);    \
32            return false;                                                             \
33        }                                                                             \
34    } while (0)
35#define VB(call)                                                                                      \
36    do {                                                                                              \
37        cublasStatus_t e_ = (call);                                                                   \
38        if (e_ != CUBLAS_STATUS_SUCCESS) {                                                            \
39            err = std::string("vision: ") + #call + ": cuBLAS status " + std::to_string((int) e_);   \
40            return false;                                                                             \
41        }                                                                                             \
42    } while (0)
43
44constexpr int kT = 256;                  // threads of the row kernels
45constexpr int kSmT = 512, kSmPer = 20;   // softmax: a row of up to 10240 keys in registers
46constexpr size_t kWs = 16u << 20;        // cuBLAS workspace
47
48__device__ __forceinline__ float bf(uint16_t b) { return __uint_as_float((uint32_t) b << 16); }
49__device__ __forceinline__ uint16_t bfr(float f) { return bf16_rn(f); }
50
51__device__ float block_reduce(float v, bool is_max) {
52    __shared__ float red[32];
53    __shared__ float tot;
54    for (int o = 16; o > 0; o >>= 1) {
55        const float u = __shfl_xor_sync(0xffffffffu, v, o);
56        v = is_max ? fmaxf(v, u) : v + u;
57    }
58    const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = (blockDim.x + 31) >> 5;
59    __syncthreads();   // (an earlier call's readers of red / tot are done)
60    if (lane == 0) red[w] = v;
61    __syncthreads();
62    if (w == 0) {
63        v = lane < nw ? red[lane] : (is_max ? -FLT_MAX : 0.0f);
64        for (int o = 16; o > 0; o >>= 1) {
65            const float u = __shfl_xor_sync(0xffffffffu, v, o);
66            v = is_max ? fmaxf(v, u) : v + u;
67        }
68        if (lane == 0) tot = v;
69    }
70    __syncthreads();
71    return tot;
72}
73
74// patch i of the gh x gw grid: its 3 x p x p values, channel-major (the reference's reshape / permute)
75__global__ void patchify_kernel(const uint8_t* __restrict__ rgb, int width, int gw, int p, uint16_t* __restrict__ out) {
76    const int i = blockIdx.x, e = threadIdx.x, pp = p * p;
77    if (e >= 3 * pp) return;
78    const int c = e / pp, r = e % pp, y = (i / gw) * p + r / p, x = (i % gw) * p + r % p;
79    const float u = (float) rgb[((size_t) y * width + x) * 3 + c];
80    out[(size_t) i * 3 * pp + e] = bfr(__fdiv_rn(__fsub_rn(__fdiv_rn(u, 255.0f), 0.5f), 0.5f));
81}
82
83// x[r] += y[r] (y null: nothing) + bias
84__global__ void add_rows_kernel(float* __restrict__ x, const float* __restrict__ y, int ldy,
85                                const uint16_t* __restrict__ bias, int dim) {
86    const int r = blockIdx.x;
87    for (int e = threadIdx.x; e < dim; e += blockDim.x) {
88        float v = x[(size_t) r * dim + e];
89        if (y != nullptr) v += y[(size_t) r * ldy + e];
90        if (bias != nullptr) v += bf(bias[e]);
91        x[(size_t) r * dim + e] = v;
92    }
93}
94
95__global__ void rmsnorm_kernel(const float* __restrict__ x, const uint16_t* __restrict__ w, int dim, float eps,
96                               uint16_t* __restrict__ out) {
97    const int r = blockIdx.x;
98    const float* xr = x + (size_t) r * dim;
99    float ss = 0.0f;
100    for (int e = threadIdx.x; e < dim; e += blockDim.x) ss += xr[e] * xr[e];
101    ss = block_reduce(ss, false);
102    const float rs = rsqrtf(ss / (float) dim + eps);
103    for (int e = threadIdx.x; e < dim; e += blockDim.x) out[(size_t) r * dim + e] = bfr(bf(w[e]) * (xr[e] * rs));
104}
105
106// a piece's rows of wqkv's output (+ bias, rounded to BF16 as the reference's linear) into qkv, q and k rotated: the
107// head's first half pairs with its second; frequency j < hd / 4 turns with the patch's row, the rest with its column
108__global__ void qkv_rope_kernel(const float* __restrict__ y, const uint16_t* __restrict__ bias, int r0, int gw,
109                                const float* __restrict__ inv_freq, int heads, int hd, uint16_t* __restrict__ qkv) {
110    const int r = blockIdx.x, gr = r0 + r, dim = heads * hd, half = hd / 2, nf = hd / 4;
111    const int row = gr / gw, col = gr % gw;
112    const float* yr = y + (size_t) r * 3 * dim;
113    uint16_t* o = qkv + (size_t) gr * 3 * dim;
114    for (int i = threadIdx.x; i < 2 * heads * half; i += blockDim.x) {
115        const int base = (i / half) * hd, d = i % half;
116        const float x1 = bf(bfr(yr[base + d] + bf(bias[base + d])));
117        const float x2 = bf(bfr(yr[base + d + half] + bf(bias[base + d + half])));
118        float sn, cs;
119        sincosf((float) (d < nf ? row : col) * inv_freq[d % nf], &sn, &cs);
120        o[base + d] = bfr(x1 * cs - x2 * sn);
121        o[base + d + half] = bfr(x2 * cs + x1 * sn);
122    }
123    for (int e = 2 * dim + threadIdx.x; e < 3 * dim; e += blockDim.x) o[e] = bfr(yr[e] + bf(bias[e]));
124}
125
126__global__ void __launch_bounds__(kSmT) softmax_kernel(const float* __restrict__ s, int n, uint16_t* __restrict__ p) {
127    const float* sr = s + (size_t) blockIdx.x * n;
128    uint16_t* pr = p + (size_t) blockIdx.x * n;
129    float v[kSmPer];
130    float m = -FLT_MAX;
131#pragma unroll
132    for (int k = 0; k < kSmPer; ++k) {
133        const int e = threadIdx.x + k * kSmT;
134        v[k] = e < n ? sr[e] : -FLT_MAX;
135        m = fmaxf(m, v[k]);
136    }
137    m = block_reduce(m, true);
138    float sum = 0.0f;
139#pragma unroll
140    for (int k = 0; k < kSmPer; ++k) {
141        const int e = threadIdx.x + k * kSmT;
142        v[k] = e < n ? expf(v[k] - m) : 0.0f;
143        sum += v[k];
144    }
145    const float inv = 1.0f / block_reduce(sum, false);
146#pragma unroll
147    for (int k = 0; k < kSmPer; ++k) {
148        const int e = threadIdx.x + k * kSmT;
149        if (e < n) pr[e] = bfr(v[k] * inv);
150    }
151}
152
153// mid = silu(gate) * up, gate | up the halves of w1's row (BF16 steps, as the reference's)
154__global__ void silu_mul_kernel(const float* __restrict__ y, int inter, uint16_t* __restrict__ mid) {
155    const int r = blockIdx.y, e = blockIdx.x * blockDim.x + threadIdx.x;
156    if (e >= inter) return;
157    const float gt = bf(bfr(y[(size_t) r * 2 * inter + e])), up = bf(bfr(y[(size_t) r * 2 * inter + inter + e]));
158    mid[(size_t) r * inter + e] = bfr(bf(bfr(gt / (1.0f + expf(-gt)))) * up);
159}
160
161// the aligner's input: block (bi, bj) of the m x m patches as one row, value c * m * m + kh * m + kw (F.unfold's
162// order), zero past the grid
163__global__ void unfold_kernel(const uint16_t* __restrict__ xn, int gh, int gw, int m, int dim, int lw,
164                              uint16_t* __restrict__ un) {
165    const int l = blockIdx.x, bi = l / lw, bj = l % lw, mm = m * m;
166    for (int f = threadIdx.x; f < dim * mm; f += blockDim.x) {
167        const int c = f / mm, k = f % mm, y = bi * m + k / m, x = bj * m + k % m;
168        un[(size_t) l * dim * mm + f] = y < gh && x < gw ? xn[((size_t) y * gw + x) * dim + c] : (uint16_t) 0;
169    }
170}
171
172// out = act(bf16(y + bias)): GELU (erf) or none
173__global__ void bias_act_kernel(const float* __restrict__ y, const uint16_t* __restrict__ bias, int n, int gelu,
174                                uint16_t* __restrict__ out) {
175    const int r = blockIdx.y, e = blockIdx.x * blockDim.x + threadIdx.x;
176    if (e >= n) return;
177    float v = bf(bfr(y[(size_t) r * n + e] + bf(bias[e])));
178    if (gelu) v = 0.5f * v * (1.0f + erff(v * 0.70710678118654752f));
179    out[(size_t) r * n + e] = bfr(v);
180}
181
182int cdiv(int a, int b) { return (a + b - 1) / b; }
183
184// y[r][o] = alpha * sum_k x[r][k] W[o][k] (row-major W [out][in] with row stride ldw, x [rows][ldx], y [rows][ldy])
185bool gemm(cublasHandle_t h, const uint16_t* W, int ldw, const uint16_t* x, int ldx, void* y, cudaDataType yt, int ldy,
186          int rows, int in, int out, float alpha, std::string& err) {
187    const float beta = 0.0f;
188    VB(cublasGemmEx(h, CUBLAS_OP_T, CUBLAS_OP_N, out, rows, in, &alpha, W, CUDA_R_16BF, ldw, x, CUDA_R_16BF, ldx, &beta,
189                    y, yt, ldy, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT));
190    return true;
191}
192
193}  // namespace
194
195template <class T>
196bool VisionTower::dalloc(T*& p, size_t n, std::string& err) {
197    void* v = nullptr;
198    const size_t b = (n * sizeof(T) + 255) / 256 * 256;
199    if (cudaMalloc(&v, b) != cudaSuccess) {
200        err = "vision: cudaMalloc " + std::to_string(b >> 20) + " MiB on CUDA" + std::to_string(at_) + " failed";
201        return false;
202    }
203    dallocs_.push_back(v);
204    dev_bytes_ += b;
205    p = (T*) v;
206    return true;
207}
208
209VisionTower::~VisionTower() { release(); }
210
211void VisionTower::release() {
212    if (at_ < 0) return;
213    int cur = 0;
214    cudaGetDevice(&cur);
215    cudaSetDevice(at_);
216    for (int i = 0; i < 2; ++i) {
217        if (copied_[i]) cudaEventDestroy((cudaEvent_t) copied_[i]);
218        if (used_[i]) cudaEventDestroy((cudaEvent_t) used_[i]);
219        copied_[i] = used_[i] = nullptr;
220    }
221    if (blas_) cublasDestroy((cublasHandle_t) blas_);
222    if (st_) cudaStreamDestroy((cudaStream_t) st_);
223    if (cs_) cudaStreamDestroy((cudaStream_t) cs_);
224    for (void* p : dallocs_) cudaFree(p);
225    if (host_) cudaFreeHost(host_);
226    cudaSetDevice(cur);
227    blas_ = st_ = cs_ = nullptr;
228    dallocs_.clear();
229    host_ = nullptr;
230    dev_ = at_ = -1;
231    dev_bytes_ = 0;
232}
233
234bool VisionTower::load(const VisionGeo& g, int device, const Reader& read, std::string& err) {
235    g_ = g;
236    const int D = g.dim, I = g.inter, P = g.patch, M = g.merge, hd = g.heads > 0 ? g.dim / g.heads : 0;
237    if (g.layers <= 0 || hd * g.heads != D || hd % 4 != 0 || P <= 0 || M <= 0 || g.max_tokens < 5) {
238        err = "vision: geometry not covered";
239        return false;
240    }
241    // the largest aligner grid within max_tokens (n_h * (n_w + 1) + 2): the work buffers' size
242    int cells = 0;
243    for (int h = 1; h <= g.max_tokens - 2; ++h) {
244        const int w = (g.max_tokens - 2) / h - 1;
245        if (w >= 1) cells = std::max(cells, h * w);
246    }
247    max_n_ = cells * M * M;
248    if (max_n_ > kSmT * kSmPer) {
249        err = "vision: " + std::to_string(max_n_) + " patches are more than the attention covers";
250        return false;
251    }
252    cudaSetDevice(device);
253    at_ = device;
254    dev_bytes_ = 0;
255    // the checkpoint's tensors, checked before anything is read
256    struct Want {
257        std::string name;
258        std::vector<int64_t> shape;
259    };
260    std::vector<Want> want = {{"vision.patch_embed.proj.weight", {D, 3 * P * P}},
261                              {"vision.patch_embed.proj.bias", {D}},
262                              {"vision.norm.weight", {D}},
263                              {"aligner.w1.weight", {g.out, (int64_t) D * M * M}},
264                              {"aligner.w1.bias", {g.out}},
265                              {"aligner.w2.weight", {g.out, g.out}},
266                              {"aligner.w2.bias", {g.out}}};
267    for (int l = 0; l < g.layers; ++l) {
268        const std::string B = "vision.blocks." + std::to_string(l) + ".";
269        want.push_back({B + "norm1.weight", {D}});
270        want.push_back({B + "norm2.weight", {D}});
271        want.push_back({B + "attn.wqkv.weight", {3 * D, D}});
272        want.push_back({B + "attn.wqkv.bias", {3 * D}});
273        want.push_back({B + "attn.wo.weight", {D, D}});
274        want.push_back({B + "attn.wo.bias", {D}});
275        want.push_back({B + "mlp.w1.weight", {2 * I, D}});
276        want.push_back({B + "mlp.w2.weight", {D, I}});
277    }
278    for (const Want& w : want) {
279        std::vector<int64_t> s;
280        if (!read(w.name, s, nullptr)) {
281            err = "vision: " + w.name + " is not in the checkpoint";
282            return false;
283        }
284        if (s != w.shape) {
285            err = "vision: " + w.name + " has another shape than the config's";
286            return false;
287        }
288    }
289    // the streamed weights, pinned
290    block_n_ = (size_t) 3 * D * D + (size_t) D * D + (size_t) 2 * I * D + (size_t) D * I;
291    al1_off_ = block_n_ * g.layers;
292    al2_off_ = al1_off_ + (size_t) g.out * D * M * M;
293    const size_t host_n = al2_off_ + (size_t) g.out * g.out;
294    if (cudaHostAlloc((void**) &host_, host_n * 2, cudaHostAllocDefault) != cudaSuccess) {
295        host_ = nullptr;
296        err = "vision: pinning " + std::to_string((host_n * 2) >> 20) + " MiB of host memory failed";
297        return false;
298    }
299    std::vector<int64_t> s;
300    for (int l = 0; l < g.layers; ++l) {
301        const std::string B = "vision.blocks." + std::to_string(l) + ".";
302        uint16_t* b = host_ + (size_t) l * block_n_;
303        if (!read(B + "attn.wqkv.weight", s, b) || !read(B + "attn.wo.weight", s, b + (size_t) 3 * D * D) ||
304            !read(B + "mlp.w1.weight", s, b + (size_t) 4 * D * D) ||
305            !read(B + "mlp.w2.weight", s, b + (size_t) 4 * D * D + (size_t) 2 * I * D)) {
306            err = "vision: block " + std::to_string(l) + ": read failed";
307            return false;
308        }
309    }
310    if (!read("aligner.w1.weight", s, host_ + al1_off_) || !read("aligner.w2.weight", s, host_ + al2_off_)) {
311        err = "vision: the aligner: read failed";
312        return false;
313    }
314    // the small ones on the device
315    auto up = [&](const std::string& name, size_t n, uint16_t*& d) -> bool {
316        std::vector<uint16_t> h(n);
317        std::vector<int64_t> sh;
318        if (!read(name, sh, h.data())) {
319            err = "vision: " + name + ": read failed";
320            return false;
321        }
322        if (!dalloc(d, n, err)) return false;
323        VK(cudaMemcpy(d, h.data(), n * 2, cudaMemcpyHostToDevice));
324        return true;
325    };
326    bool ok = up("vision.patch_embed.proj.weight", (size_t) D * 3 * P * P, pe_w_) &&
327              up("vision.patch_embed.proj.bias", D, pe_b_) && up("vision.norm.weight", D, norm_) &&
328              up("aligner.w1.bias", g.out, al1_b_) && up("aligner.w2.bias", g.out, al2_b_);
329    n1_.assign(g.layers, nullptr);
330    n2_.assign(g.layers, nullptr);
331    bqkv_.assign(g.layers, nullptr);
332    bo_.assign(g.layers, nullptr);
333    for (int l = 0; l < g.layers && ok; ++l) {
334        const std::string B = "vision.blocks." + std::to_string(l) + ".";
335        ok = up(B + "norm1.weight", D, n1_[l]) && up(B + "norm2.weight", D, n2_[l]) &&
336             up(B + "attn.wqkv.bias", 3 * D, bqkv_[l]) && up(B + "attn.wo.bias", D, bo_[l]);
337    }
338    if (!ok) return false;
339    {   // the rotary's frequencies: theta ^ -(2i / (hd / 2)), hd / 4 of them
340        const int nf = hd / 4;
341        std::vector<float> f(nf);
342        for (int i = 0; i < nf; ++i) f[i] = 1.0f / std::pow(g.theta, (float) (2 * i) / (float) (hd / 2));
343        if (!dalloc(inv_freq_, nf, err)) return false;
344        VK(cudaMemcpy(inv_freq_, f.data(), nf * 4, cudaMemcpyHostToDevice));
345    }
346    // the work buffers: the patch grid's rows whole (the residual, its norm, q / k / v), the GEMM outputs a piece of
347    // rows at a time, the attention's scores a piece of queries at a time (~48 MB)
348    const int L = cells;
349    rb_ = 2048;
350    qb_ = std::max(16, (int) ((48u << 20) / ((size_t) max_n_ * 4)) / 16 * 16);
351    slot_n_ = std::max(block_n_, (size_t) 1 << 22);
352    const size_t y_n = (size_t) rb_ * std::max({3 * D, 2 * I, D});
353    const size_t qkv_n = std::max({(size_t) max_n_ * 3 * D,
354                                   (size_t) max_n_ * 3 * P * P + ((size_t) max_n_ * 3 * P * P + 1) / 2,   // patches, pixels
355                                   (size_t) L * D * M * M + (size_t) 2 * L * g.out});                      // the aligner's
356    if ((size_t) L * g.out > y_n || (size_t) max_n_ * D > y_n) {
357        err = "vision: work buffer sizes";
358        return false;
359    }
360    ok = dalloc(x_, (size_t) max_n_ * D, err) && dalloc(xn_, (size_t) max_n_ * D, err) && dalloc(qkv_, qkv_n, err) &&
361         dalloc(y_, y_n, err) && dalloc(o_, (size_t) max_n_ * D, err) && dalloc(mid_, (size_t) rb_ * I, err) &&
362         dalloc(s_, (size_t) qb_ * max_n_, err) && dalloc(p_, (size_t) qb_ * max_n_, err) &&
363         dalloc(slot_[0], slot_n_, err) && dalloc(slot_[1], slot_n_, err) && dalloc(ws_, kWs, err);
364    if (!ok) return false;
365    patch_ = qkv_;   // (before block 0's qkv)
366    rgb_ = (uint8_t*) (qkv_ + (size_t) max_n_ * 3 * P * P);
367    un_ = qkv_;      // (after the last block's attention)
368    a16_ = un_ + (size_t) L * D * M * M;
369    outb_ = a16_ + (size_t) L * g.out;
370    cublasHandle_t h = nullptr;
371    VB(cublasCreate(&h));
372    blas_ = h;
373    cudaStream_t st = nullptr, cs = nullptr;
374    VK(cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking));
375    VK(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking));
376    st_ = st;
377    cs_ = cs;
378    VB(cublasSetStream(h, st));
379    VB(cublasSetWorkspace(h, ws_, kWs));
380    for (int i = 0; i < 2; ++i) {
381        cudaEvent_t a = nullptr, b = nullptr;
382        VK(cudaEventCreateWithFlags(&a, cudaEventDisableTiming));
383        VK(cudaEventCreateWithFlags(&b, cudaEventDisableTiming));
384        copied_[i] = a;
385        used_[i] = b;
386    }
387    dev_ = device;
388    return true;
389}
390
391bool VisionTower::encode(const uint8_t* rgb, int width, int height, std::vector<uint16_t>& rows, int& n_h, int& n_w,
392                         std::string& err) {
393    if (dev_ < 0) {
394        err = "vision: not loaded";
395        return false;
396    }
397    const VisionGeo& g = g_;
398    const int D = g.dim, I = g.inter, P = g.patch, M = g.merge, hd = D / g.heads, H3 = 3 * D;
399    if (width <= 0 || height <= 0 || width % P != 0 || height % P != 0) {
400        err = "vision: an image of " + std::to_string(width) + " x " + std::to_string(height) +
401              " pixels (both sides must be multiples of " + std::to_string(P) + ")";
402        return false;
403    }
404    const int gh = height / P, gw = width / P, N = gh * gw;
405    n_h = cdiv(gh, M);
406    n_w = cdiv(gw, M);
407    const int L = n_h * n_w;
408    if (N > max_n_ || n_h * (n_w + 1) + 2 > g.max_tokens) {
409        err = "vision: an image of " + std::to_string(width) + " x " + std::to_string(height) + " pixels is more than " +
410              std::to_string(g.max_tokens) + " image tokens";
411        return false;
412    }
413    cudaSetDevice(dev_);
414    cublasHandle_t h = (cublasHandle_t) blas_;
415    cudaStream_t s = (cudaStream_t) st_, cs = (cudaStream_t) cs_;
416    // the weights in the order the encode takes them: the blocks, then the aligner's in pieces of a slot
417    std::vector<Piece> pcs;
418    for (int l = 0; l < g.layers; ++l) pcs.push_back({host_ + (size_t) l * block_n_, block_n_});
419    const int in1 = D * M * M, r1 = (int) std::min<size_t>(g.out, slot_n_ / in1), r2 = (int) std::min<size_t>(g.out, slot_n_ / g.out);
420    for (int o0 = 0; o0 < g.out; o0 += r1)
421        pcs.push_back({host_ + al1_off_ + (size_t) o0 * in1, (size_t) std::min(r1, g.out - o0) * in1});
422    for (int o0 = 0; o0 < g.out; o0 += r2)
423        pcs.push_back({host_ + al2_off_ + (size_t) o0 * g.out, (size_t) std::min(r2, g.out - o0) * g.out});
424    auto fetch = [&](size_t i) -> bool {
425        const int k = (int) (i % 2);
426        VK(cudaStreamWaitEvent(cs, (cudaEvent_t) used_[k], 0));
427        VK(cudaMemcpyAsync(slot_[k], pcs[i].host, pcs[i].n * 2, cudaMemcpyHostToDevice, cs));
428        VK(cudaEventRecord((cudaEvent_t) copied_[k], cs));
429        return true;
430    };
431    size_t pi = 0;   // the piece being used
432    auto take = [&]() -> const uint16_t* {   // the next piece's slot, once its copy is in (the one after it started)
433        const int k = (int) (pi % 2);
434        if (pi + 1 < pcs.size() && !fetch(pi + 1)) return nullptr;
435        if (cudaStreamWaitEvent(s, (cudaEvent_t) copied_[k], 0) != cudaSuccess) {
436            err = "vision: waiting for a weight copy failed";
437            return nullptr;
438        }
439        return slot_[k];
440    };
441    auto done = [&]() {   // the piece's work is queued: its slot is free once that ran
442        cudaEventRecord((cudaEvent_t) used_[pi % 2], s);
443        ++pi;
444    };
445    if (!fetch(0)) return false;
446
447    // the patches
448    VK(cudaMemcpyAsync(rgb_, rgb, (size_t) N * 3 * P * P, cudaMemcpyHostToDevice, s));
449    patchify_kernel<<<N, 3 * P * P, 0, s>>>(rgb_, width, gw, P, patch_);
450    if (!gemm(h, pe_w_, 3 * P * P, patch_, 3 * P * P, x_, CUDA_R_32F, D, N, 3 * P * P, D, 1.0f, err)) return false;
451    add_rows_kernel<<<N, kT, 0, s>>>(x_, nullptr, 0, pe_b_, D);
452
453    const float scale = 1.0f / std::sqrt((float) hd);
454    const int qb = (int) std::max<size_t>(1, std::min<size_t>((size_t) N, (size_t) qb_ * max_n_ / (size_t) N));
455    for (int l = 0; l < g.layers; ++l) {
456        const uint16_t* wqkv = take();
457        if (wqkv == nullptr) return false;
458        const uint16_t *wo = wqkv + (size_t) H3 * D, *w1 = wo + (size_t) D * D, *w2 = w1 + (size_t) 2 * I * D;
459        rmsnorm_kernel<<<N, kT, 0, s>>>(x_, n1_[l], D, g.eps, xn_);
460        for (int r0 = 0; r0 < N; r0 += rb_) {
461            const int nr = std::min(rb_, N - r0);
462            if (!gemm(h, wqkv, D, xn_ + (size_t) r0 * D, D, y_, CUDA_R_32F, H3, nr, D, H3, 1.0f, err)) return false;
463            qkv_rope_kernel<<<nr, kT, 0, s>>>(y_, bqkv_[l], r0, gw, inv_freq_, g.heads, hd, qkv_);
464        }
465        for (int q0 = 0; q0 < N; q0 += qb) {
466            const int nq = std::min(qb, N - q0);
467            const float one = 1.0f, zero = 0.0f;
468            for (int hh = 0; hh < g.heads; ++hh) {
469                // S^T (keys x queries, column-major) = K Q^T: row-major S [query][key]
470                VB(cublasGemmEx(h, CUBLAS_OP_T, CUBLAS_OP_N, N, nq, hd, &scale, qkv_ + D + hh * hd, CUDA_R_16BF, H3,
471                                qkv_ + (size_t) q0 * H3 + hh * hd, CUDA_R_16BF, H3, &zero, s_, CUDA_R_32F, N,
472                                CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT));
473                softmax_kernel<<<nq, kSmT, 0, s>>>(s_, N, p_);
474                // O^T (hd x queries) = V^T P^T: row-major O [query][head's hd] at column hh * hd
475                VB(cublasGemmEx(h, CUBLAS_OP_N, CUBLAS_OP_N, hd, nq, N, &one, qkv_ + 2 * D + hh * hd, CUDA_R_16BF, H3,
476                                p_, CUDA_R_16BF, N, &zero, o_ + hh * hd, CUDA_R_16BF, D, CUBLAS_COMPUTE_32F,
477                                CUBLAS_GEMM_DEFAULT));
478            }
479            if (!gemm(h, wo, D, o_, D, y_, CUDA_R_32F, D, nq, D, D, 1.0f, err)) return false;
480            add_rows_kernel<<<nq, kT, 0, s>>>(x_ + (size_t) q0 * D, y_, D, bo_[l], D);
481        }
482        rmsnorm_kernel<<<N, kT, 0, s>>>(x_, n2_[l], D, g.eps, xn_);
483        for (int r0 = 0; r0 < N; r0 += rb_) {
484            const int nr = std::min(rb_, N - r0);
485            if (!gemm(h, w1, D, xn_ + (size_t) r0 * D, D, y_, CUDA_R_32F, 2 * I, nr, D, 2 * I, 1.0f, err)) return false;
486            silu_mul_kernel<<<dim3(cdiv(I, kT), nr), kT, 0, s>>>(y_, I, mid_);
487            if (!gemm(h, w2, I, mid_, I, y_, CUDA_R_32F, D, nr, I, D, 1.0f, err)) return false;
488            add_rows_kernel<<<nr, kT, 0, s>>>(x_ + (size_t) r0 * D, y_, D, nullptr, D);
489        }
490        done();
491    }
492    rmsnorm_kernel<<<N, kT, 0, s>>>(x_, norm_, D, g.eps, xn_);
493
494    // the aligner
495    unfold_kernel<<<L, kT, 0, s>>>(xn_, gh, gw, M, D, n_w, un_);
496    for (int o0 = 0; o0 < g.out; o0 += r1) {
497        const uint16_t* w = take();
498        if (w == nullptr) return false;
499        if (!gemm(h, w, in1, un_, in1, y_ + o0, CUDA_R_32F, g.out, L, in1, std::min(r1, g.out - o0), 1.0f, err))
500            return false;
501        done();
502    }
503    bias_act_kernel<<<dim3(cdiv(g.out, kT), L), kT, 0, s>>>(y_, al1_b_, g.out, 1, a16_);
504    for (int o0 = 0; o0 < g.out; o0 += r2) {
505        const uint16_t* w = take();
506        if (w == nullptr) return false;
507        if (!gemm(h, w, g.out, a16_, g.out, y_ + o0, CUDA_R_32F, g.out, L, g.out, std::min(r2, g.out - o0), 1.0f, err))
508            return false;
509        done();
510    }
511    bias_act_kernel<<<dim3(cdiv(g.out, kT), L), kT, 0, s>>>(y_, al2_b_, g.out, 0, outb_);
512    rows.resize((size_t) L * g.out);
513    VK(cudaMemcpyAsync(rows.data(), outb_, rows.size() * 2, cudaMemcpyDeviceToHost, s));
514    VK(cudaStreamSynchronize(s));
515    VK(cudaGetLastError());
516    return true;
517}
518
519}  // namespace strata::ds4