okami.mom/strata

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

Niko1221Merge f-own-3v (aec86299d) into f-own-int: our own Qwen vision tower (mtmd stays the default)0479b72e9

main
2.5 KiB49 linesraw
1// tools/vision/own/vit_ref.h - the float32 CPU reference of the Qwen vision tower (own-stack phase 3).
2//
3// Plain C++ (threads, no ggml, no vendor library): weights converted to float32 at load, every operation in float32 with double sums where
4// a sum is long (norms, softmax).  It is the oracle every backend (CUDA, HIP, later CPU/Metal/SYCL) is checked against, and it is checked
5// against mtmd's embeddings first.  It is NOT the product CPU path: a loop-and-block GEMM, no vector intrinsics, ~1.8 GB of weights.
6//
7// What it computes (geometry-driven, see vit_geometry.h):
8//   patches (patch x patch x 3, the two temporal taps summed) -> + bias, in 2x2-merge order -> + the position table resized to the patch
9//   grid (bilinear, align corners) -> layers x { x += o(attn(LN1 x)); x += down(gelu(up(LN2 x))) } with a 2D rotary on q and k and global
10//   attention -> post LayerNorm -> merger (4 patches -> merger_in -> mm.0 -> gelu -> mm.2) -> one out_dim row per 2x2 block, row-major.
11#pragma once
12
13#include "gguf_lite.h"
14#include "image_prep.h"
15#include "vit_geometry.h"
16
17#include <string>
18#include <vector>
19
20namespace strata_vit {
21
22class VitRef {
23public:
24    // Reads every weight of the tower into float32.  `g` must be supported() (the caller checks).
25    bool load(const Gguf& gg, const VitGeometry& g, std::string& err);
26
27    // img: a prepared picture (sides multiples of patch * merge).  rows: nx * ny rows of out_dim floats, row i at grid position (i % nx, i / nx).
28    // threads <= 0: all hardware threads.
29    bool encode(const PreparedImage& img, int threads, std::vector<float>& rows, int& nx, int& ny, std::string& err) const;
30
31    const VitGeometry& geometry() const { return g_; }
32
33private:
34    struct Layer {
35        std::vector<float> ln1_w, ln1_b, ln2_w, ln2_b, qkv_w, qkv_b, o_w, o_b, up_w, up_b, down_w, down_b;
36    };
37    VitGeometry g_;
38    // STRATA_VIT_REF_ROUND=1 (a diagnostic): each matrix product's input is rounded to its weight's 16-bit type (BF16 or F16) first, as ggml's CPU
39    // and CUDA backends do; it shows how much of a difference to mtmd is that rounding and how much is the maths.  0: no rounding (the reference).
40    int act_round_ = 0;               // 0 none, 1 BF16, 2 F16
41    std::vector<float> patch_w_;      // [width][3 * patch * patch], the taps summed
42    std::vector<float> patch_b_, pos_, post_w_, post_b_, mm0_w_, mm0_b_, mm2_w_, mm2_b_;
43    std::vector<Layer> layers_;
44};
45
46// small helpers the tests and the GPU checks share
47double cosine(const float* a, const float* b, size_t n);
48
49}  // namespace strata_vit