okami.mom/strata

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

Niko1221Merge f-own-5b 9b242bb5b into f-own-int (round 15: the own text encoder and tokenizer as test programs, the DiT reference tool and position tables; committed work only)11c8c701a

main
27.4 KiB557 linesraw
1// src/image/te/qwen3vl_te.cu - Strata's Qwen-Image-2.1 text encoder (see include/strata/image/qwen3vl_te.hpp).
2//
3// Layout: activations are token-major, [T][width] (a token is a row).  Per layer:
4//   h16  = f16(RMSNorm(x) * attn_norm)                                    rms_f16_kernel
5//   qkv  = h16 . [Wq; Wk; Wv]^T          f32 [T][(H + 2 KV) D]           three weights decoded into one f16 buffer, one GemmEx
6//   q16, k16 = f16(rope(RMSNorm_head(q|k) * q_norm|k_norm)), v16 = f16(v), head-major [heads][T][D]   qk_rope_kernel
7//   per chunk of 256 queries, per query head r of a KV group g (batched over the 8 groups):
8//        S = q . k^T (f32), P = f16(softmax(S / sqrt(D), causal)), O = P . v (f32, into att [T][H D])
9//   att16 = f16(att);  x += att16 . Wo^T  (GemmEx with beta = 1: straight into the f32 residual)
10//   h16  = f16(RMSNorm(x) * ffn_norm);  gu = h16 . [Wgate; Wup]^T  f32 [T][2F]
11//   a16  = f16(silu(gate) * up);  x += a16 . Wdown^T
12// The rope angles are computed in double on the device (positions are the token indices; Qwen3-VL's IMROPE with
13// sections 24/20/20 and equal text positions is the plain NEOX rotation of the two halves), so no host maths library
14// enters the result.  Fixed-order reductions everywhere: the same prompt gives the same bytes run to run.
15#include "strata/image/qwen3vl_te.hpp"
16
17#include "strata/image/te_dequant.hpp"
18#include "strata/kernels/f16_bits.hpp"
19
20#define STRATA_GGUF_MAIN_DISABLED 1
21#include "strata/artifact/gguf_reader.hpp"
22
23#if defined(__HIP__) || defined(__HIPCC__) || defined(__HIP_PLATFORM_AMD__)
24#include "strata/hip_compat/cuda_runtime.h"
25#include "strata/hip_compat/cublas_v2.h"
26#else
27#include <cuda_runtime.h>
28#include <cublas_v2.h>
29#endif
30
31#include <algorithm>
32#include <chrono>
33#include <cmath>
34#include <cstdio>
35#include <cstring>
36#include <memory>
37#include <string>
38#include <thread>
39#include <vector>
40
41namespace strata::image {
42namespace {
43
44constexpr int QCHUNK = 256;               // queries per attention chunk (fixed: see the file comment)
45constexpr int HD = 128;                   // head dim (checked against the file)
46
47#define TE_CUDA(x)                                                                                         \
48    do {                                                                                                   \
49        cudaError_t e_ = (x);                                                                              \
50        if (e_ != cudaSuccess) return std::string("qwen3vl_te: ") + #x + ": " + cudaGetErrorString(e_);    \
51    } while (0)
52#define TE_BLAS(x)                                                                                         \
53    do {                                                                                                   \
54        auto s_ = (x);                                                                                     \
55        if (s_ != CUBLAS_STATUS_SUCCESS) return std::string("qwen3vl_te: ") + #x + ": status " + std::to_string((int) s_); \
56    } while (0)
57#define TE_TRY(x)                                                                                          \
58    do {                                                                                                   \
59        std::string r_ = (x);                                                                              \
60        if (!r_.empty()) return r_;                                                                        \
61    } while (0)
62
63using strata::kernels::f16_from_f32;
64
65// ---------------------------------------------------------------------------------------------------------------
66// kernels (256 threads; fixed-order block reductions)
67
68__device__ __forceinline__ float block_sum256(float v, float* sh) {
69    sh[threadIdx.x] = v;
70    __syncthreads();
71    for (int s = 128; s > 0; s >>= 1) {
72        if ((int) threadIdx.x < s) sh[threadIdx.x] += sh[threadIdx.x + s];
73        __syncthreads();
74    }
75    const float r = sh[0];
76    __syncthreads();
77    return r;
78}
79
80__device__ __forceinline__ float block_max256(float v, float* sh) {
81    sh[threadIdx.x] = v;
82    __syncthreads();
83    for (int s = 128; s > 0; s >>= 1) {
84        if ((int) threadIdx.x < s) sh[threadIdx.x] = fmaxf(sh[threadIdx.x], sh[threadIdx.x + s]);
85        __syncthreads();
86    }
87    const float r = sh[0];
88    __syncthreads();
89    return r;
90}
91
92// out[t][c] = f16(x[t][c] * inv_rms(x[t]) * w[c]); one block per token
93__global__ void rms_f16_kernel(const float* __restrict__ x, const float* __restrict__ w, int C, float eps,
94                               uint16_t* __restrict__ out) {
95    __shared__ float sh[256];
96    const float* row = x + (size_t) blockIdx.x * C;
97    float s = 0.f;
98    for (int c = threadIdx.x; c < C; c += 256) s += row[c] * row[c];
99    s = block_sum256(s, sh);
100    const float inv = 1.0f / sqrtf(s / (float) C + eps);
101    uint16_t* o = out + (size_t) blockIdx.x * C;
102    for (int c = threadIdx.x; c < C; c += 256) o[c] = f16_from_f32((row[c] * inv) * w[c]);
103}
104
105// rope table: cs[t][i] = (cos, sin) of t * base^(-2i/D), i < D/2, in double
106__global__ void rope_table_kernel(int T, double base, float2* __restrict__ cs) {
107    const int idx = blockIdx.x * blockDim.x + threadIdx.x;
108    if (idx >= T * (HD / 2)) return;
109    const int t = idx / (HD / 2), i = idx % (HD / 2);
110    const double a = (double) t * pow(base, -2.0 * i / HD);
111    cs[idx] = make_float2((float) cos(a), (float) sin(a));
112}
113
114// one block of 128 threads per (token, head) of q and k: per-head RMSNorm * w, NEOX rope, f16, head-major out;
115// heads H + KV + KV: q heads, k heads, then v heads (only cast)
116__global__ void qk_rope_kernel(const float* __restrict__ qkv, int T, int H, int KV, const float* __restrict__ qw,
117                               const float* __restrict__ kw, float eps, const float2* __restrict__ cs,
118                               uint16_t* __restrict__ q16, uint16_t* __restrict__ k16, uint16_t* __restrict__ v16) {
119    __shared__ float sh[HD];
120    __shared__ float red[HD];
121    const int t = blockIdx.x, hh = blockIdx.y, d = threadIdx.x;
122    const int width = (H + 2 * KV) * HD;
123    const float v = qkv[(size_t) t * width + (size_t) hh * HD + d];
124    if (hh >= H + KV) {                                   // v: cast only
125        v16[((size_t) (hh - H - KV) * T + t) * HD + d] = f16_from_f32(v);
126        return;
127    }
128    red[d] = v * v;
129    __syncthreads();
130    for (int s = HD / 2; s > 0; s >>= 1) {
131        if (d < s) red[d] += red[d + s];
132        __syncthreads();
133    }
134    const float inv = 1.0f / sqrtf(red[0] / (float) HD + eps);
135    const float* w = hh < H ? qw : kw;
136    sh[d] = (v * inv) * w[d];
137    __syncthreads();
138    const int i = d < HD / 2 ? d : d - HD / 2;
139    const float2 c = cs[(size_t) t * (HD / 2) + i];
140    const float a = sh[i], b = sh[i + HD / 2];
141    const float r = d < HD / 2 ? a * c.x - b * c.y : a * c.y + b * c.x;
142    if (hh < H) q16[((size_t) hh * T + t) * HD + d] = f16_from_f32(r);
143    else k16[((size_t) (hh - H) * T + t) * HD + d] = f16_from_f32(r);
144}
145
146// causal softmax over rows of S (f32 [rows][ld], row j of the chunk is query q0 + (j % qc)), scale first, -> f16 P with
147// the same layout; columns past the query are 0.
148__global__ void softmax_causal_kernel(const float* __restrict__ S, int ld, int ncols, int qc, int q0, float scale,
149                                      uint16_t* __restrict__ P) {
150    __shared__ float sh[256];
151    const int row = blockIdx.x;
152    const int q = q0 + row % qc;
153    const int valid = min(q + 1, ncols);
154    const float* s = S + (size_t) row * ld;
155    float m = -INFINITY;
156    for (int c = threadIdx.x; c < valid; c += 256) m = fmaxf(m, s[c] * scale);
157    m = block_max256(m, sh);
158    float sum = 0.f;
159    for (int c = threadIdx.x; c < valid; c += 256) sum += expf(s[c] * scale - m);
160    sum = block_sum256(sum, sh);
161    const float inv = 1.0f / sum;
162    uint16_t* p = P + (size_t) row * ld;
163    for (int c = threadIdx.x; c < ncols; c += 256) p[c] = c < valid ? f16_from_f32(expf(s[c] * scale - m) * inv) : (uint16_t) 0;
164}
165
166__global__ void swiglu_f16_kernel(const float* __restrict__ gu, int T, int F, uint16_t* __restrict__ out) {
167    const size_t n = (size_t) T * F;
168    for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (size_t) gridDim.x * blockDim.x) {
169        const size_t t = i / F, f = i % F;
170        const float g = gu[t * 2 * F + f], u = gu[t * 2 * F + F + f];
171        out[i] = f16_from_f32((g / (1.0f + expf(-g))) * u);
172    }
173}
174
175__global__ void cast_f16_kernel(const float* __restrict__ in, size_t n, uint16_t* __restrict__ out) {
176    for (size_t i = (size_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (size_t) gridDim.x * blockDim.x)
177        out[i] = f16_from_f32(in[i]);
178}
179
180unsigned grid_for(size_t n) { return (unsigned) std::min<size_t>((n + 255) / 256, 65535u * 8); }
181
182struct WeightRef { uint32_t type = 0; size_t off = 0; int64_t ne0 = 0, rows = 0; };
183
184struct Layer {
185    WeightRef q, k, v, o, gate, up, down;
186    size_t attn_norm = 0, ffn_norm = 0, q_norm = 0, k_norm = 0;    // float offsets into the norm buffer
187};
188
189}  // namespace
190
191struct Qwen3VlTe {
192    std::unique_ptr<strata::GgufFile> file;
193    int device = 0;
194    int n_layer = 0, C = 0, F = 0, H = 0, KV = 0;
195    float eps = 1e-6f;
196    double theta = 5e6;
197    std::vector<Layer> layers;
198    const strata::TensorInfo* embd = nullptr;
199    cudaStream_t stream = nullptr;
200    cublasHandle_t blas = nullptr;
201    uint8_t* d_w = nullptr;            // resident: every layer weight, raw blocks; streamed: two layer slots
202    float* d_norm = nullptr;           // every 1-D norm weight, f32
203    uint16_t* d_stage = nullptr;       // one decoded f16 weight group ([Wq; Wk; Wv] or [Wgate; Wup] or Wo / Wdown)
204    size_t stage_elems = 0;
205    size_t weight_bytes = 0, norm_bytes = 0;
206    double read_ms = 0, upload_ms = 0;
207    // uploads: the file's bytes go through two pinned chunks (copied into them by several threads), then async copies
208    bool streamed = false;
209    std::vector<std::pair<const strata::TensorInfo*, size_t>> plan;   // tensor, offset in the resident layout
210    std::vector<size_t> layer_base;    // resident offset of each layer's first weight; a layer's weights are contiguous
211    size_t slot_bytes = 0;             // the largest layer
212    cudaStream_t copy = nullptr;
213    uint8_t* pinned[2] = {nullptr, nullptr};
214    cudaEvent_t pin_ev[2] = {nullptr, nullptr}, up_ev[2] = {nullptr, nullptr}, done_ev[2] = {nullptr, nullptr};
215    int pin_next = 0, threads = 1;
216};
217
218namespace {
219
220std::string find_weight(Qwen3VlTe* te, const std::string& name, int64_t ne0, int64_t rows, WeightRef& w, size_t& off,
221                        std::vector<std::pair<const strata::TensorInfo*, size_t>>& plan) {
222    const strata::TensorInfo* t = te->file->find(name);
223    if (!t) return "qwen3vl_te: tensor " + name + " missing";
224    if (t->shape.size() != 2 || (int64_t) t->shape[0] != ne0 || (int64_t) t->shape[1] != rows)
225        return "qwen3vl_te: tensor " + name + " has an unexpected shape";
226    const size_t rb = te_row_bytes(t->type, ne0);
227    if (rb == 0) return "qwen3vl_te: tensor " + name + " has type " + t->type_name() + ", which the encoder does not read";
228    w = {t->type, off, ne0, rows};
229    plan.emplace_back(t, off);
230    off += (rb * rows + 255) / 256 * 256;
231    return std::string();
232}
233
234std::string find_norm(Qwen3VlTe* te, const std::string& name, int64_t n, size_t& at, std::vector<float>& host) {
235    const strata::TensorInfo* t = te->file->find(name);
236    if (!t) return "qwen3vl_te: tensor " + name + " missing";
237    if ((int64_t) t->elements() != n) return "qwen3vl_te: tensor " + name + " has an unexpected size";
238    at = host.size();
239    host.resize(at + (size_t) n);
240    return te_dequant_f32_host(t->type, te->file->tensor_data(*t), n, 1, host.data() + at);
241}
242
243constexpr size_t PIN_CHUNK = 32u << 20;   // bytes per pinned chunk (two of them)
244constexpr double RESIDENT_MIN_GIB = 14.0; // cards with at least this much TOTAL memory keep the weights resident
245
246// host bytes -> device, async on te->copy through the two pinned chunks; the host copy into a chunk is split over
247// te->threads threads (the mapped file's pages fault in in parallel).  The bytes on the device are the file's bytes,
248// whichever way they travel.
249std::string upload(Qwen3VlTe* te, uint8_t* dst, const uint8_t* src, size_t n) {
250    for (size_t done = 0; done < n;) {
251        const int b = te->pin_next;
252        te->pin_next ^= 1;
253        TE_CUDA(cudaEventSynchronize(te->pin_ev[b]));          // the chunk's previous copy has left it
254        const size_t c = std::min(PIN_CHUNK, n - done);
255        const int nt = std::max(1, std::min<int>(te->threads, (int) (c >> 20)));
256        std::vector<std::thread> pool;
257        const size_t part = (c + nt - 1) / nt;
258        for (int t = 0; t < nt; ++t) {
259            const size_t a = (size_t) t * part, e = std::min(c, a + part);
260            if (a < e) pool.emplace_back([=] { std::memcpy(te->pinned[b] + a, src + done + a, e - a); });
261        }
262        for (auto& th : pool) th.join();
263        TE_CUDA(cudaMemcpyAsync(dst + done, te->pinned[b], c, cudaMemcpyHostToDevice, te->copy));
264        TE_CUDA(cudaEventRecord(te->pin_ev[b], te->copy));
265        done += c;
266    }
267    return std::string();
268}
269
270// streamed: layer li's weights into slot li % 2, after the compute stream is done with the layer that used it
271std::string issue_layer(Qwen3VlTe* te, int li) {
272    if (li >= te->n_layer) return std::string();
273    const int s = li & 1;
274    TE_CUDA(cudaStreamWaitEvent(te->copy, te->done_ev[s], 0));
275    const size_t base = te->layer_base[li];
276    for (int k = 0; k < 7; ++k) {
277        const auto& [t, o] = te->plan[(size_t) li * 7 + k];
278        TE_TRY(upload(te, te->d_w + (size_t) s * te->slot_bytes + (o - base), te->file->tensor_data(*t),
279                      te_row_bytes(t->type, (int64_t) t->shape[0]) * t->shape[1]));
280    }
281    TE_CUDA(cudaEventRecord(te->up_ev[s], te->copy));
282    return std::string();
283}
284
285std::string meta_int(const strata::GgufFile& f, const std::string& key, int& v) {
286    const strata::MetaValue* m = f.get(key);
287    if (!m || !m->is_num()) return "qwen3vl_te: metadata " + key + " missing";
288    v = (int) m->num();
289    return std::string();
290}
291
292std::string open_impl(Qwen3VlTe* te, const std::string& path, int device, int mode) {
293    const auto t0 = std::chrono::steady_clock::now();
294    te->file = std::make_unique<strata::GgufFile>(path);
295    const strata::GgufFile& f = *te->file;
296    const strata::MetaValue* arch = f.get("general.architecture");
297    if (!arch || arch->s != "qwen3vl") return "qwen3vl_te: " + path + " is not a qwen3vl GGUF";
298    int hd = 0;
299    TE_TRY(meta_int(f, "qwen3vl.block_count", te->n_layer));
300    TE_TRY(meta_int(f, "qwen3vl.embedding_length", te->C));
301    TE_TRY(meta_int(f, "qwen3vl.feed_forward_length", te->F));
302    TE_TRY(meta_int(f, "qwen3vl.attention.head_count", te->H));
303    TE_TRY(meta_int(f, "qwen3vl.attention.head_count_kv", te->KV));
304    TE_TRY(meta_int(f, "qwen3vl.attention.key_length", hd));
305    if (const strata::MetaValue* m = f.get("qwen3vl.rope.freq_base")) te->theta = m->num();
306    if (hd != HD || te->H * HD != te->C || te->H % te->KV != 0) return "qwen3vl_te: unexpected attention geometry";
307    te->eps = 1e-6f;   // sd.cpp llm.hpp: config.rms_norm_eps for QWEN3_VL (the file says 9.99999997e-07, the same f32)
308    te->embd = f.find("token_embd.weight");
309    if (!te->embd || te_row_bytes(te->embd->type, te->C) == 0) return "qwen3vl_te: token_embd.weight missing or unreadable";
310
311    const int C = te->C, F = te->F, Q = te->H * HD, K = te->KV * HD;
312    std::vector<std::pair<const strata::TensorInfo*, size_t>>& plan = te->plan;
313    std::vector<float> norms;
314    size_t off = 0;
315    te->layers.resize(te->n_layer);
316    for (int i = 0; i < te->n_layer; ++i) {
317        Layer& L = te->layers[i];
318        te->layer_base.push_back(off);
319        const std::string p = "blk." + std::to_string(i) + ".";
320        TE_TRY(find_weight(te, p + "attn_q.weight", C, Q, L.q, off, plan));
321        TE_TRY(find_weight(te, p + "attn_k.weight", C, K, L.k, off, plan));
322        TE_TRY(find_weight(te, p + "attn_v.weight", C, K, L.v, off, plan));
323        TE_TRY(find_weight(te, p + "attn_output.weight", Q, C, L.o, off, plan));
324        TE_TRY(find_weight(te, p + "ffn_gate.weight", C, F, L.gate, off, plan));
325        TE_TRY(find_weight(te, p + "ffn_up.weight", C, F, L.up, off, plan));
326        TE_TRY(find_weight(te, p + "ffn_down.weight", F, C, L.down, off, plan));
327        TE_TRY(find_norm(te, p + "attn_norm.weight", C, L.attn_norm, norms));
328        TE_TRY(find_norm(te, p + "ffn_norm.weight", C, L.ffn_norm, norms));
329        TE_TRY(find_norm(te, p + "attn_q_norm.weight", HD, L.q_norm, norms));
330        TE_TRY(find_norm(te, p + "attn_k_norm.weight", HD, L.k_norm, norms));
331    }
332    te->weight_bytes = off;
333    for (int i = 0; i < te->n_layer; ++i)
334        te->slot_bytes = std::max(te->slot_bytes, (i + 1 < te->n_layer ? te->layer_base[i + 1] : off) - te->layer_base[i]);
335    te->norm_bytes = norms.size() * sizeof(float);
336    te->stage_elems = std::max<size_t>({(size_t) (Q + 2 * K) * C, (size_t) 2 * F * C, (size_t) C * Q, (size_t) C * F});
337
338    if (device >= 0) TE_CUDA(cudaSetDevice(device));
339    TE_CUDA(cudaGetDevice(&te->device));
340    size_t free_b = 0, total_b = 0;
341    TE_CUDA(cudaMemGetInfo(&free_b, &total_b));
342    te->streamed = mode == 2 || (mode == 0 && total_b / 1073741824.0 < RESIDENT_MIN_GIB);   // never free memory
343    TE_CUDA(cudaStreamCreateWithFlags(&te->stream, cudaStreamNonBlocking));
344    TE_CUDA(cudaStreamCreateWithFlags(&te->copy, cudaStreamNonBlocking));
345    for (int b = 0; b < 2; ++b) {
346        TE_CUDA(cudaMallocHost((void**) &te->pinned[b], PIN_CHUNK));
347        TE_CUDA(cudaEventCreateWithFlags(&te->pin_ev[b], cudaEventDisableTiming));
348        TE_CUDA(cudaEventCreateWithFlags(&te->up_ev[b], cudaEventDisableTiming));
349        TE_CUDA(cudaEventCreateWithFlags(&te->done_ev[b], cudaEventDisableTiming));
350    }
351    TE_BLAS(cublasCreate(&te->blas));
352    TE_BLAS(cublasSetStream(te->blas, te->stream));
353    TE_CUDA(cudaMalloc((void**) &te->d_w, te->streamed ? 2 * te->slot_bytes : te->weight_bytes));
354    TE_CUDA(cudaMalloc((void**) &te->d_norm, te->norm_bytes));
355    TE_CUDA(cudaMalloc((void**) &te->d_stage, te->stage_elems * sizeof(uint16_t)));
356    const auto t1 = std::chrono::steady_clock::now();
357    if (!te->streamed)
358        for (const auto& [t, o] : plan)
359            TE_TRY(upload(te, te->d_w + o, f.tensor_data(*t), te_row_bytes(t->type, (int64_t) t->shape[0]) * t->shape[1]));
360    TE_TRY(upload(te, reinterpret_cast<uint8_t*>(te->d_norm), reinterpret_cast<const uint8_t*>(norms.data()), te->norm_bytes));
361    TE_CUDA(cudaStreamSynchronize(te->copy));
362    const auto t2 = std::chrono::steady_clock::now();
363    te->read_ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
364    te->upload_ms = std::chrono::duration<double, std::milli>(t2 - t1).count();
365    return std::string();
366}
367
368// Y[T][N] (f32, ldc = ldy) = X16[T][K] . W16[N][K]^T (+ Y when accumulate)
369std::string gemm(Qwen3VlTe* te, const uint16_t* x16, int T, int K, const uint16_t* w16, int N, float* y, int ldy,
370                 bool accumulate) {
371    const float one = 1.f, beta = accumulate ? 1.f : 0.f;
372    TE_BLAS(cublasGemmEx(te->blas, CUBLAS_OP_T, CUBLAS_OP_N, N, T, K, &one, w16, CUDA_R_16F, K, x16, CUDA_R_16F, K, &beta,
373                         y, CUDA_R_32F, ldy, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT));
374    return std::string();
375}
376
377std::string decode(Qwen3VlTe* te, int li, const WeightRef& w, uint16_t* dst) {
378    const uint8_t* src = te->streamed ? te->d_w + (size_t) (li & 1) * te->slot_bytes + (w.off - te->layer_base[li])
379                                      : te->d_w + w.off;
380    return te_dequant_f16(w.type, src, w.ne0, w.rows, dst, te->stream);
381}
382
383struct Work {   // per-encode device buffers
384    std::vector<void*> ptrs;
385    size_t bytes = 0;
386    ~Work() { for (void* p : ptrs) cudaFree(p); }
387    template <class T> std::string get(T** p, size_t n) {
388        TE_CUDA(cudaMalloc((void**) p, std::max<size_t>(n, 1) * sizeof(T)));
389        ptrs.push_back(*p);
390        bytes += std::max<size_t>(n, 1) * sizeof(T);
391        return std::string();
392    }
393};
394
395std::string encode_impl(Qwen3VlTe* te, const int32_t* ids, int T, float* out, Qwen3VlTeStats* st) {
396    const int C = te->C, F = te->F, H = te->H, KV = te->KV, Q = H * HD, KD = KV * HD, R = H / KV;
397    const int vocab = (int) te->embd->shape[1];
398    std::vector<float> emb((size_t) T * C);
399    const size_t erb = te_row_bytes(te->embd->type, C);
400    for (int t = 0; t < T; ++t) {
401        if (ids[t] < 0 || ids[t] >= vocab) return "qwen3vl_te: token id " + std::to_string(ids[t]) + " outside the vocabulary";
402        TE_TRY(te_dequant_f32_host(te->embd->type, te->file->tensor_data(*te->embd) + (size_t) ids[t] * erb, C, 1,
403                                   emb.data() + (size_t) t * C));
404    }
405    TE_CUDA(cudaSetDevice(te->device));
406    Work wk;
407    float *x, *qkv, *att, *gu, *S;
408    uint16_t *h16, *q16, *k16, *v16, *a16, *P;
409    float2* cs;
410    const int qc = std::min(T, QCHUNK);
411    TE_TRY(wk.get(&x, (size_t) T * C));
412    TE_TRY(wk.get(&h16, (size_t) T * std::max(C, Q)));
413    TE_TRY(wk.get(&qkv, (size_t) T * (Q + 2 * KD)));
414    TE_TRY(wk.get(&q16, (size_t) T * Q));
415    TE_TRY(wk.get(&k16, (size_t) T * KD));
416    TE_TRY(wk.get(&v16, (size_t) T * KD));
417    TE_TRY(wk.get(&att, (size_t) T * Q));
418    TE_TRY(wk.get(&gu, (size_t) T * 2 * F));
419    TE_TRY(wk.get(&a16, (size_t) T * F));
420    TE_TRY(wk.get(&S, (size_t) KV * qc * T));
421    TE_TRY(wk.get(&P, (size_t) KV * qc * T));
422    TE_TRY(wk.get(&cs, (size_t) T * (HD / 2)));
423    cudaEvent_t e0, e1;
424    TE_CUDA(cudaEventCreate(&e0));
425    TE_CUDA(cudaEventCreate(&e1));
426    TE_CUDA(cudaEventRecord(e0, te->stream));
427    TE_CUDA(cudaMemcpyAsync(x, emb.data(), emb.size() * sizeof(float), cudaMemcpyHostToDevice, te->stream));
428    rope_table_kernel<<<(T * (HD / 2) + 255) / 256, 256, 0, te->stream>>>(T, te->theta, cs);
429    const float scale = 1.0f / sqrtf((float) HD);
430    const float one = 1.f, zero = 0.f;
431    uint16_t* W = te->d_stage;
432    if (te->streamed) {
433        TE_TRY(issue_layer(te, 0));
434        TE_TRY(issue_layer(te, 1));
435    }
436    for (int li = 0; li < te->n_layer; ++li) {
437        const Layer& L = te->layers[li];
438        const float* nw = te->d_norm;
439        if (te->streamed) TE_CUDA(cudaStreamWaitEvent(te->stream, te->up_ev[li & 1], 0));
440        // attention
441        rms_f16_kernel<<<T, 256, 0, te->stream>>>(x, nw + L.attn_norm, C, te->eps, h16);
442        TE_TRY(decode(te, li, L.q, W));
443        TE_TRY(decode(te, li, L.k, W + (size_t) Q * C));
444        TE_TRY(decode(te, li, L.v, W + (size_t) (Q + KD) * C));
445        TE_TRY(gemm(te, h16, T, C, W, Q + 2 * KD, qkv, Q + 2 * KD, false));
446        qk_rope_kernel<<<dim3(T, H + 2 * KV), HD, 0, te->stream>>>(qkv, T, H, KV, nw + L.q_norm, nw + L.k_norm, te->eps,
447                                                                   cs, q16, k16, v16);
448        for (int q0 = 0; q0 < T; q0 += QCHUNK) {
449            const int n = std::min(QCHUNK, T - q0);
450            const int kn = q0 + n;                      // keys 0 .. kn-1 (causal)
451            for (int r = 0; r < R; ++r) {
452                // S[g][j][c] = q(head g R + r, query q0 + j) . k(group g, key c)
453                TE_BLAS(cublasGemmStridedBatchedEx(
454                    te->blas, CUBLAS_OP_T, CUBLAS_OP_N, kn, n, HD, &one, k16, CUDA_R_16F, HD, (long long) T * HD,
455                    q16 + ((size_t) r * T + q0) * HD, CUDA_R_16F, HD, (long long) R * T * HD, &zero, S, CUDA_R_32F, kn,
456                    (long long) n * kn, KV, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT));
457                softmax_causal_kernel<<<KV * n, 256, 0, te->stream>>>(S, kn, kn, n, q0, scale, P);
458                // O(head g R + r, query q0 + j) = P[g][j] . v(group g): written into att[q0 + j][(g R + r) HD ..]
459                TE_BLAS(cublasGemmStridedBatchedEx(
460                    te->blas, CUBLAS_OP_N, CUBLAS_OP_N, HD, n, kn, &one, v16, CUDA_R_16F, HD, (long long) T * HD, P,
461                    CUDA_R_16F, kn, (long long) n * kn, &zero, att + (size_t) q0 * Q + (size_t) r * HD, CUDA_R_32F, Q,
462                    (long long) R * HD, KV, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT));
463            }
464        }
465        cast_f16_kernel<<<grid_for((size_t) T * Q), 256, 0, te->stream>>>(att, (size_t) T * Q, h16);
466        TE_TRY(decode(te, li, L.o, W));
467        TE_TRY(gemm(te, h16, T, Q, W, C, x, C, true));
468        // feed-forward
469        rms_f16_kernel<<<T, 256, 0, te->stream>>>(x, nw + L.ffn_norm, C, te->eps, h16);
470        TE_TRY(decode(te, li, L.gate, W));
471        TE_TRY(decode(te, li, L.up, W + (size_t) F * C));
472        TE_TRY(gemm(te, h16, T, C, W, 2 * F, gu, 2 * F, false));
473        swiglu_f16_kernel<<<grid_for((size_t) T * F), 256, 0, te->stream>>>(gu, T, F, a16);
474        TE_TRY(decode(te, li, L.down, W));
475        TE_TRY(gemm(te, a16, T, F, W, C, x, C, true));
476        if (te->streamed) {                           // slot li % 2 is free once this layer's decodes are done
477            TE_CUDA(cudaEventRecord(te->done_ev[li & 1], te->stream));
478            TE_TRY(issue_layer(te, li + 2));
479        }
480    }
481    TE_CUDA(cudaGetLastError());
482    TE_CUDA(cudaMemcpyAsync(out, x, (size_t) T * C * sizeof(float), cudaMemcpyDeviceToHost, te->stream));
483    TE_CUDA(cudaEventRecord(e1, te->stream));
484    TE_CUDA(cudaStreamSynchronize(te->stream));
485    float ms = 0;
486    cudaEventElapsedTime(&ms, e0, e1);
487    cudaEventDestroy(e0);
488    cudaEventDestroy(e1);
489    for (size_t i = 0; i < (size_t) T * C; ++i)
490        if (!std::isfinite(out[i])) return "qwen3vl_te: the condition has a non-finite value";
491    if (st) {
492        st->encode_ms = ms;
493        st->weight_bytes = te->streamed ? 2 * te->slot_bytes : te->weight_bytes;
494        st->peak_bytes = st->weight_bytes + te->norm_bytes + te->stage_elems * sizeof(uint16_t) + wk.bytes;
495        st->streamed = te->streamed;
496    }
497    return std::string();
498}
499
500}  // namespace
501
502Qwen3VlTe* qwen3vl_te_open(const std::string& gguf_path, int device, std::string* err, int mode, int threads) {
503    auto* te = new Qwen3VlTe();
504    te->threads = threads > 0 ? threads : (int) std::min(8u, std::max(1u, std::thread::hardware_concurrency()));
505    std::string e;
506    try {
507        e = open_impl(te, gguf_path, device, mode);
508    } catch (const std::exception& ex) {
509        e = std::string("qwen3vl_te: ") + ex.what();
510    }
511    if (!e.empty()) {
512        if (err) *err = e;
513        qwen3vl_te_close(te);
514        return nullptr;
515    }
516    return te;
517}
518
519int qwen3vl_te_hidden(const Qwen3VlTe* te) { return te ? te->C : 0; }
520
521std::string qwen3vl_te_encode(Qwen3VlTe* te, const int32_t* ids, int n, float* out, Qwen3VlTeStats* stats) {
522    if (!te || n <= 0) return "qwen3vl_te: nothing to encode";
523    try {
524        return encode_impl(te, ids, n, out, stats);
525    } catch (const std::exception& ex) {
526        return std::string("qwen3vl_te: ") + ex.what();
527    }
528}
529
530std::string qwen3vl_te_open_report(const Qwen3VlTe* te) {
531    char b[160];
532    std::snprintf(b, sizeof b, "%s, read %.0f ms, upload %.0f ms (%.2f GB of weights%s)",
533                  te->streamed ? "streamed" : "resident", te->read_ms, te->upload_ms, te->weight_bytes / 1e9,
534                  te->streamed ? ", uploaded per layer at every encode" : "");
535    return b;
536}
537
538void qwen3vl_te_close(Qwen3VlTe* te) {
539    if (!te) return;
540    if (te->copy) cudaStreamSynchronize(te->copy);
541    if (te->stream) cudaStreamSynchronize(te->stream);
542    for (int b = 0; b < 2; ++b) {
543        if (te->pinned[b]) cudaFreeHost(te->pinned[b]);
544        if (te->pin_ev[b]) cudaEventDestroy(te->pin_ev[b]);
545        if (te->up_ev[b]) cudaEventDestroy(te->up_ev[b]);
546        if (te->done_ev[b]) cudaEventDestroy(te->done_ev[b]);
547    }
548    if (te->copy) cudaStreamDestroy(te->copy);
549    if (te->d_w) cudaFree(te->d_w);
550    if (te->d_norm) cudaFree(te->d_norm);
551    if (te->d_stage) cudaFree(te->d_stage);
552    if (te->blas) cublasDestroy(te->blas);
553    if (te->stream) cudaStreamDestroy(te->stream);
554    delete te;
555}
556
557}  // namespace strata::image