okami.mom/strata

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

Niko1221Merge f-own-3v (88fc47ccf) into f-own-int: --tower auto uses our tower on every CUDA class above 1,024 tokens4ef5079f5

main
31.5 KiB606 linesraw
1// tools/vision/own/vit_sycl.cpp - the VitGpu class (vit_gpu.h) on an Intel GPU: SYCL kernels and oneMKL products (own-stack phase 3, OWN-3V part B).
2//
3// A line-for-line counterpart of vit_gpu.cu (CUDA / HIP): the same host flow, weights as stored (BF16 / F16; F32 matrices become BF16, Q8_0 becomes F16), the same
4// row chunking, the same 16-bit types (F16 q, k, v with 1/sqrt(head size) in q, F16 scores turned into F16 probabilities in place, float32 residual stream,
5// 16-bit product inputs with float32 results) and the same diagnostics (STRATA_VIT_REF_ROUND, STRATA_VIT_ROWS, STRATA_VIT_SCORES, STRATA_VIT_PROF).
6// Two differences, both forced by oneMKL on the Arc (RESULTS-OWN-3V.md 11):
7//   - the P*V product writes the attention context head by head, ctx[h][token][j] (oneMKL refuses batched outputs that interleave), and the o-projection's
8//     cast reads it back into the token-major 16-bit input (the same numbers);
9//   - the score chunk is larger than on CUDA (oneMKL's batched products with an inner size of 72 are slow on small chunks), sized so the reader's device memory
10//     stays at or below mtmd-SYCL's.
11// No atomics: every reduction is a work-group reduction of a fixed work-group size, and oneMKL gave one result in eight launches on every shape used here.
12#include "vit_gpu.h"
13
14#include <sycl/sycl.hpp>
15#include <oneapi/mkl.hpp>
16
17#include <algorithm>
18#include <cfloat>
19#include <chrono>
20#include <cmath>
21#include <cstdint>
22#include <cstdio>
23#include <cstdlib>
24#include <cstring>
25
26namespace strata_vit {
27
28namespace {
29
30namespace blas = oneapi::mkl::blas::column_major;
31using oneapi::mkl::transpose;
32using half = sycl::half;
33using bf16 = sycl::ext::oneapi::bfloat16;
34
35enum Kind { K_F32 = 0, K_F16 = 1, K_BF16 = 2 };   // the 16-bit kind a product's input takes (its weight's)
36
37struct DevW {            // a weight matrix [rows = out][cols = in] on the device
38    void* p = nullptr;
39    Kind kind = K_BF16;
40    int rows = 0, cols = 0;
41};
42
43struct DevLayer {
44    float *ln1_w = nullptr, *ln1_b = nullptr, *ln2_w = nullptr, *ln2_b = nullptr, *qkv_b = nullptr, *o_b = nullptr, *up_b = nullptr, *down_b = nullptr;
45    DevW qkv, o, up, down;
46};
47
48inline uint16_t f_to_bf16(float f) {          // round to nearest even
49    uint32_t u = sycl::bit_cast<uint32_t>(f);
50    if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 0x40);   // NaN stays NaN
51    u += 0x7fffu + ((u >> 16) & 1u);
52    return (uint16_t) (u >> 16);
53}
54inline uint16_t f_to_f16bits(float f) { return sycl::bit_cast<uint16_t>(half(f)); }
55inline float f16bits_to_f(uint16_t u) { return (float) sycl::bit_cast<half>(u); }
56
57inline void store_kind(void* out, size_t i, float v, int kind) {
58    if (kind == K_F32) ((float*) out)[i] = v;
59    else if (kind == K_F16) ((uint16_t*) out)[i] = f_to_f16bits(v);
60    else ((uint16_t*) out)[i] = f_to_bf16(v);
61}
62
63constexpr int kSoftmaxThreads = 256, kSoftmaxPer = 64;
64
65uint16_t host_f32_to_bf16(float f) {
66    uint32_t u;
67    std::memcpy(&u, &f, 4);
68    if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 0x40);
69    u += 0x7fffu + ((u >> 16) & 1u);
70    return (uint16_t) (u >> 16);
71}
72uint16_t host_f32_to_f16(float f) {
73    const half h(f);
74    uint16_t u;
75    std::memcpy(&u, &h, 2);
76    return u;
77}
78
79// ---- kernels (the CUDA kernels of vit_gpu.cu; one work-group of `T` items per row unless said otherwise) ----
80
81// x[t] += patch bias + the position table resized (bilinear, align corners) to the token's grid position
82void k_patch_post(sycl::queue& q, float* x, const float* bias, const float* pos, int G, int pw, int ph, int nbx, int D, int N) {
83    q.parallel_for(sycl::nd_range<1>((size_t) N * 256, 256), [=](sycl::nd_item<1> it) {
84        const int t = (int) it.get_group(0), b = t / 4, r = t % 4;
85        const int ty = 2 * (b / nbx) + r / 2, tx = 2 * (b % nbx) + r % 2;
86        float sfx = (float) pw / G, sfy = (float) ph / G;
87        if (pw > 1 && G > 1) sfx = (float) (pw - 1) / (G - 1);
88        if (ph > 1 && G > 1) sfy = (float) (ph - 1) / (G - 1);
89        const float fy = (float) ty / sfy, fx = (float) tx / sfx;
90        int y0 = (int) sycl::floor(fy), x0 = (int) sycl::floor(fx), y1 = y0 + 1, x1 = x0 + 1;
91        y0 = sycl::max(0, sycl::min(y0, G - 1)); y1 = sycl::max(0, sycl::min(y1, G - 1));
92        x0 = sycl::max(0, sycl::min(x0, G - 1)); x1 = sycl::max(0, sycl::min(x1, G - 1));
93        const float dy = sycl::fmax(0.0f, sycl::fmin(fy - (float) y0, 1.0f)), dx = sycl::fmax(0.0f, sycl::fmin(fx - (float) x0, 1.0f));
94        const float* a = pos + ((size_t) y0 * G + x0) * D;
95        const float* bb = pos + ((size_t) y0 * G + x1) * D;
96        const float* c = pos + ((size_t) y1 * G + x0) * D;
97        const float* d = pos + ((size_t) y1 * G + x1) * D;
98        float* xr = x + (size_t) t * D;
99        for (int i = (int) it.get_local_id(0); i < D; i += 256)
100            xr[i] += bias[i] + (a[i] * (1 - dx) * (1 - dy) + bb[i] * dx * (1 - dy) + c[i] * (1 - dx) * dy + d[i] * dx * dy);
101    });
102}
103
104// out = LayerNorm(x) * w + b, into `kind`; rows rows of D
105void k_layernorm(sycl::queue& q, const float* x, const float* w, const float* b, float eps, int D, void* out, int kind, int rows) {
106    q.parallel_for(sycl::nd_range<1>((size_t) rows * 256, 256), [=](sycl::nd_item<1> it) {
107        const size_t row = it.get_group(0);
108        const int lid = (int) it.get_local_id(0);
109        const float* xr = x + row * D;
110        float s = 0.0f;
111        for (int i = lid; i < D; i += 256) s += xr[i];
112        const float mean = sycl::reduce_over_group(it.get_group(), s, sycl::plus<float>()) / (float) D;
113        float v = 0.0f;
114        for (int i = lid; i < D; i += 256) { const float d = xr[i] - mean; v += d * d; }
115        const float scale = sycl::rsqrt(sycl::reduce_over_group(it.get_group(), v, sycl::plus<float>()) / (float) D + eps);
116        for (int i = lid; i < D; i += 256) store_kind(out, row * D + i, (xr[i] - mean) * scale * w[i] + b[i], kind);
117    });
118}
119
120// y [rows][3D] (the fused qkv product of the tokens row0 ..) + bias -> q, k (rotary applied), v, each [N][D] in F16
121void k_qkv_rope(sycl::queue& q, const float* y, const float* bias, int row0, int nbx, int heads, int hd, float theta_scale, float qscale, uint16_t* qo, uint16_t* ko,
122                uint16_t* vo, int rows) {
123    q.parallel_for(sycl::nd_range<1>((size_t) rows * 256, 256), [=](sycl::nd_item<1> it) {
124        const int t = row0 + (int) it.get_group(0), D = heads * hd, half_ = hd / 2, quarter = hd / 4;
125        const int b = t / 4, r = t % 4;
126        const int ty = 2 * (b / nbx) + r / 2, tx = 2 * (b % nbx) + r % 2;
127        const float* yr = y + it.get_group(0) * 3 * (size_t) D;
128        const int lid = (int) it.get_local_id(0);
129        for (int i = lid; i < 2 * heads * half_; i += 256) {
130            const int part = i / (heads * half_), rem = i % (heads * half_), h = rem / half_, j = rem % half_;
131            const int base = part * D + h * hd;
132            const float a = yr[base + j] + bias[base + j], c = yr[base + j + half_] + bias[base + j + half_];
133            const float freq = sycl::pow(theta_scale, (float) (j % quarter));
134            const float ang = (float) (j < quarter ? ty : tx) * freq;
135            const float sn = sycl::sin(ang), cs = sycl::cos(ang);
136            uint16_t* dst = (part == 0 ? qo : ko) + (size_t) t * D + h * hd;
137            const float sc = part == 0 ? qscale : 1.0f;
138            dst[j] = f_to_f16bits((a * cs - c * sn) * sc);
139            dst[j + half_] = f_to_f16bits((a * sn + c * cs) * sc);
140        }
141        for (int e = lid; e < D; e += 256) vo[(size_t) t * D + e] = f_to_f16bits(yr[2 * D + e] + bias[2 * D + e]);
142    });
143}
144
145// In place: rows of n F16 scores become F16 probabilities.  T items and PER scores per item (T * PER >= n), the row held in registers.
146template <int T, int PER>
147void k_softmax_rows(sycl::queue& q, uint16_t* S, int n, int ld, int rows) {
148    q.parallel_for(sycl::nd_range<1>((size_t) rows * T, T), [=](sycl::nd_item<1> it) {
149        uint16_t* s = S + it.get_group(0) * (size_t) ld;
150        const int lid = (int) it.get_local_id(0);
151        float v[PER];
152        float m = -FLT_MAX;
153#pragma unroll
154        for (int k = 0; k < PER; ++k) {
155            const int j = lid + k * T;
156            v[k] = j < n ? f16bits_to_f(s[j]) : -FLT_MAX;
157            m = sycl::fmax(m, v[k]);
158        }
159        m = sycl::reduce_over_group(it.get_group(), m, sycl::maximum<float>());
160        float sum = 0.0f;
161#pragma unroll
162        for (int k = 0; k < PER; ++k) {
163            const int j = lid + k * T;
164            v[k] = j < n ? sycl::exp(v[k] - m) : 0.0f;
165            sum += v[k];
166        }
167        sum = sycl::reduce_over_group(it.get_group(), sum, sycl::plus<float>());
168        const float inv = 1.0f / sum;
169#pragma unroll
170        for (int k = 0; k < PER; ++k) {
171            const int j = lid + k * T;
172            if (j < n) s[j] = f_to_f16bits(v[k] * inv);
173        }
174    });
175}
176
177void softmax_rows(sycl::queue& q, uint16_t* S, int n, int ld, int rows) {
178    if (n <= 128) k_softmax_rows<64, 2>(q, S, n, ld, rows);
179    else if (n <= 512) k_softmax_rows<64, 8>(q, S, n, ld, rows);
180    else if (n <= 1024) k_softmax_rows<128, 8>(q, S, n, ld, rows);
181    else if (n <= 4096) k_softmax_rows<256, 16>(q, S, n, ld, rows);
182    else k_softmax_rows<256, 64>(q, S, n, ld, rows);
183}
184
185// a row too long for registers (more than 16,384 patches): three passes over the row in memory
186void k_softmax_rows_long(sycl::queue& q, uint16_t* S, int n, int ld, int rows) {
187    q.parallel_for(sycl::nd_range<1>((size_t) rows * kSoftmaxThreads, kSoftmaxThreads), [=](sycl::nd_item<1> it) {
188        uint16_t* s = S + it.get_group(0) * (size_t) ld;
189        const int lid = (int) it.get_local_id(0);
190        float m = -FLT_MAX;
191        for (int j = lid; j < n; j += kSoftmaxThreads) m = sycl::fmax(m, f16bits_to_f(s[j]));
192        m = sycl::reduce_over_group(it.get_group(), m, sycl::maximum<float>());
193        float sum = 0.0f;
194        for (int j = lid; j < n; j += kSoftmaxThreads) sum += sycl::exp(f16bits_to_f(s[j]) - m);
195        sum = sycl::reduce_over_group(it.get_group(), sum, sycl::plus<float>());
196        const float inv = 1.0f / sum;
197        for (int j = lid; j < n; j += kSoftmaxThreads) s[j] = f_to_f16bits(sycl::exp(f16bits_to_f(s[j]) - m) * inv);
198    });
199}
200
201size_t grid_for(size_t n) { return std::min<size_t>((n + 255) / 256, 65535) * 256; }
202
203// y[i] rounded to the 16-bit kind and back (STRATA_VIT_REF_ROUND)
204void k_round(sycl::queue& q, float* y, size_t n, int kind) {
205    const size_t g = grid_for(n);
206    q.parallel_for(sycl::nd_range<1>(g, 256), [=](sycl::nd_item<1> it) {
207        for (size_t i = it.get_global_id(0); i < n; i += g) {
208            const float v = y[i];
209            y[i] = kind == K_F16 ? (float) half(v) : sycl::bit_cast<float>((uint32_t) f_to_bf16(v) << 16);
210        }
211    });
212}
213
214// the head-major attention context ctx[h][token][j] (N tokens) of rows r0 .. r0 + rows to the token-major 16-bit input out[r][h * hd + j]
215void k_cast_ctx(sycl::queue& q, const float* ctx, int N, int heads, int hd, int r0, int rows, void* out, int kind) {
216    const int D = heads * hd;
217    q.parallel_for(sycl::nd_range<1>((size_t) rows * 256, 256), [=](sycl::nd_item<1> it) {
218        const int r = (int) it.get_group(0);
219        for (int e = (int) it.get_local_id(0); e < D; e += 256) {
220            const int h = e / hd, j = e % hd;
221            store_kind(out, (size_t) r * D + e, ctx[((size_t) h * N + (size_t) (r0 + r)) * hd + j], kind);
222        }
223    });
224}
225
226// x[r] += y[r] + bias
227void k_add_bias_res(sycl::queue& q, float* x, const float* y, const float* bias, int D, int rows) {
228    q.parallel_for(sycl::nd_range<1>((size_t) rows * 256, 256), [=](sycl::nd_item<1> it) {
229        const size_t base = it.get_group(0) * (size_t) D;
230        for (int i = (int) it.get_local_id(0); i < D; i += 256) x[base + i] += y[base + i] + bias[i];
231    });
232}
233
234// out = gelu_tanh(y + bias) into `kind`
235void k_bias_gelu_cast(sycl::queue& q, const float* y, const float* bias, int n, void* out, int kind, int rows) {
236    q.parallel_for(sycl::nd_range<1>((size_t) rows * 256, 256), [=](sycl::nd_item<1> it) {
237        const size_t base = it.get_group(0) * (size_t) n;
238        for (int i = (int) it.get_local_id(0); i < n; i += 256) {
239            const float x = y[base + i] + bias[i];
240            const float g = 0.5f * x * (1.0f + sycl::tanh(0.79788456080286535587989211986876f * x * (1.0f + 0.044715f * x * x)));
241            store_kind(out, base + i, g, kind);
242        }
243    });
244}
245
246// y[r] += bias
247void k_add_bias(sycl::queue& q, float* y, const float* bias, int n, int rows) {
248    q.parallel_for(sycl::nd_range<1>((size_t) rows * 256, 256), [=](sycl::nd_item<1> it) {
249        const size_t base = it.get_group(0) * (size_t) n;
250        for (int i = (int) it.get_local_id(0); i < n; i += 256) y[base + i] += bias[i];
251    });
252}
253
254// the GPU this reader uses: the Level Zero (else any) GPU with the most memory; ONEAPI_DEVICE_SELECTOR filters the list
255bool pick_gpu(sycl::device& out, std::string& why) {
256    try {
257        std::vector<sycl::device> gpus = sycl::device::get_devices(sycl::info::device_type::gpu);
258        if (gpus.empty()) { why = "no GPU found"; return false; }
259        auto score = [](const sycl::device& d) {
260            const bool l0 = d.get_backend() == sycl::backend::ext_oneapi_level_zero;
261            return std::make_pair(l0 ? 1 : 0, (unsigned long long) d.get_info<sycl::info::device::global_mem_size>());
262        };
263        out = *std::max_element(gpus.begin(), gpus.end(), [&](const sycl::device& a, const sycl::device& b) { return score(a) < score(b); });
264        if (!out.has(sycl::aspect::fp16)) { why = "the GPU has no 16-bit float support"; return false; }
265        return true;
266    } catch (const sycl::exception& e) {
267        why = std::string("no GPU runtime: ") + e.what();
268        return false;
269    }
270}
271
272}  // namespace
273
274struct VitGpuImpl {
275    VitGeometry g;
276    sycl::queue q;
277    std::string async_err;              // the first asynchronous error the queue reported
278    std::vector<void*> allocs;          // every device allocation (weights and work buffers), freed in the destructor
279    size_t bytes = 0, work_bytes = 0;
280    size_t n_weight_allocs = 0;
281
282    float *patch_w = nullptr, *patch_b = nullptr, *pos = nullptr, *post_w = nullptr, *post_b = nullptr, *mm0_b = nullptr, *mm2_b = nullptr;
283    DevW mm0, mm2;
284    std::vector<DevLayer> layers;
285
286    int cap_patches = 0;
287    float *d_x = nullptr, *d_ctx = nullptr, *d_y = nullptr, *d_out = nullptr;   // as vit_gpu.cu; d_ctx holds the context HEAD-MAJOR [H][N][HD]
288    uint16_t *d_a = nullptr, *d_f16 = nullptr;
289    uint16_t *d_q16 = nullptr, *d_k16 = nullptr, *d_v16 = nullptr;
290    uint16_t* d_S = nullptr;
291    size_t sp_elems = 0;
292    int kRows = 512;
293    // scores per attention chunk: 32M elements = 64 MB of F16 (CUDA: 8M).  oneMKL's batched products with an inner size of 72 need wide chunks to be fast
294    // on the Arc (RESULTS-OWN-3V.md 11.1); 64 MB keeps the reader at or below mtmd-SYCL's memory at 1,024 tokens.  STRATA_VIT_SCORES (M elements) overrides.
295    size_t kScoreElems = (size_t) 32 << 20;
296    size_t kScoreElemsLarge = (size_t) 256 << 20;   // above 16,384 patches: 256M scores (512 MB); A750, 16,384 tokens: 147.9 s at the 64-query floor, 118.3 s with 256M, 117.0 s with 512M
297    bool scores_env = false;                        // STRATA_VIT_SCORES given: one size for every picture
298    bool round_out = false;
299
300    ~VitGpuImpl() {
301        try {
302            q.wait();
303        } catch (...) {
304        }
305        for (void* p : allocs) sycl::free(p, q);
306    }
307    template <class T> bool alloc(T*& p, size_t n, std::string& err, bool weight) {
308        void* m = nullptr;
309        try {
310            m = sycl::malloc_device(n * sizeof(T), q);
311        } catch (const sycl::exception& e) {
312            err = std::string("GPU memory: ") + e.what();
313            return false;
314        }
315        if (!m) { err = "GPU memory: out of device memory"; return false; }
316        p = (T*) m;
317        allocs.push_back(m);
318        bytes += n * sizeof(T);
319        if (!weight) work_bytes += n * sizeof(T);
320        return true;
321    }
322    bool upload_f32(float*& dst, const Gguf& gg, const std::string& name, std::string& err) {
323        const GgufTensorInfo* t = gg.tensor(name);
324        if (!t) { err = "the mmproj file lacks the tensor " + name; return false; }
325        std::vector<float> h((size_t) t->nelem());
326        if (!gg.read_f32(*t, h.data(), err)) return false;
327        if (!alloc(dst, h.size(), err, true)) return false;
328        q.memcpy(dst, h.data(), h.size() * 4).wait();
329        return true;
330    }
331    bool upload_matrix(DevW& w, const Gguf& gg, const std::string& name, std::string& err) {
332        const GgufTensorInfo* t = gg.tensor(name);
333        if (!t || t->ne.size() != 2) { err = "the mmproj file lacks the matrix " + name; return false; }
334        w.cols = (int) t->ne[0];
335        w.rows = (int) t->ne[1];
336        const size_t n = (size_t) t->nelem();
337        std::vector<unsigned char> raw;
338        if (t->type == GT_F16 || t->type == GT_BF16) {          // as stored
339            raw.resize(n * 2);
340            if (!gg.read_raw(*t, raw.data(), err)) return false;
341            w.kind = t->type == GT_F16 ? K_F16 : K_BF16;
342        } else {                                                 // F32 -> BF16, Q8_0 -> F16
343            std::vector<float> f(n);
344            if (!gg.read_f32(*t, f.data(), err)) return false;
345            raw.resize(n * 2);
346            const bool bf = t->type == GT_F32;
347            w.kind = bf ? K_BF16 : K_F16;
348            for (size_t i = 0; i < n; ++i) {
349                const uint16_t u = bf ? host_f32_to_bf16(f[i]) : host_f32_to_f16(f[i]);
350                std::memcpy(&raw[i * 2], &u, 2);
351            }
352        }
353        uint16_t* dev = nullptr;
354        if (!alloc(dev, n, err, true)) return false;
355        w.p = dev;
356        q.memcpy(w.p, raw.data(), n * 2).wait();
357        return true;
358    }
359
360    // y[M][w.rows] (float32) = A[M][w.cols] (kind of w) * w^T
361    void gemm(const DevW& w, const void* A, int M, float* y) {
362        const int m = w.rows, k = w.cols;
363        if (w.kind == K_F32)
364            blas::gemm(q, transpose::trans, transpose::nontrans, m, M, k, 1.0f, (const float*) w.p, k, (const float*) A, k, 0.0f, y, m);
365        else if (w.kind == K_F16)
366            blas::gemm(q, transpose::trans, transpose::nontrans, m, M, k, 1.0f, (const half*) w.p, k, (const half*) A, k, 0.0f, y, m);
367        else
368            blas::gemm(q, transpose::trans, transpose::nontrans, m, M, k, 1.0f, (const bf16*) w.p, k, (const bf16*) A, k, 0.0f, y, m);
369        if (round_out && w.kind != K_F32) k_round(q, y, (size_t) M * w.rows, (int) w.kind);
370    }
371
372    bool size_buffers(int patches, std::string& err) {
373        if (patches <= cap_patches) return true;
374        q.wait();
375        for (size_t i = allocs.size(); i > n_weight_allocs; --i) sycl::free(allocs[i - 1], q);
376        bytes -= work_bytes;
377        work_bytes = 0;
378        allocs.resize(n_weight_allocs);
379        const size_t N = (size_t) patches, D = (size_t) g.width, F = (size_t) std::max(g.ffn, g.merger_hidden);
380        const size_t K0 = (size_t) 3 * g.patch * g.patch;
381        d_x = d_y = d_ctx = d_out = nullptr;
382        d_a = d_f16 = d_q16 = d_k16 = d_v16 = nullptr;
383        d_S = nullptr;
384        const size_t Np = (N + 7) / 8 * 8;
385        const size_t budget = (N > 16384 && !scores_env) ? kScoreElemsLarge : kScoreElems;
386        sp_elems = std::min<size_t>((size_t) g.heads * N * Np, std::max<size_t>(budget, (size_t) g.heads * Np * 64));
387        const size_t R = std::min<size_t>(N, (size_t) kRows);
388        const size_t ctx_elems = std::max({N * D, N * K0, (N / 4) * (size_t) g.out_dim});
389        bool ok = alloc(d_x, N * D, err, false) && alloc(d_ctx, ctx_elems, err, false) && alloc(d_y, R * std::max<size_t>(3 * D, F), err, false) &&
390                  alloc(d_a, R * D, err, false) && alloc(d_f16, R * F, err, false) &&
391                  alloc(d_q16, N * D, err, false) && alloc(d_k16, N * D, err, false) && alloc(d_v16, N * D, err, false);
392        if (ok && !alloc(d_S, sp_elems, err, false)) {
393            // no room for the large chunk: the default chunk instead, slower, never an error
394            ok = false;
395            if (budget != kScoreElems) {
396                err.clear();
397                sp_elems = std::min<size_t>((size_t) g.heads * N * Np, std::max<size_t>(kScoreElems, (size_t) g.heads * Np * 64));
398                ok = alloc(d_S, sp_elems, err, false);
399            }
400        }
401        d_out = d_ctx;
402        if (!ok) { cap_patches = 0; return false; }
403        cap_patches = patches;
404        return true;
405    }
406};
407
408VitGpu::VitGpu() : impl_(new VitGpuImpl()) {}
409VitGpu::~VitGpu() = default;
410size_t VitGpu::device_bytes() const { return impl_->bytes; }
411
412bool VitGpu::available(std::string& why) {
413    sycl::device d;
414    return pick_gpu(d, why);
415}
416
417bool VitGpu::prefer_mtmd(bool bf16_matrices, int max_tokens, std::string& why) {
418    (void) bf16_matrices;
419    (void) max_tokens;
420    (void) why;
421    return false;
422}
423
424bool VitGpu::load(const Gguf& gg, const VitGeometry& g, int device, int max_patches, std::string& err) {
425    VitGpuImpl& m = *impl_;
426    (void) device;          // one GPU: the one pick_gpu chooses
427    std::string why;
428    if (!vit_geometry_supported(g, why)) { err = "this tower is not supported: " + why; return false; }
429    m.g = g;
430    sycl::device dev;
431    if (!pick_gpu(dev, why)) { err = "cannot use the GPU: " + why; return false; }
432    try {
433        std::string* sink = &m.async_err;
434        m.q = sycl::queue(dev, [sink](sycl::exception_list l) {
435            for (auto& e : l) {
436                try {
437                    std::rethrow_exception(e);
438                } catch (const std::exception& x) {
439                    if (sink->empty()) *sink = x.what();
440                }
441            }
442        }, sycl::property::queue::in_order());
443        {   // the patch embedding: the two temporal taps summed, kept in float32 (a small matrix)
444            const GgufTensorInfo* t0 = gg.tensor("v.patch_embd.weight");
445            if (!t0) { err = "the mmproj file lacks v.patch_embd.weight"; return false; }
446            std::vector<float> w0((size_t) t0->nelem()), w1;
447            if (!gg.read_f32(*t0, w0.data(), err)) return false;
448            if (g.patch_taps == 2) {
449                const GgufTensorInfo* t1 = gg.tensor("v.patch_embd.weight.1");
450                w1.resize(w0.size());
451                if (!t1 || !gg.read_f32(*t1, w1.data(), err)) { if (err.empty()) err = "the mmproj file lacks v.patch_embd.weight.1"; return false; }
452                for (size_t i = 0; i < w0.size(); ++i) w0[i] += w1[i];
453            }
454            if (!m.alloc(m.patch_w, w0.size(), err, true)) return false;
455            m.q.memcpy(m.patch_w, w0.data(), w0.size() * 4).wait();
456        }
457        if (!m.upload_f32(m.patch_b, gg, "v.patch_embd.bias", err) || !m.upload_f32(m.pos, gg, "v.position_embd.weight", err) ||
458            !m.upload_f32(m.post_w, gg, "v.post_ln.weight", err) || !m.upload_f32(m.post_b, gg, "v.post_ln.bias", err) ||
459            !m.upload_matrix(m.mm0, gg, "mm.0.weight", err) || !m.upload_f32(m.mm0_b, gg, "mm.0.bias", err) ||
460            !m.upload_matrix(m.mm2, gg, "mm.2.weight", err) || !m.upload_f32(m.mm2_b, gg, "mm.2.bias", err))
461            return false;
462        m.layers.assign((size_t) g.layers, DevLayer{});
463        for (int il = 0; il < g.layers; ++il) {
464            DevLayer& L = m.layers[(size_t) il];
465            const std::string p = "v.blk." + std::to_string(il) + ".";
466            if (!m.upload_f32(L.ln1_w, gg, p + "ln1.weight", err) || !m.upload_f32(L.ln1_b, gg, p + "ln1.bias", err) ||
467                !m.upload_f32(L.ln2_w, gg, p + "ln2.weight", err) || !m.upload_f32(L.ln2_b, gg, p + "ln2.bias", err) ||
468                !m.upload_matrix(L.qkv, gg, p + "attn_qkv.weight", err) || !m.upload_f32(L.qkv_b, gg, p + "attn_qkv.bias", err) ||
469                !m.upload_matrix(L.o, gg, p + "attn_out.weight", err) || !m.upload_f32(L.o_b, gg, p + "attn_out.bias", err) ||
470                !m.upload_matrix(L.up, gg, p + "ffn_up.weight", err) || !m.upload_f32(L.up_b, gg, p + "ffn_up.bias", err) ||
471                !m.upload_matrix(L.down, gg, p + "ffn_down.weight", err) || !m.upload_f32(L.down_b, gg, p + "ffn_down.bias", err))
472                return false;
473        }
474        m.n_weight_allocs = m.allocs.size();
475        if (const char* e = std::getenv("STRATA_VIT_REF_ROUND")) m.round_out = std::atoi(e) != 0;
476        if (const char* e = std::getenv("STRATA_VIT_ROWS")) { const int v = std::atoi(e); if (v >= 16) m.kRows = v; }
477        if (const char* e = std::getenv("STRATA_VIT_SCORES")) { const int v = std::atoi(e); if (v >= 1) { m.kScoreElems = (size_t) v << 20; m.scores_env = true; } }
478        if (const char* e = std::getenv("STRATA_VIT_SCORES_LARGE")) { const long v = std::atol(e); if (v >= 1) m.kScoreElemsLarge = (size_t) v << 20; }   // a diagnostic, as in vit_gpu.cu
479        return m.size_buffers(std::max(max_patches, 16), err);
480    } catch (const std::exception& e) {
481        err = std::string("the GPU failed while loading the vision encoder: ") + e.what();
482        return false;
483    }
484}
485
486bool VitGpu::encode(const PreparedImage& img, std::vector<float>& rows, int& nx, int& ny, std::string& err) {
487    VitGpuImpl& m = *impl_;
488    const VitGeometry& g = m.g;
489    if (m.layers.empty()) { err = "the tower is not loaded"; return false; }
490    if (img.w <= 0 || img.h <= 0 || img.w % g.align() != 0 || img.h % g.align() != 0) { err = "the picture size is not a multiple of patch * merge"; return false; }
491    if (g.head_dim > 96 || g.head_dim % 4 != 0) { err = "this head size is not handled by the GPU attention kernel"; return false; }
492    const int P = g.patch, D = g.width, H = g.heads, HD = g.head_dim, F = g.ffn;
493    const int pw = img.w / P, ph = img.h / P, N = pw * ph, nbx = pw / 2;
494    nx = pw / 2;
495    ny = ph / 2;
496    sycl::queue& q = m.q;
497    try {
498        if (!m.size_buffers(N, err)) return false;
499        static const bool prof = std::getenv("STRATA_VIT_PROF") != nullptr;
500        double pt[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
501        auto pclock = [] { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); };
502        double pmark = prof ? pclock() : 0.0;
503        auto stage = [&](int i) {
504            if (!prof) return;
505            q.wait();
506            const double now = pclock();
507            pt[i] += now - pmark;
508            pmark = now;
509        };
510        auto sync_err = [&](const char* what) {
511            q.wait_and_throw();
512            if (!m.async_err.empty()) { err = std::string(what) + ": " + m.async_err; m.async_err.clear(); return false; }
513            return true;
514        };
515        const int K0 = 3 * P * P;
516        {   // the patch matrix [N][K0], channel-major per patch, tokens in 2x2-merge order, built on the host; it lives in the context buffer
517            std::vector<float> pm((size_t) N * K0);
518            const size_t plane = (size_t) img.w * img.h;
519            for (int t = 0; t < N; ++t) {
520                const int b = t / 4, r = t % 4, py = 2 * (b / nbx) + r / 2, px = 2 * (b % nbx) + r % 2;
521                float* a = &pm[(size_t) t * K0];
522                for (int c = 0; c < 3; ++c)
523                    for (int ky = 0; ky < P; ++ky)
524                        std::memcpy(a + (size_t) c * P * P + (size_t) ky * P, &img.chw[c * plane + (size_t) (py * P + ky) * img.w + (size_t) px * P], (size_t) P * sizeof(float));
525            }
526            q.memcpy(m.d_ctx, pm.data(), pm.size() * 4).wait();
527        }
528        stage(0);
529        DevW pw_w;
530        pw_w.p = m.patch_w; pw_w.kind = K_F32; pw_w.rows = D; pw_w.cols = K0;
531        m.gemm(pw_w, m.d_ctx, N, m.d_x);
532        k_patch_post(q, m.d_x, m.patch_b, m.pos, g.pos_grid, pw, ph, nbx, D, N);
533        if (!sync_err("patch embedding")) return false;
534        stage(1);
535
536        const float theta_scale = std::pow(g.rope_theta, -2.0f / (float) (HD / 2));
537        const float kq_scale = 1.0f / std::sqrt((float) HD);
538        const int R = m.kRows;
539        uint16_t* const a16 = m.d_a;
540        for (const DevLayer& L : m.layers) {
541            for (int r0 = 0; r0 < N; r0 += R) {
542                const int rows_ = std::min(R, N - r0);
543                k_layernorm(q, m.d_x + (size_t) r0 * D, L.ln1_w, L.ln1_b, g.eps, D, a16, (int) L.qkv.kind, rows_);
544                m.gemm(L.qkv, a16, rows_, m.d_y);
545                k_qkv_rope(q, m.d_y, L.qkv_b, r0, nbx, H, HD, theta_scale, kq_scale, m.d_q16, m.d_k16, m.d_v16, rows_);
546            }
547            stage(2);
548            // per chunk of queries: S = K Q^T (one batched product over the heads), softmax, O = V P written head-major (ctx[h][token][j])
549            const int Np = (N + 7) / 8 * 8;
550            const int QC = (int) std::max<size_t>(1, std::min<size_t>((size_t) N, m.sp_elems / ((size_t) H * Np)));
551            for (int q0 = 0; q0 < N; q0 += QC) {
552                const int qc = std::min(QC, N - q0);
553                blas::gemm_batch(q, transpose::trans, transpose::nontrans, N, qc, HD, half(1.0f), (const half*) m.d_k16, D, HD, (const half*) (m.d_q16 + (size_t) q0 * D), D,
554                                 HD, half(0.0f), (half*) m.d_S, Np, (int64_t) qc * Np, H);
555                stage(8);
556                if (N <= kSoftmaxThreads * kSoftmaxPer) softmax_rows(q, m.d_S, N, Np, H * qc);
557                else k_softmax_rows_long(q, m.d_S, N, Np, H * qc);
558                stage(9);
559                blas::gemm_batch(q, transpose::nontrans, transpose::nontrans, HD, qc, N, 1.0f, (const half*) m.d_v16, D, HD, (const half*) m.d_S, Np, (int64_t) qc * Np, 0.0f,
560                                 m.d_ctx + (size_t) q0 * HD, HD, (int64_t) N * HD, H);
561                stage(10);
562            }
563            stage(3);
564            for (int r0 = 0; r0 < N; r0 += R) {      // the output projection in chunks: the head-major context rows to the 16-bit input, the product, the residual
565                const int rows_ = std::min(R, N - r0);
566                k_cast_ctx(q, m.d_ctx, N, H, HD, r0, rows_, a16, (int) L.o.kind);
567                m.gemm(L.o, a16, rows_, m.d_y);
568                k_add_bias_res(q, m.d_x + (size_t) r0 * D, m.d_y, L.o_b, D, rows_);
569            }
570            stage(4);
571            for (int r0 = 0; r0 < N; r0 += R) {      // the feed-forward block in chunks
572                const int rows_ = std::min(R, N - r0);
573                k_layernorm(q, m.d_x + (size_t) r0 * D, L.ln2_w, L.ln2_b, g.eps, D, a16, (int) L.up.kind, rows_);
574                m.gemm(L.up, a16, rows_, m.d_y);
575                k_bias_gelu_cast(q, m.d_y, L.up_b, F, m.d_f16, (int) L.down.kind, rows_);
576                m.gemm(L.down, m.d_f16, rows_, m.d_y);
577                k_add_bias_res(q, m.d_x + (size_t) r0 * D, m.d_y, L.down_b, D, rows_);
578            }
579            stage(5);
580        }
581        if (!sync_err("the layers")) return false;
582        const int M = N / 4, RM = std::max(1, R / 4);
583        for (int r0 = 0; r0 < M; r0 += RM) {
584            const int rows_ = std::min(RM, M - r0);
585            k_layernorm(q, m.d_x + (size_t) r0 * 4 * D, m.post_w, m.post_b, g.eps, D, a16, (int) m.mm0.kind, rows_ * 4);
586            m.gemm(m.mm0, a16, rows_, m.d_y);
587            k_bias_gelu_cast(q, m.d_y, m.mm0_b, g.merger_hidden, m.d_f16, (int) m.mm2.kind, rows_);
588            m.gemm(m.mm2, m.d_f16, rows_, m.d_out + (size_t) r0 * g.out_dim);
589            k_add_bias(q, m.d_out + (size_t) r0 * g.out_dim, m.mm2_b, g.out_dim, rows_);
590        }
591        if (!sync_err("the projector")) return false;
592        stage(6);
593        rows.resize((size_t) M * g.out_dim);
594        q.memcpy(rows.data(), m.d_out, rows.size() * 4).wait();
595        stage(7);
596        if (prof)
597            std::fprintf(stderr, "vit-prof N=%d: patch-matrix %.2f, patch-embed %.2f, ln+qkv %.2f, attention %.2f (S product %.2f, softmax %.2f, PV product %.2f), o-proj %.2f, ffn %.2f, merger %.2f, copy-out %.2f ms\n",
598                         N, pt[0], pt[1], pt[2], pt[3] + pt[8] + pt[9] + pt[10], pt[8], pt[9], pt[10], pt[4], pt[5], pt[6], pt[7]);
599        return true;
600    } catch (const std::exception& e) {
601        err = std::string("the GPU failed: ") + e.what();
602        return false;
603    }
604}
605
606}  // namespace strata_vit