okami.mom/strata

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

Niko1221Merge f-own-3c 971bff01a into f-p4-int870ea9763

main
10.6 KiB209 linesraw
1// tools/vision/own/own_reader.cpp - see own_reader.h
2#include "own_reader.h"
3
4#include "cpu_caps.h"
5#include "vit_cpu.h"
6#include "vit_ref.h"
7#ifdef STRATA_VIT_GPU
8#include "vit_gpu.h"
9#endif
10
11#include <algorithm>
12#include <chrono>
13#include <cstdint>
14#include <cstdio>
15#include <cstdlib>
16#include <iostream>
17#include <memory>
18#include <thread>
19
20namespace strata_vit {
21
22namespace {
23
24// "ENC <image> <out>": the image path ends at the last space before the output path (a path of the image may hold spaces)
25bool parse_enc(const std::string& line, std::string& img, std::string& out) {
26    if (line.rfind("ENC ", 0) != 0) return false;
27    const std::string rest = line.substr(4);
28    const size_t sp = rest.rfind(' ');
29    if (sp == std::string::npos || sp == 0) return false;
30    img = rest.substr(0, sp);
31    out = rest.substr(sp + 1);
32    return !img.empty() && !out.empty();
33}
34
35}  // namespace
36
37std::string vision_tower_default(const char* env, std::string& note) {
38    const std::string v = env ? env : "";
39    if (v == "mtmd" || v == "own" || v == "auto") return v;
40    if (!v.empty()) note = "STRATA_VISION_TOWER=" + v + " is not mtmd, own or auto; using auto";
41    return "auto";
42}
43
44bool own_reader_inject_failure(const char* point) {
45    const char* v = std::getenv("STRATA_VIT_TEST_FAIL");
46    return v && point && std::string(v) == point;
47}
48
49bool own_reader_supported(const std::string& mmproj, bool gpu, int max_tokens, std::string& why) {
50    if (gpu) {
51#ifdef STRATA_VIT_GPU
52        bool bf16 = false;      // the layer matrices' type decides on Pascal (vit_gpu.h)
53        {
54            Gguf g0;
55            std::string e0;
56            if (g0.open(mmproj, e0))
57                if (const GgufTensorInfo* t = g0.tensor("v.blk.0.attn_qkv.weight")) bf16 = t->type == GT_BF16;
58        }
59        if (!VitGpu::available(why) || VitGpu::prefer_mtmd(bf16, max_tokens, why)) return false;
60#else
61        why = "this build has no GPU backend for the own tower";
62        return false;
63#endif
64    }
65    // (an MSVC x86 build kept mtmd here until 11-11; since 54f9cc3c0 it is 0.986 of mtmd-CPU's time at 1,024 tokens, RESULTS-OWN-3V.md D2, so that rule is gone)
66    Gguf gg;
67    VitGeometry g;
68    if (!gg.open(mmproj, why) || !vit_geometry_from_gguf(gg, g, why)) return false;
69    if (!gpu) return own_cpu_reader_supported(g, quant::best_isa(), why);
70    if (!vit_geometry_supported(g, why)) return false;
71    if (g.head_dim > 96) { why = "a head size above 96 is not handled by the GPU attention"; return false; }   // `auto` then reads with mtmd
72    return true;
73}
74
75bool own_cpu_reader_supported(const VitGeometry& g, quant::Isa isa, std::string& why) {
76    // Every CPU tier is allowed (owner 11-11, "make ours the default" below AVX2 too).  Until then an x86 CPU whose best tier was scalar, sse41 or avx kept mtmd under
77    // `auto`; the tiers were gated since (RESULTS-OWN-3V.md PART H: rule 1 on both reader files, byte-identical repeats, no instruction above the CPU's tier outside the
78    // CPU-checked kernels, timed against llama.cpp's reader built for the same CPU class: 0.05 to 0.35 of its time, one cell 1.04).  `isa` stays an argument so a
79    // per-tier rule is one line here and has a test.
80    (void) isa;
81    return vit_geometry_supported(g, why);
82}
83
84std::string vision_tower_resolve(const std::string& tower, bool own_ok) {
85    if (tower == "mtmd" || tower == "own") return tower;      // an explicit choice is never overruled, either way
86    return own_ok ? "own" : "mtmd";                           // auto
87}
88
89int own_reader_run(const OwnReaderOptions& o) {
90    using clock = std::chrono::steady_clock;
91    const auto load_t0 = clock::now();
92    // every return before READY goes through here: under `auto` the reason goes back to strata-vision, which starts mtmd's reader (nothing on stdout yet)
93    auto fail = [&o](const std::string& msg, int code) {
94        if (o.start_error) {
95            *o.start_error = msg;
96            return kOwnStartFailed;
97        }
98        std::printf("ERR %s\n", msg.c_str());
99        std::fflush(stdout);
100        return code;
101    };
102    const std::string injected = " (injected for a test: STRATA_VIT_TEST_FAIL)";
103#ifndef STRATA_VIT_GPU
104    if (o.gpu) return fail("this build has no GPU backend for the own tower (use --tower mtmd)", 3);
105#endif
106    Gguf gg;
107    VitGeometry geo;
108    std::string err;
109    if (!gg.open(o.mmproj, err) || !vit_geometry_from_gguf(gg, geo, err) || !vit_geometry_supported(geo, err))
110        return fail("cannot load the vision encoder " + o.mmproj + " (" + err + ")", 1);
111    int threads = o.threads;
112    std::unique_ptr<VitRef> cpu;
113    std::unique_ptr<VitCpu> fast;
114#ifdef STRATA_VIT_GPU
115    std::unique_ptr<VitGpu> gpu;
116    if (o.gpu) {
117        std::string why;
118        if (own_reader_inject_failure("gpu")) return fail("this picture reader found no GPU" + injected, 3);
119        if (!VitGpu::available(why)) return fail("this picture reader found no GPU (" + why + ")", 3);
120        gpu.reset(new VitGpu());
121        // buffers for the warm-up picture below (2048 x 2048: 4,096 tokens at most, fewer under a lower limit): claimed now, before READY.  A larger limit
122        // (the app allows up to 16,384 image tokens) grows them when such a picture comes: slower for that picture, never an error.
123        const int tokens = std::min(o.max_tokens > 0 ? o.max_tokens : geo.max_tokens, 4096);
124        if (!gpu->load(gg, geo, 0, tokens * 4, err)) return fail("cannot load the vision encoder " + o.mmproj + " (" + err + ")", 1);
125        if (own_reader_inject_failure("load")) return fail("cannot load the vision encoder " + o.mmproj + injected, 1);   // after the load: its memory is freed on return
126    }
127#endif
128    if (!o.gpu) {
129        // the CPU path of the own tower is the fast tower (VitCpu); STRATA_VIT_CPU=ref selects the float32 reference (VitRef: the oracle, for tests)
130        const char* sel = std::getenv("STRATA_VIT_CPU");
131        if (!(sel && std::string(sel) == "ref")) {
132            fast.reset(new VitCpu());
133            if (!fast->load(gg, geo, err)) return fail("cannot load the vision encoder " + o.mmproj + " (" + err + ")", 1);
134        } else {
135            cpu.reset(new VitRef());
136            if (!cpu->load(gg, geo, err)) return fail("cannot load the vision encoder " + o.mmproj + " (" + err + ")", 1);
137        }
138        if (own_reader_inject_failure("load")) return fail("cannot load the vision encoder " + o.mmproj + injected, 1);
139        if (threads <= 0) threads = (int) std::max(1u, std::min(16u, std::thread::hardware_concurrency() / 2));
140    }
141    std::fprintf(stderr, "strata-vision: own tower (%s, %d layers, width %d) loaded in %.1f s, %s\n", geo.projector.c_str(), geo.layers, geo.width,
142                 std::chrono::duration<double>(clock::now() - load_t0).count(), o.gpu ? "on the GPU" : ("on the CPU, " + std::to_string(threads) + " threads").c_str());
143    auto encode = [&](const PreparedImage& prep, std::vector<float>& rows, int& nx, int& ny, std::string& e) {
144#ifdef STRATA_VIT_GPU
145        if (gpu) return gpu->encode(prep, rows, nx, ny, e);
146#endif
147        if (fast) return fast->encode(prep, threads, rows, nx, ny, e);
148        return cpu->encode(prep, threads, rows, nx, ny, e);
149    };
150#ifdef STRATA_VIT_GPU
151    if (gpu) {   // warm up at the largest picture before READY: the work buffers are taken now, not at the first real picture
152        const auto w0 = clock::now();
153        ImageU8 gray;
154        gray.w = gray.h = 2048;
155        gray.rgb.assign((size_t) 2048 * 2048 * 3, 128);
156        PreparedImage wp;
157        std::vector<float> rows;
158        int nx = 0, ny = 0;
159        err.clear();
160        if (own_reader_inject_failure("warmup")) err = "out of GPU memory" + injected;
161        if (err.empty() && prepare_image(gray, geo, o.min_tokens, o.max_tokens, wp, err) && encode(wp, rows, nx, ny, err))
162            std::fprintf(stderr, "strata-vision: warmed up at %d image tokens in %.1f s, %.0f MiB of GPU memory\n", nx * ny,
163                         std::chrono::duration<double>(clock::now() - w0).count(), (double) gpu->device_bytes() / 1048576.0);
164        else
165            return fail("the vision encoder failed its warm-up (" + err + ")", 1);
166    }
167#endif
168    std::printf("READY %d own\n", geo.out_dim);   // the third word names the reader (a server reads only the start: "READY")
169    std::fflush(stdout);
170
171    std::string line;
172    while (std::getline(std::cin, line)) {
173        while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) line.pop_back();
174        if (line == "QUIT") break;
175        std::string img, out;
176        if (!parse_enc(line, img, out)) { std::printf("ERR expected: ENC <image> <output>\n"); std::fflush(stdout); continue; }
177        const auto t0 = clock::now();
178        ImageU8 src;
179        PreparedImage prep;
180        if (!image_load_file(img, src, err)) { std::printf("ERR cannot read the image %s\n", img.c_str()); std::fflush(stdout); continue; }
181        if (!prepare_image(src, geo, o.min_tokens, o.max_tokens, prep, err)) { std::printf("ERR the image could not be preprocessed (%s)\n", err.c_str()); std::fflush(stdout); continue; }
182        const int n_expect = (prep.w / geo.align()) * (prep.h / geo.align());
183        // never silently produce many times the budget (I7, #3690): over the limit (a rounding margin of an eighth) the picture is refused
184        if (o.max_tokens > 0 && n_expect > o.max_tokens + o.max_tokens / 8) {
185            std::printf("ERR the picture became %d image tokens, over the limit of %d (vision.max_tokens); send a smaller picture or raise the limit\n", n_expect,
186                        o.max_tokens);
187            std::fflush(stdout);
188            continue;
189        }
190        std::vector<float> rows;
191        int nx = 0, ny = 0;
192        if (std::getenv("STRATA_VIT_PROF"))
193            std::fprintf(stderr, "vit-prof: read + decode + prepare %.2f ms\n", std::chrono::duration<double, std::milli>(clock::now() - t0).count());
194        if (!encode(prep, rows, nx, ny, err)) { std::printf("ERR the vision encoder failed (%s)\n", err.c_str()); std::fflush(stdout); continue; }
195        const int n = nx * ny;
196        FILE* f = std::fopen(out.c_str(), "wb");
197        if (!f) { std::printf("ERR cannot write %s\n", out.c_str()); std::fflush(stdout); continue; }
198        const int32_t hdr[5] = {0x31455653, n, nx, ny, geo.out_dim};
199        const bool ok = std::fwrite(hdr, sizeof hdr, 1, f) == 1 && std::fwrite(rows.data(), sizeof(float) * (size_t) geo.out_dim, (size_t) n, f) == (size_t) n;
200        std::fclose(f);
201        if (!ok) { std::printf("ERR short write to %s\n", out.c_str()); std::fflush(stdout); continue; }
202        const double ms = std::chrono::duration<double, std::milli>(clock::now() - t0).count();
203        std::printf("OK %d %d %d %.0f\n", n, nx, ny, ms);
204        std::fflush(stdout);
205    }
206    return 0;
207}
208
209}  // namespace strata_vit