okami.mom/strata

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

Niko1221Merge f-own-3v 6ccf276d2 into f-own-int (round 16: our picture reader as the default, llama.cpp's selectable)c7ea3ac6a

main
35.6 KiB622 linesraw
1// tools/vision/own/vit_metal.mm - see vit_gpu.h: the Qwen vision tower on a Mac's GPU (Metal), the counterpart of vit_gpu.cu (CUDA / HIP) and
2// vit_sycl.cpp (Intel).  The same host flow and the same numbers: weights stay as the file stores them (BF16 or F16; F32 matrices become BF16, Q8_0
3// becomes F16), float32 activations, each matrix product with a 16-bit input of the weight's type and float32 accumulation, q / k / v and the scores
4// in F16, the same chunk rules.  Its own small Metal host (one device, one queue, shared buffers, one command buffer per layer); the kernels
5// (vit_metal.metal, and the tensor-op products in vit_metal_mpp.metal) are embedded in the program and compiled when the reader starts.
6//
7// The products: the Metal 4 tensor ops (MetalPerformancePrimitives matmul2d) where they compile and a self-test against the plain simdgroup kernel
8// passes, decided per product at load and logged once; else the plain kernel.  STRATA_VIT_NO_MPP=1 (a diagnostic) asks for the plain kernel everywhere.
9#import <Foundation/Foundation.h>
10#import <Metal/Metal.h>
11
12#include "vit_gpu.h"
13#include "vit_metal_src.h"     // generated at build time: kVitMetalSrc, kVitMetalMppSrc
14
15#include <algorithm>
16#include <chrono>
17#include <cmath>
18#include <cstdio>
19#include <cstdint>
20#include <cstdlib>
21#include <cstring>
22#include <map>
23#include <set>
24
25#include <mach/mach.h>
26#include <malloc/malloc.h>
27
28namespace strata_vit {
29
30namespace {
31
32enum Kind { K_F32 = 0, K_F16 = 1, K_BF16 = 2 };
33
34struct DevW {            // a weight matrix [rows = out][cols = in] on the device
35    id<MTLBuffer> b = nil;
36    Kind kind = K_BF16;
37    int rows = 0, cols = 0;
38};
39
40struct DevLayer {
41    id<MTLBuffer> ln1_w = nil, ln1_b = nil, ln2_w = nil, ln2_b = nil, qkv_b = nil, o_b = nil, up_b = nil, down_b = nil;
42    DevW qkv, o, up, down;
43};
44
45// a buffer and a byte offset into it
46struct BO {
47    id<MTLBuffer> b;
48    size_t off;
49    BO(id<MTLBuffer> buf, size_t o = 0) : b(buf), off(o) {}
50};
51
52// the argument structs of vit_metal.metal (same layout)
53struct PatchPostArgs { int32_t G, pw, ph, nbx, D; };
54struct NormArgs { int32_t D, kind; float eps; };
55struct RopeArgs { int32_t row0, nbx, heads, hd; float theta_scale, qscale; };
56struct SoftmaxArgs { int32_t n, ld; };
57struct EltArgs { uint64_t n; int32_t kind; int32_t D; };
58struct GemmArgs { uint32_t rows, in, out, ldx, ldw, ldy; uint64_t sx, sw, sy; };
59
60uint16_t host_f32_to_bf16(float f) {
61    uint32_t u;
62    std::memcpy(&u, &f, 4);
63    if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 0x40);
64    u += 0x7fffu + ((u >> 16) & 1u);
65    return (uint16_t) (u >> 16);
66}
67uint16_t host_f32_to_f16(float f) {
68    const __fp16 h = (__fp16) f;      // round to nearest even (clang on arm64)
69    uint16_t u;
70    std::memcpy(&u, &h, 2);
71    return u;
72}
73// STRATA_VIT_MEM=1 (a diagnostic, stderr only): the process's physical footprint (what the gate reads with `footprint`) at a point of the load
74void footprint_note(const char* where) {
75    static const bool on = std::getenv("STRATA_VIT_MEM") != nullptr;
76    if (!on) return;
77    task_vm_info_data_t vi;
78    mach_msg_type_number_t n = TASK_VM_INFO_COUNT;
79    if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &vi, &n) == KERN_SUCCESS)
80        std::fprintf(stderr, "vit-mem: %-34s footprint %.1f MiB\n", where, (double) vi.phys_footprint / 1048576.0);
81}
82
83float host_f16_to_f32(uint16_t u) {
84    __fp16 h;
85    std::memcpy(&h, &u, 2);
86    return (float) h;
87}
88
89}  // namespace
90
91struct VitGpuImpl {
92    VitGeometry g;
93    id<MTLDevice> dev = nil;
94    id<MTLCommandQueue> queue = nil;
95    id<MTLLibrary> lib = nil, lib_mpp = nil;
96    std::map<std::string, id<MTLComputePipelineState>> pipes;
97    id<MTLCommandBuffer> cb = nil;
98    id<MTLComputeCommandEncoder> enc = nil;
99    std::string fail;          // the first dispatch problem (a missing pipeline, a group too large for a pipeline): encode reports it
100    size_t bytes = 0, work_bytes = 0;
101
102    id<MTLBuffer> patch_w = nil, patch_b = nil, pos = nil, post_w = nil, post_b = nil, mm0_b = nil, mm2_b = nil;
103    DevW mm0, mm2;
104    std::vector<DevLayer> layers;
105
106    // the product kernels chosen at load (the self-test): tensor op or plain, per product
107    bool mpp_bf16 = false, mpp_f16 = false, mpp_s = false, mpp_pv = false;
108
109    int cap_patches = 0;
110    // work buffers (as vit_gpu.cu): d_x residual [N][D]; d_ctx context [N][D] (also the patch matrix, and the projector's output at the end); d_y one
111    // chunk's product; d_a a chunk's 16-bit GEMM input; d_f16 the activated FFN / merger hidden of a chunk; q, k, v [N][D] F16; d_S the scores of a chunk
112    id<MTLBuffer> d_x = nil, d_ctx = nil, d_y = nil, d_a = nil, d_f16 = nil, d_q16 = nil, d_k16 = nil, d_v16 = nil, d_S = nil;
113    size_t sp_elems = 0;
114    int kRows = 512;
115    size_t kScoreElems = (size_t) 8 << 20;
116    size_t kScoreElemsLarge = (size_t) 256 << 20;    // above 16,384 patches (512 MB of F16; the SYCL tower's choice; vit_gpu.cu takes 512M on CUDA / HIP)
117    bool scores_env = false;
118    int n_pad = 0, q_align = 0;
119    int pad_for(size_t n) const { return n_pad ? n_pad : n > 16384 ? 64 : 8; }
120    int align_for(size_t n) const { return q_align ? q_align : n > 16384 ? 64 : 1; }
121    size_t padded(size_t n) const { const size_t p = (size_t) pad_for(n); return (n + p - 1) / p * p; }
122    bool round_out = false;
123
124    ~VitGpuImpl() { finish(); }
125
126    id<MTLBuffer> buf(size_t n_bytes, bool weight, std::string& err) {
127        id<MTLBuffer> b = [dev newBufferWithLength:std::max<size_t>(n_bytes, 16) options:MTLResourceStorageModeShared];
128        if (!b) { err = "GPU memory: no buffer of " + std::to_string(n_bytes) + " bytes"; return nil; }
129        bytes += n_bytes;
130        if (!weight) work_bytes += n_bytes;
131        return b;
132    }
133    id<MTLBuffer> buf_from(const void* src, size_t n_bytes, std::string& err) {
134        id<MTLBuffer> b = buf(n_bytes, true, err);
135        if (b) std::memcpy([b contents], src, n_bytes);
136        return b;
137    }
138    bool upload_f32(__strong id<MTLBuffer>& dst, const Gguf& gg, const std::string& name, std::string& err) {
139        const GgufTensorInfo* t = gg.tensor(name);
140        if (!t) { err = "the mmproj file lacks the tensor " + name; return false; }
141        std::vector<float> h((size_t) t->nelem());
142        if (!gg.read_f32(*t, h.data(), err)) return false;
143        dst = buf_from(h.data(), h.size() * 4, err);
144        return dst != nil;
145    }
146    bool upload_matrix(DevW& w, const Gguf& gg, const std::string& name, std::string& err) {
147        const GgufTensorInfo* t = gg.tensor(name);
148        if (!t || t->ne.size() != 2) { err = "the mmproj file lacks the matrix " + name; return false; }
149        w.cols = (int) t->ne[0];
150        w.rows = (int) t->ne[1];
151        const size_t n = (size_t) t->nelem();
152        std::vector<uint16_t> raw(n);
153        if (t->type == GT_F16 || t->type == GT_BF16) {        // as stored
154            if (!gg.read_raw(*t, raw.data(), err)) return false;
155            w.kind = t->type == GT_F16 ? K_F16 : K_BF16;
156        } else {                                                // F32 -> BF16, Q8_0 -> F16
157            std::vector<float> f(n);
158            if (!gg.read_f32(*t, f.data(), err)) return false;
159            const bool bf = t->type == GT_F32;
160            w.kind = bf ? K_BF16 : K_F16;
161            for (size_t i = 0; i < n; ++i) raw[i] = bf ? host_f32_to_bf16(f[i]) : host_f32_to_f16(f[i]);
162        }
163        w.b = buf_from(raw.data(), n * 2, err);
164        return w.b != nil;
165    }
166
167    // ---- dispatching ----
168    id<MTLComputePipelineState> pipe(const std::string& fn) {
169        auto it = pipes.find(fn);
170        if (it != pipes.end()) return it->second;
171        id<MTLLibrary> L = fn.rfind("vm_", 0) == 0 ? lib_mpp : lib;
172        id<MTLFunction> f = L ? [L newFunctionWithName:[NSString stringWithUTF8String:fn.c_str()]] : nil;
173        NSError* e = nil;
174        id<MTLComputePipelineState> p = f ? [dev newComputePipelineStateWithFunction:f error:&e] : nil;
175        pipes[fn] = p;
176        return p;
177    }
178    id<MTLComputeCommandEncoder> encoder() {
179        if (!cb) cb = [queue commandBuffer];
180        if (!enc) enc = [cb computeCommandEncoder];      // serial dispatch: each dispatch sees the previous one's writes
181        return enc;
182    }
183    void go(const std::string& fn, std::initializer_list<BO> bufs, const void* args, size_t args_bytes, MTLSize grid, NSUInteger threads) {
184        if (!fail.empty()) return;
185        if (grid.width == 0 || grid.height == 0 || grid.depth == 0) return;
186        id<MTLComputePipelineState> p = pipe(fn);
187        if (!p) { fail = "no pipeline " + fn; return; }
188        // a group larger than the pipeline allows is NOT run by Metal, and no error is raised (the engine's #2323): so check every dispatch
189        if ([p maxTotalThreadsPerThreadgroup] < threads) {
190            fail = fn + " needs " + std::to_string(threads) + " threads a group, this GPU allows " + std::to_string((size_t) [p maxTotalThreadsPerThreadgroup]);
191            return;
192        }
193        id<MTLComputeCommandEncoder> e = encoder();
194        [e setComputePipelineState:p];
195        NSUInteger i = 0;
196        for (const BO& b : bufs) [e setBuffer:b.b offset:b.off atIndex:i++];
197        [e setBytes:args length:args_bytes atIndex:15];
198        [e dispatchThreadgroups:grid threadsPerThreadgroup:MTLSizeMake(threads, 1, 1)];
199        // STRATA_VIT_MEM=1: the footprint after the first run of each kernel (the GPU waited for), to see which one takes memory on first use
200        static const bool mem = std::getenv("STRATA_VIT_MEM") != nullptr;
201        if (mem && seen.insert(fn).second) {
202            (void) finish();
203            footprint_note(("first run of " + fn).c_str());
204        }
205    }
206    std::set<std::string> seen;
207    // commit what is encoded as its own command buffer, without waiting (one per layer: no long-running buffer)
208    void split() {
209        if (enc) { [enc endEncoding]; enc = nil; }
210        if (cb) { [cb commit]; last = cb; cb = nil; }
211    }
212    id<MTLCommandBuffer> last = nil;
213    // commit and wait for everything encoded so far; false (with the reason) on a GPU error
214    bool finish(std::string* err = nullptr) {
215        split();
216        if (last) {
217            [last waitUntilCompleted];
218            const bool ok = [last status] == MTLCommandBufferStatusCompleted;
219            if (!ok && err) {
220                NSError* e = [last error];
221                *err = std::string("the GPU work failed: ") + (e ? [[e localizedDescription] UTF8String] : "unknown");
222            }
223            last = nil;
224            return ok;
225        }
226        return true;
227    }
228
229    // Y[z][rows][out] = X[z][rows][in] * W[z](out, in), float32 accumulation; `wn`: W is [in][out]; the product's kernel by name (plain) or tensor op
230    void gemm(const char* plain, const char* mpp, BO X, BO W, BO Y, int rows, int in, int out, int ldx, int ldw, int ldy, size_t sx, size_t sw, size_t sy,
231              int batch, int tm = 64) {
232        const GemmArgs a{(uint32_t) rows, (uint32_t) in, (uint32_t) out, (uint32_t) ldx, (uint32_t) ldw, (uint32_t) ldy, sx, sw, sy};
233        const bool use = mpp != nullptr;
234        const int TM = use ? tm : 64;
235        go(use ? mpp : plain, {X, W, Y}, &a, sizeof a, MTLSizeMake((out + 63) / 64, (rows + TM - 1) / TM, batch), 128);
236    }
237    // y[M][w.rows] (float32) = A[M][K] (w's kind) * w^T
238    void wgemm(const DevW& w, BO A, int M, BO y) {
239        const char* plain = w.kind == K_F16 ? "vk_gemm_f16" : "vk_gemm_bf16";
240        const char* mpp = nullptr;
241        if (w.kind == K_F16 && mpp_f16) mpp = M >= 128 ? "vm_gemm_f16_128" : "vm_gemm_f16_64";
242        if (w.kind == K_BF16 && mpp_bf16) mpp = M >= 128 ? "vm_gemm_bf16_128" : "vm_gemm_bf16_64";
243        gemm(plain, mpp, A, BO(w.b), y, M, w.cols, w.rows, w.cols, w.cols, w.rows, 0, 0, 0, 1, M >= 128 ? 128 : 64);
244        if (round_out) {
245            const EltArgs e{(uint64_t) M * w.rows, (int32_t) w.kind, 0};
246            go("vk_round", {y}, &e, sizeof e, MTLSizeMake(blocks_for(e.n), 1, 1), 256);
247        }
248    }
249    static NSUInteger blocks_for(size_t n, int per = 256) { return (NSUInteger) std::min<size_t>((n + per - 1) / per, 65535); }
250
251    bool size_buffers(int patches, std::string& err) {
252        if (patches <= cap_patches) return true;
253        if (!finish(&err)) return false;
254        bytes -= work_bytes;
255        work_bytes = 0;
256        d_x = d_ctx = d_y = d_a = d_f16 = d_q16 = d_k16 = d_v16 = d_S = nil;
257        const size_t N = (size_t) patches, D = (size_t) g.width, F = (size_t) std::max(g.ffn, g.merger_hidden);
258        const size_t K0 = (size_t) 3 * g.patch * g.patch;
259        const size_t Np = padded(N);
260        const size_t budget = (N > 16384 && !scores_env) ? kScoreElemsLarge : kScoreElems;
261        sp_elems = std::min<size_t>((size_t) g.heads * N * Np, std::max<size_t>(budget, (size_t) g.heads * Np * 64));
262        const size_t R = std::min<size_t>(N, (size_t) kRows);
263        const size_t ctx_elems = std::max({N * D, N * K0, (N / 4) * (size_t) g.out_dim});
264        d_x = buf(N * D * 4, false, err);
265        d_ctx = d_x ? buf(ctx_elems * 4, false, err) : nil;
266        d_y = d_ctx ? buf(R * std::max<size_t>(3 * D, F) * 4, false, err) : nil;
267        d_a = d_y ? buf(R * D * 2, false, err) : nil;
268        d_f16 = d_a ? buf(R * F * 2, false, err) : nil;
269        d_q16 = d_f16 ? buf(N * D * 2, false, err) : nil;
270        d_k16 = d_q16 ? buf(N * D * 2, false, err) : nil;
271        d_v16 = d_k16 ? buf(N * D * 2, false, err) : nil;
272        if (!d_v16) { cap_patches = 0; return false; }
273        d_S = buf(sp_elems * 2, false, err);
274        if (!d_S && budget != kScoreElems) {      // no room for the large chunk: the default chunk instead, slower, never an error
275            err.clear();
276            sp_elems = std::min<size_t>((size_t) g.heads * N * Np, std::max<size_t>(kScoreElems, (size_t) g.heads * Np * 64));
277            d_S = buf(sp_elems * 2, false, err);
278        }
279        if (!d_S) { cap_patches = 0; return false; }
280        cap_patches = patches;
281        return true;
282    }
283
284    // The tensor-op products against the plain kernel on small odd sizes (a batch of 2, strides wider than the rows): true when every value agrees within
285    // float32 rounding of a different summation order.  One check per product kind.
286    bool mpp_check(const char* plain, const char* mpp, int ti /* 1 F16, 2 BF16 */, bool wn, bool out_half, std::string& why) {
287        const int M = 70, N = 90, K = 100, LDX = 104, LDW = wn ? 136 : 104, LDY = 96, B = 2;
288        const size_t sx = (size_t) M * LDX, sw = (size_t) (wn ? K : N) * LDW, sy = (size_t) M * LDY;
289        std::string e;
290        id<MTLBuffer> bx = buf(sx * B * 2, false, e), bw = buf(sw * B * 2, false, e), y0 = buf(sy * B * 4, false, e), y1 = buf(sy * B * 4, false, e);
291        if (!bx || !bw || !y0 || !y1) { why = "no memory for the self-test"; return false; }
292        uint32_t seed = 12345u;
293        auto rnd = [&]() { seed = seed * 1664525u + 1013904223u; return (float) ((seed >> 8) & 0xffffu) / 32768.0f - 1.0f; };
294        uint16_t* px = (uint16_t*) [bx contents];
295        uint16_t* pw = (uint16_t*) [bw contents];
296        for (size_t i = 0; i < sx * B; ++i) px[i] = ti == 1 ? host_f32_to_f16(rnd()) : host_f32_to_bf16(rnd());
297        for (size_t i = 0; i < sw * B; ++i) pw[i] = ti == 1 ? host_f32_to_f16(rnd()) : host_f32_to_bf16(rnd());
298        std::memset([y0 contents], 0, sy * B * 4);
299        std::memset([y1 contents], 0, sy * B * 4);
300        // the expected result on the host (double sums of the 16-bit inputs), written in the output's type into y0.  Not the plain GPU kernel: its first
301        // run costs the process ~136 MB of GPU-owned memory (D5), which a Mac with the tensor ops would otherwise never pay
302        (void) plain;
303        {
304            auto in16 = [&](uint16_t u) { return ti == 1 ? (double) host_f16_to_f32(u) : (double) [](uint16_t b) { uint32_t v = (uint32_t) b << 16; float f; std::memcpy(&f, &v, 4); return f; }(u); };
305            for (int z = 0; z < B; ++z)
306                for (int r = 0; r < M; ++r)
307                    for (int c = 0; c < N; ++c) {
308                        double s = 0.0;
309                        for (int k = 0; k < K; ++k) {
310                            const double x = in16(px[(size_t) z * sx + (size_t) r * LDX + k]);
311                            const double w = wn ? in16(pw[(size_t) z * sw + (size_t) k * LDW + c]) : in16(pw[(size_t) z * sw + (size_t) c * LDW + k]);
312                            s += x * w;
313                        }
314                        const size_t i = (size_t) z * sy + (size_t) r * LDY + c;
315                        if (out_half) ((uint16_t*) [y0 contents])[i] = host_f32_to_f16((float) s);
316                        else ((float*) [y0 contents])[i] = (float) s;
317                    }
318        }
319        gemm(plain, mpp, BO(bx), BO(bw), BO(y1), M, K, N, LDX, LDW, LDY, sx, sw, sy, B, 64);
320        std::string ferr;
321        const bool ran = fail.empty() && finish(&ferr);
322        bytes -= (sx * B * 2 + sw * B * 2 + sy * B * 8);
323        work_bytes -= (sx * B * 2 + sw * B * 2 + sy * B * 8);
324        if (!ran) { why = fail.empty() ? ferr : fail; fail.clear(); return false; }
325        double worst = 0.0;
326        for (int z = 0; z < B; ++z)
327            for (int r = 0; r < M; ++r)
328                for (int c = 0; c < N; ++c) {
329                    const size_t i = (size_t) z * sy + (size_t) r * LDY + c;
330                    float a, b;
331                    if (out_half) { a = host_f16_to_f32(((uint16_t*) [y0 contents])[i]); b = host_f16_to_f32(((uint16_t*) [y1 contents])[i]); }
332                    else { a = ((float*) [y0 contents])[i]; b = ((float*) [y1 contents])[i]; }
333                    const double d = std::fabs((double) a - (double) b);
334                    worst = std::max(worst, d);
335                    const double tol = out_half ? 1e-2 + 2e-3 * std::fabs((double) a) : 1e-3 + 1e-4 * std::fabs((double) a);
336                    if (!(d <= tol)) {
337                        char m[160];
338                        std::snprintf(m, sizeof m, "differs from the exact product (%g against %g at %d,%d,%d)", (double) b, (double) a, z, r, c);
339                        why = m;
340                        return false;
341                    }
342                }
343        return true;
344    }
345};
346
347VitGpu::VitGpu() : impl_(new VitGpuImpl()) {}
348VitGpu::~VitGpu() = default;
349size_t VitGpu::device_bytes() const { return impl_->bytes; }
350
351bool VitGpu::available(std::string& why) {
352    @autoreleasepool {
353        id<MTLDevice> d = MTLCreateSystemDefaultDevice();
354        if (!d) { why = "no Metal GPU"; return false; }
355        return true;
356    }
357}
358
359bool VitGpu::prefer_mtmd(bool bf16_matrices, int max_tokens, std::string& why) {
360    // the Metal tower passed its gate on the M5 Max (RESULTS-OWN-3V.md D1, D4-D8: rule 1 and 2, 0.47 to 0.79 of mtmd-Metal's time, less memory, the 16,384-token
361    // picture that mtmd-Metal aborts on), so `auto` (the default) takes it on every Mac (owner 11-11: our tower the default, mtmd selectable)
362    (void) bf16_matrices;
363    (void) max_tokens;
364    (void) why;
365    return false;
366}
367
368bool VitGpu::load(const Gguf& gg, const VitGeometry& g, int device, int max_patches, std::string& err) {
369    @autoreleasepool {
370        VitGpuImpl& m = *impl_;
371        (void) device;      // one GPU on a Mac
372        std::string why;
373        if (!vit_geometry_supported(g, why)) { err = "this tower is not supported: " + why; return false; }
374        m.g = g;
375        footprint_note("start of the load");
376        m.dev = MTLCreateSystemDefaultDevice();
377        if (!m.dev) { err = "no Metal GPU"; return false; }
378        m.queue = [m.dev newCommandQueue];
379        footprint_note("device and queue");
380        // the kernels: safe maths (no fast-math), compiled from the embedded source
381        {
382            MTLCompileOptions* o = [MTLCompileOptions new];
383            if (@available(macOS 15.0, *)) o.mathMode = MTLMathModeSafe;
384            else {
385#pragma clang diagnostic push
386#pragma clang diagnostic ignored "-Wdeprecated-declarations"
387                o.fastMathEnabled = NO;     // macOS before 15: the only switch there (fast maths is the default)
388#pragma clang diagnostic pop
389            }
390            NSError* e = nil;
391            m.lib = [m.dev newLibraryWithSource:[NSString stringWithUTF8String:kVitMetalSrc] options:o error:&e];
392            if (!m.lib) { err = std::string("the Metal kernels do not compile: ") + (e ? [[e localizedDescription] UTF8String] : "unknown"); return false; }
393        }
394        footprint_note("plain kernels compiled");
395        if (std::getenv("STRATA_VIT_MEM")) {     // diagnostic: does any first dispatch cost the ~250 MB, or only the product kernels' (D5)?
396            std::string e;
397            id<MTLBuffer> t = m.buf(4096, false, e), tb = m.buf(4096, false, e);
398            const EltArgs a{0, 0, 16};
399            m.go("vk_add_bias", {BO(t), BO(tb)}, &a, sizeof a, MTLSizeMake(4, 1, 1), 32);
400            (void) m.finish();
401            footprint_note("after one tiny vk_add_bias");
402            m.bytes -= 8192; m.work_bytes -= 8192;
403        }
404        // the tensor-op products: Metal 4 only, then per product a self-test against the plain kernel
405        std::string mpp_why;
406        const bool no_mpp = std::getenv("STRATA_VIT_NO_MPP") != nullptr;
407        bool metal4 = false;
408        if (@available(macOS 26.0, *)) metal4 = [m.dev supportsFamily:MTLGPUFamilyMetal4];
409        if (no_mpp) mpp_why = "STRATA_VIT_NO_MPP";
410        else if (!metal4) mpp_why = "no Metal 4 on this GPU or macOS";
411        else {
412            MTLCompileOptions* o = [MTLCompileOptions new];
413            if (@available(macOS 15.0, *)) o.mathMode = MTLMathModeSafe;
414            NSError* e = nil;
415            m.lib_mpp = [m.dev newLibraryWithSource:[NSString stringWithUTF8String:kVitMetalMppSrc] options:o error:&e];
416            if (!m.lib_mpp) mpp_why = std::string("the tensor-op kernels do not compile (") + (e ? std::string([[e localizedDescription] UTF8String]).substr(0, 160) : "unknown") + ")";
417        }
418        std::string w_bf, w_f16, w_s, w_pv;
419        if (m.lib_mpp) {
420            m.mpp_bf16 = m.mpp_check("vk_gemm_bf16", "vm_gemm_bf16_64", 2, false, false, w_bf);
421            m.mpp_f16 = m.mpp_check("vk_gemm_f16", "vm_gemm_f16_64", 1, false, false, w_f16);
422            m.mpp_s = m.mpp_check("vk_gemm_s", "vm_gemm_s", 1, false, true, w_s);
423            m.mpp_pv = m.mpp_check("vk_gemm_pv", "vm_gemm_pv", 1, true, false, w_pv);
424        }
425        // diagnostics: the plain kernel for one product only (STRATA_VIT_NO_MPP_W: the weight products, _S: the scores, _PV: the context)
426        if (std::getenv("STRATA_VIT_NO_MPP_W")) { m.mpp_bf16 = m.mpp_f16 = false; w_bf = w_f16 = "STRATA_VIT_NO_MPP_W"; }
427        if (std::getenv("STRATA_VIT_NO_MPP_S")) { m.mpp_s = false; w_s = "STRATA_VIT_NO_MPP_S"; }
428        if (std::getenv("STRATA_VIT_NO_MPP_PV")) { m.mpp_pv = false; w_pv = "STRATA_VIT_NO_MPP_PV"; }
429        auto say = [&](bool on, const std::string& w) { return on ? std::string("tensor op") : "plain" + (w.empty() ? (mpp_why.empty() ? std::string() : " (" + mpp_why + ")") : " (" + w + ")"); };
430        std::fprintf(stderr, "strata-vision: Metal tower on %s; products: BF16 weights %s, F16 weights %s, attention S %s, P*V %s; patch matrix float32, one output a thread\n",
431                     [[m.dev name] UTF8String], say(m.mpp_bf16, w_bf).c_str(), say(m.mpp_f16, w_f16).c_str(), say(m.mpp_s, w_s).c_str(), say(m.mpp_pv, w_pv).c_str());
432        m.bytes = m.work_bytes = 0;
433        footprint_note("kernels compiled, self-test done");
434        // the patch embedding: the two temporal taps summed, kept in float32 (a small matrix)
435        {
436            const GgufTensorInfo* t0 = gg.tensor("v.patch_embd.weight");
437            if (!t0) { err = "the mmproj file lacks v.patch_embd.weight"; return false; }
438            std::vector<float> w0((size_t) t0->nelem()), w1;
439            if (!gg.read_f32(*t0, w0.data(), err)) return false;
440            if (g.patch_taps == 2) {
441                const GgufTensorInfo* t1 = gg.tensor("v.patch_embd.weight.1");
442                w1.resize(w0.size());
443                if (!t1 || !gg.read_f32(*t1, w1.data(), err)) { if (err.empty()) err = "the mmproj file lacks v.patch_embd.weight.1"; return false; }
444                for (size_t i = 0; i < w0.size(); ++i) w0[i] += w1[i];
445            }
446            m.patch_w = m.buf_from(w0.data(), w0.size() * 4, err);
447            if (!m.patch_w) return false;
448        }
449        if (!m.upload_f32(m.patch_b, gg, "v.patch_embd.bias", err) || !m.upload_f32(m.pos, gg, "v.position_embd.weight", err) ||
450            !m.upload_f32(m.post_w, gg, "v.post_ln.weight", err) || !m.upload_f32(m.post_b, gg, "v.post_ln.bias", err) ||
451            !m.upload_matrix(m.mm0, gg, "mm.0.weight", err) || !m.upload_f32(m.mm0_b, gg, "mm.0.bias", err) ||
452            !m.upload_matrix(m.mm2, gg, "mm.2.weight", err) || !m.upload_f32(m.mm2_b, gg, "mm.2.bias", err))
453            return false;
454        m.layers.assign((size_t) g.layers, DevLayer{});
455        for (int il = 0; il < g.layers; ++il) {
456            DevLayer& L = m.layers[(size_t) il];
457            const std::string p = "v.blk." + std::to_string(il) + ".";
458            if (!m.upload_f32(L.ln1_w, gg, p + "ln1.weight", err) || !m.upload_f32(L.ln1_b, gg, p + "ln1.bias", err) ||
459                !m.upload_f32(L.ln2_w, gg, p + "ln2.weight", err) || !m.upload_f32(L.ln2_b, gg, p + "ln2.bias", err) ||
460                !m.upload_matrix(L.qkv, gg, p + "attn_qkv.weight", err) || !m.upload_f32(L.qkv_b, gg, p + "attn_qkv.bias", err) ||
461                !m.upload_matrix(L.o, gg, p + "attn_out.weight", err) || !m.upload_f32(L.o_b, gg, p + "attn_out.bias", err) ||
462                !m.upload_matrix(L.up, gg, p + "ffn_up.weight", err) || !m.upload_f32(L.up_b, gg, p + "ffn_up.bias", err) ||
463                !m.upload_matrix(L.down, gg, p + "ffn_down.weight", err) || !m.upload_f32(L.down_b, gg, p + "ffn_down.bias", err))
464                return false;
465        }
466        if (const char* e = std::getenv("STRATA_VIT_REF_ROUND")) m.round_out = std::atoi(e) != 0;
467        if (const char* e = std::getenv("STRATA_VIT_ROWS")) { const int v = std::atoi(e); if (v >= 16) m.kRows = v; }
468        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; } }
469        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; }
470        if (const char* e = std::getenv("STRATA_VIT_NPAD")) { const int v = std::atoi(e); if (v >= 8 && v % 8 == 0) m.n_pad = v; }
471        if (const char* e = std::getenv("STRATA_VIT_QALIGN")) { const int v = std::atoi(e); if (v >= 1) m.q_align = v; }
472        footprint_note("weights uploaded");
473        const bool ok = m.size_buffers(std::max(max_patches, 16), err);
474        footprint_note("work buffers");
475        // the host copies of the weights (one matrix at a time, up to ~10 MB each) are freed by now, but macOS's allocator keeps freed large blocks in its
476        // cache, where they count in the reader's footprint (87 MB at READY, RESULTS-OWN-3V.md D5): hand them back
477        malloc_zone_pressure_relief(nullptr, 0);
478        return ok;
479    }
480}
481
482bool VitGpu::encode(const PreparedImage& img, std::vector<float>& rows, int& nx, int& ny, std::string& err) {
483    @autoreleasepool {
484        VitGpuImpl& m = *impl_;
485        const VitGeometry& g = m.g;
486        if (m.layers.empty()) { err = "the tower is not loaded"; return false; }
487        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; }
488        if (g.head_dim > 96 || g.head_dim % 4 != 0) { err = "this head size is not handled by the GPU attention kernel"; return false; }
489        const int P = g.patch, D = g.width, H = g.heads, HD = g.head_dim, F = g.ffn;
490        const int pw = img.w / P, ph = img.h / P, N = pw * ph, nbx = pw / 2;
491        nx = pw / 2;
492        ny = ph / 2;
493        if (!m.size_buffers(N, err)) return false;
494        m.fail.clear();
495        // STRATA_VIT_PROF=1 (a diagnostic, stderr only, off by default): the time of each stage, the GPU waited for after every stage
496        static const bool prof = std::getenv("STRATA_VIT_PROF") != nullptr;
497        double pt[10] = {0};
498        auto pclock = [] { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); };
499        double pmark = prof ? pclock() : 0.0;
500        auto stage = [&](int i) {
501            if (!prof) return;
502            (void) m.finish();
503            const double now = pclock();
504            pt[i] += now - pmark;
505            pmark = now;
506        };
507        const int K0 = 3 * P * P;
508        {   // the patch matrix [N][K0], channel-major per patch, tokens in 2x2-merge order, written by the host into the context buffer (the GPU is idle here)
509            float* pm = (float*) [m.d_ctx contents];
510            const size_t plane = (size_t) img.w * img.h;
511            for (int t = 0; t < N; ++t) {
512                const int b = t / 4, r = t % 4, py = 2 * (b / nbx) + r / 2, px = 2 * (b % nbx) + r % 2;
513                float* a = pm + (size_t) t * K0;
514                for (int c = 0; c < 3; ++c)
515                    for (int ky = 0; ky < P; ++ky)
516                        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));
517            }
518        }
519        stage(0);
520        {
521            const GemmArgs a{(uint32_t) N, (uint32_t) K0, (uint32_t) D, (uint32_t) K0, (uint32_t) K0, (uint32_t) D, 0, 0, 0};
522            m.go("vk_gemm_seq_f32", {BO(m.d_ctx), BO(m.patch_w), BO(m.d_x)}, &a, sizeof a, MTLSizeMake((D + 63) / 64, N, 1), 64);
523        }
524        {
525            const PatchPostArgs a{g.pos_grid, pw, ph, nbx, D};
526            m.go("vk_patch_post", {BO(m.d_x), BO(m.patch_b), BO(m.pos)}, &a, sizeof a, MTLSizeMake(N, 1, 1), 256);
527        }
528        stage(1);
529        const float theta_scale = std::pow(g.rope_theta, -2.0f / (float) (HD / 2));
530        const float kq_scale = 1.0f / std::sqrt((float) HD);
531        const int R = m.kRows;
532        for (const DevLayer& L : m.layers) {
533            for (int r0 = 0; r0 < N; r0 += R) {
534                const int rows_c = std::min(R, N - r0);
535                const NormArgs na{D, (int32_t) L.qkv.kind, g.eps};
536                m.go("vk_layernorm", {BO(m.d_x, (size_t) r0 * D * 4), BO(L.ln1_w), BO(L.ln1_b), BO(m.d_a)}, &na, sizeof na, MTLSizeMake(rows_c, 1, 1), 256);
537                m.wgemm(L.qkv, BO(m.d_a), rows_c, BO(m.d_y));
538                const RopeArgs ra{r0, nbx, H, HD, theta_scale, kq_scale};
539                m.go("vk_qkv_rope", {BO(m.d_y), BO(L.qkv_b), BO(m.d_q16), BO(m.d_k16), BO(m.d_v16)}, &ra, sizeof ra, MTLSizeMake(rows_c, 1, 1), 256);
540            }
541            stage(2);
542            const int Np = (int) m.padded((size_t) N);
543            int QC = (int) std::max<size_t>(1, std::min<size_t>((size_t) N, m.sp_elems / ((size_t) H * Np)));
544            const int qa = m.align_for((size_t) N);
545            if (qa > 1 && QC < N && QC >= qa) QC -= QC % qa;
546            for (int q0 = 0; q0 < N; q0 += QC) {
547                const int qc = std::min(QC, N - q0);
548                // S [head][query][key] = q k^T (q carries the scale), F16
549                m.gemm("vk_gemm_s", m.mpp_s ? "vm_gemm_s" : nullptr, BO(m.d_q16, (size_t) q0 * D * 2), BO(m.d_k16), BO(m.d_S), qc, HD, N, D, D, Np,
550                       (size_t) HD, (size_t) HD, (size_t) qc * Np, H);
551                stage(8);
552                const SoftmaxArgs sa{N, Np};
553                const char* sm = nullptr;
554                NSUInteger st = 256;
555                if (N <= 128) { sm = "vk_softmax_rows_2"; st = 64; }
556                else if (N <= 512) { sm = "vk_softmax_rows_8"; st = 64; }
557                else if (N <= 1024) { sm = "vk_softmax_rows_8"; st = 128; }
558                else if (N <= 4096) { sm = "vk_softmax_rows_16"; st = 256; }
559                else if (N <= 16384) { sm = "vk_softmax_rows_64"; st = 256; }
560                if (sm && [m.pipe(sm) maxTotalThreadsPerThreadgroup] < st) sm = nullptr;     // registers too few for that group here: the long-row kernel
561                if (sm) m.go(sm, {BO(m.d_S)}, &sa, sizeof sa, MTLSizeMake((size_t) H * qc, 1, 1), st);
562                else m.go("vk_softmax_rows_long", {BO(m.d_S)}, &sa, sizeof sa, MTLSizeMake((size_t) H * qc, 1, 1), 256);
563                stage(9);
564                // context [query][head * HD + d] = P V, float32
565                m.gemm("vk_gemm_pv", m.mpp_pv ? "vm_gemm_pv" : nullptr, BO(m.d_S), BO(m.d_v16), BO(m.d_ctx, (size_t) q0 * D * 4), qc, N, HD, Np, D, D,
566                       (size_t) qc * Np, (size_t) HD, (size_t) HD, H);
567            }
568            stage(3);
569            for (int r0 = 0; r0 < N; r0 += R) {
570                const int rows_c = std::min(R, N - r0);
571                const EltArgs ca{(uint64_t) rows_c * D, (int32_t) L.o.kind, D};
572                m.go("vk_cast", {BO(m.d_ctx, (size_t) r0 * D * 4), BO(m.d_a)}, &ca, sizeof ca, MTLSizeMake(VitGpuImpl::blocks_for(ca.n), 1, 1), 256);
573                m.wgemm(L.o, BO(m.d_a), rows_c, BO(m.d_y));
574                const EltArgs ra{0, 0, D};
575                m.go("vk_add_bias_res", {BO(m.d_x, (size_t) r0 * D * 4), BO(m.d_y), BO(L.o_b)}, &ra, sizeof ra, MTLSizeMake(rows_c, 1, 1), 256);
576            }
577            stage(4);
578            for (int r0 = 0; r0 < N; r0 += R) {
579                const int rows_c = std::min(R, N - r0);
580                const NormArgs na{D, (int32_t) L.up.kind, g.eps};
581                m.go("vk_layernorm", {BO(m.d_x, (size_t) r0 * D * 4), BO(L.ln2_w), BO(L.ln2_b), BO(m.d_a)}, &na, sizeof na, MTLSizeMake(rows_c, 1, 1), 256);
582                m.wgemm(L.up, BO(m.d_a), rows_c, BO(m.d_y));
583                const EltArgs ga{0, (int32_t) L.down.kind, F};
584                m.go("vk_bias_gelu_cast", {BO(m.d_y), BO(L.up_b), BO(m.d_f16)}, &ga, sizeof ga, MTLSizeMake(rows_c, 1, 1), 256);
585                m.wgemm(L.down, BO(m.d_f16), rows_c, BO(m.d_y));
586                const EltArgs ra{0, 0, D};
587                m.go("vk_add_bias_res", {BO(m.d_x, (size_t) r0 * D * 4), BO(m.d_y), BO(L.down_b)}, &ra, sizeof ra, MTLSizeMake(rows_c, 1, 1), 256);
588            }
589            stage(5);
590            m.split();      // each layer is its own command buffer: none runs long enough for the system to cut it short
591        }
592        // post norm (into the merger's input kind), then the merger on 4-patch rows, in chunks; the output rows go to the context buffer
593        const int M = N / 4, RM = std::max(1, R / 4);
594        for (int r0 = 0; r0 < M; r0 += RM) {
595            const int rows_c = std::min(RM, M - r0);
596            const NormArgs na{D, (int32_t) m.mm0.kind, g.eps};
597            m.go("vk_layernorm", {BO(m.d_x, (size_t) r0 * 4 * D * 4), BO(m.post_w), BO(m.post_b), BO(m.d_a)}, &na, sizeof na, MTLSizeMake((size_t) rows_c * 4, 1, 1), 256);
598            m.wgemm(m.mm0, BO(m.d_a), rows_c, BO(m.d_y));
599            const EltArgs ga{0, (int32_t) m.mm2.kind, g.merger_hidden};
600            m.go("vk_bias_gelu_cast", {BO(m.d_y), BO(m.mm0_b), BO(m.d_f16)}, &ga, sizeof ga, MTLSizeMake(rows_c, 1, 1), 256);
601            m.wgemm(m.mm2, BO(m.d_f16), rows_c, BO(m.d_ctx, (size_t) r0 * g.out_dim * 4));
602            const EltArgs ba{0, 0, g.out_dim};
603            m.go("vk_add_bias", {BO(m.d_ctx, (size_t) r0 * g.out_dim * 4), BO(m.mm2_b)}, &ba, sizeof ba, MTLSizeMake(rows_c, 1, 1), 256);
604        }
605        std::string ferr;
606        const bool ok = m.finish(&ferr);
607        if (!m.fail.empty()) { err = m.fail; return false; }
608        if (!ok) { err = ferr; return false; }
609        stage(6);
610        rows.resize((size_t) M * g.out_dim);
611        std::memcpy(rows.data(), [m.d_ctx contents], rows.size() * 4);
612        footprint_note("after a picture");
613        malloc_zone_pressure_relief(nullptr, 0);     // the picture's decode and preparation buffers, freed by the caller before this one: see load()
614        stage(7);
615        if (prof)
616            std::fprintf(stderr, "vit-prof N=%d: patch-matrix %.2f, patch-embed %.2f, ln+qkv %.2f, attention %.2f (S product %.2f, softmax %.2f), o-proj %.2f, ffn %.2f, merger %.2f, copy-out %.2f ms\n",
617                         N, pt[0], pt[1], pt[2], pt[3] + pt[8] + pt[9], pt[8], pt[9], pt[4], pt[5], pt[6], pt[7]);
618        return true;
619    }
620}
621
622}  // namespace strata_vit