okami.mom/strata

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

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

main
20.6 KiB380 linesraw
1// tools/vision/strata_vision.cpp - the image half of Strata's multimodal path.
2//
3// Turns an image into the embeddings the text model reads in place of its <|image_pad|> tokens, with llama.cpp's
4// mtmd library and the model's mmproj file (vision encoder + projector).  The engine does the rest: it places the
5// rows at the image's pad tokens and gives them their 2-D M-RoPE positions (see --serve GENI in generate.cpp).
6//
7//   strata-vision --mmproj <mmproj.gguf> --model <text model .gguf, first split> [--gpu] [--threads N]
8//                 [--max-tokens N] [--min-tokens N] [--flash-attn on|off|auto]
9// Flash attention defaults to auto, and to off on the CPU when ggml is built with AVX-512 (see main).
10//
11// Resident: prints "READY <n_embd> <reader>" (reader: own or mtmd; older builds print two words), then per stdin line
12//   ENC <image path> <output path>   ->  "OK <n_tokens> <nx> <ny> <ms>"  or  "ERR <message>"
13//   QUIT
14// The output file is  int32 {0x31455653 'SVE1', n_tokens, nx, ny, n_embd}  then float32 [n_tokens][n_embd],
15// row i at grid position (x = i % nx, y = i / nx).  The text model is opened vocab-only (no weights).
16#include "ggml-backend.h"
17#include "ggml-cpu.h"
18#include "gguf.h"
19#include "gguf_meta.h"
20#include "gpu_arch.h"
21#include "llama.h"
22#include "mtmd.h"
23#include "mtmd-helper.h"
24#include "own_reader.h"
25
26#include <algorithm>
27#if !defined(_WIN32)
28#include <fcntl.h>
29#include <unistd.h>
30#elif defined(STRATA_VISION_HIP)
31#define WIN32_LEAN_AND_MEAN
32#define NOMINMAX
33#include <windows.h>
34#endif
35#include <chrono>
36#include <cstdio>
37#include <cstdlib>
38#include <cstring>
39#include <iostream>
40#include <sstream>
41#include <string>
42#include <thread>
43#include <vector>
44
45namespace {
46
47// the GPU architectures ggml-hip printed while it started ("  Device 0: ..., gfx1201:sramecc-:xnack- (0x1201), ...")
48std::vector<std::string> g_gfx;
49
50void quiet_log(ggml_log_level level, const char* text, void*) {
51    if (level == GGML_LOG_LEVEL_INFO && std::strstr(text, "Device ") != nullptr) {
52        const std::string gfx = strata_gfx_in(text);
53        if (!gfx.empty()) g_gfx.push_back(gfx);
54    }
55    if (level >= GGML_LOG_LEVEL_WARN) std::fputs(text, stderr);
56}
57
58// "ENC <image> <out>": paths may contain spaces, so the image path ends at the last " " before the output path;
59// the server always writes paths without spaces, but a user calling the tool by hand might not
60bool parse_enc(const std::string& line, std::string& img, std::string& out) {
61    if (line.rfind("ENC ", 0) != 0) return false;
62    const std::string rest = line.substr(4);
63    const size_t sp = rest.rfind(' ');
64    if (sp == std::string::npos || sp == 0) return false;
65    img = rest.substr(0, sp);
66    out = rest.substr(sp + 1);
67    return !img.empty() && !out.empty();
68}
69
70}  // namespace
71
72int main(int argc, char** argv) {
73#if defined(_WIN32) && defined(STRATA_VISION_HIP)
74    // hipblas.dll is delay-loaded (tools/vision/CMakeLists.txt): it and the ROCm DLLs behind it (rocblas.dll finds its kernel
75    // library and ../.kpack beside itself) stay in rocm\bin of the engine package, which is not on the DLL search path of a
76    // program started with nothing but System32 in PATH.  Put that folder on it before the first call.
77    {
78        wchar_t exe[MAX_PATH];
79        const DWORD n = GetModuleFileNameW(nullptr, exe, MAX_PATH);
80        std::wstring dir(exe, n);
81        const size_t cut = dir.find_last_of(L"\\/");
82        if (cut != std::wstring::npos) {
83            dir.resize(cut);
84            const std::wstring rocm = dir + L"\\rocm\\bin";
85            if (GetFileAttributesW(rocm.c_str()) != INVALID_FILE_ATTRIBUTES) SetDllDirectoryW(rocm.c_str());
86        }
87    }
88#endif
89    std::string mmproj, model;
90    bool gpu = false;
91    int threads = 0, max_tokens = 0, min_tokens = 0;
92    llama_flash_attn_type fa = LLAMA_FLASH_ATTN_TYPE_AUTO;
93    bool fa_given = false;
94    // --tower mtmd|own|auto: whose picture reader runs (own-stack phase 3).  The default is auto (owner 11-11: our tower the default, mtmd selectable): ours
95    // where it was measured no slower and correct, mtmd's by itself where it was measured slower (own_reader_supported).  Without --tower the environment's
96    // STRATA_VISION_TOWER decides (the model's run config carries STRATA_VISION_TOWER=mtmd when someone picks llama.cpp's reader in the settings; an older
97    // strata-vision ignores it).  An explicit --tower wins.
98    std::string tower_note;
99    std::string tower = strata_vit::vision_tower_default(std::getenv("STRATA_VISION_TOWER"), tower_note);
100    if (!tower_note.empty()) std::fprintf(stderr, "strata-vision: %s\n", tower_note.c_str());
101    for (int i = 1; i < argc; ++i) {
102        const std::string a = argv[i];
103        auto next = [&]() -> std::string {
104            if (i + 1 >= argc) { std::fprintf(stderr, "%s needs a value\n", a.c_str()); std::exit(2); }
105            return argv[++i];
106        };
107        if (a == "--mmproj") mmproj = next();
108        else if (a == "--model") model = next();
109        else if (a == "--gpu") gpu = true;
110        else if (a == "--tower") {
111            tower = next();
112            if (tower != "mtmd" && tower != "own" && tower != "auto") { std::fprintf(stderr, "--tower takes mtmd, own or auto\n"); return 2; }
113        }
114        else if (a == "--version") {
115#ifdef STRATA_VISION_HIP
116            std::printf("strata-vision hip (GPU architectures: %s)\n", STRATA_VISION_HIP_ARCHS);
117#elif defined(STRATA_VISION_METAL)
118            std::printf("strata-vision metal\n");
119#elif defined(STRATA_VISION_SYCL)
120            std::printf("strata-vision sycl (Intel GPU)\n");
121#else
122            std::printf("strata-vision\n");
123#endif
124            return 0;
125        }
126        else if (a == "--threads") threads = std::atoi(next().c_str());
127        else if (a == "--max-tokens") max_tokens = std::atoi(next().c_str());
128        else if (a == "--min-tokens") min_tokens = std::atoi(next().c_str());   // mtmd image_min_tokens (#767)
129        else if (a == "--flash-attn") {   // FA keeps K and V in FP16; off = the attention in FP32
130            const std::string v = next();
131            fa = v == "on" ? LLAMA_FLASH_ATTN_TYPE_ENABLED : v == "off" ? LLAMA_FLASH_ATTN_TYPE_DISABLED
132                                                                        : LLAMA_FLASH_ATTN_TYPE_AUTO;
133            fa_given = true;
134        }
135        else { std::fprintf(stderr, "unknown argument %s\n", a.c_str()); return 2; }
136    }
137    // auto: our tower where it can read this file on this backend, else mtmd; when ours then fails before READY, mtmd's reader starts in its place
138    bool own_may_fall_back = false, own_fell_back = false;
139    if (tower == "auto") {
140        std::string why;
141        tower = strata_vit::vision_tower_resolve(tower, !mmproj.empty() && strata_vit::own_reader_supported(mmproj, gpu, max_tokens, why));
142        own_may_fall_back = tower == "own" && !model.empty();   // mtmd needs the text model's header
143        if (tower == "mtmd" && !why.empty()) std::fprintf(stderr, "strata-vision: llama.cpp's reader (%s)\n", why.c_str());
144    }
145    if (mmproj.empty() || (model.empty() && tower != "own")) {   // our tower needs no text model: it never tokenizes
146        std::fprintf(stderr, "usage: strata-vision --mmproj <mmproj.gguf> --model <model.gguf> [--gpu] [--threads N] "
147                             "[--max-tokens N] [--min-tokens N] [--flash-attn on|off|auto]\n");
148        return 2;
149    }
150    // On the CPU the GPU stays unseen: a CUDA build otherwise opens a context there (measured: 0.4-0.7 GB of VRAM,
151    // 150-260 expert slots less for the engine beside it).  Before anything reaches the CUDA runtime.
152    if (!gpu) {
153#ifdef _WIN32
154        _putenv_s("CUDA_VISIBLE_DEVICES", "-1");
155        _putenv_s("HIP_VISIBLE_DEVICES", "-1");
156#else
157        setenv("CUDA_VISIBLE_DEVICES", "-1", 1);
158        setenv("HIP_VISIBLE_DEVICES", "-1", 1);
159#endif
160    }
161    if (tower == "own") {
162        strata_vit::OwnReaderOptions o;
163        o.mmproj = mmproj;
164        o.gpu = gpu;
165        o.threads = threads;
166        o.max_tokens = max_tokens;
167        o.min_tokens = min_tokens;
168        std::string start_error;
169        if (own_may_fall_back) o.start_error = &start_error;
170        const int rc = strata_vit::own_reader_run(o);
171        if (rc != strata_vit::kOwnStartFailed) return rc;
172        // nothing was written to stdout yet: the server still waits for READY, which mtmd's reader below gives (with "mtmd" as its third word)
173        std::fprintf(stderr, "strata-vision: Strata's picture reader did not start (%s); reading pictures with llama.cpp's reader\n", start_error.c_str());
174        std::fflush(stderr);
175        own_fell_back = true;
176    }
177    llama_log_set(quiet_log, nullptr);
178    mtmd_helper_log_set(quiet_log, nullptr);
179    llama_backend_init();
180#if defined(STRATA_VISION_HIP) || defined(STRATA_VISION_SYCL)
181#ifdef STRATA_VISION_SYCL
182#define STRATA_VISION_BUILT_FOR "Intel GPUs"
183#else
184#define STRATA_VISION_BUILT_FOR STRATA_VISION_HIP_ARCHS
185#endif
186    if (gpu) {
187        // The AMD / Intel GPU reader: starting the backends prints the GPU line.  With --gpu and no GPU, mtmd would quietly use the CPU
188        // (a second, slower CPU reader inside the HIP program), and a card the build has no code for would abort at its first
189        // kernel.  Both end here with a line the server reads: it then starts the CPU reader (serve/server.py, Vision._start).
190        bool have_gpu = false;
191        for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
192            const auto type = ggml_backend_dev_type(ggml_backend_dev_get(i));
193            have_gpu = have_gpu || type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU;
194        }
195        if (!have_gpu) {
196            std::printf("ERR this picture reader found no GPU (it was built for: %s)\n", STRATA_VISION_BUILT_FOR);
197            std::fflush(stdout);
198            return 3;
199        }
200#ifdef STRATA_VISION_HIP
201        const char* check = std::getenv("STRATA_VISION_ARCH_CHECK");
202        if (!g_gfx.empty() && (check == nullptr || std::atoi(check) != 0) &&
203            !strata_arch_listed(STRATA_VISION_HIP_ARCHS, g_gfx.front())) {
204            std::printf("ERR this GPU (%s) is not in the picture reader's build (%s)\n", g_gfx.front().c_str(),
205                        STRATA_VISION_HIP_ARCHS);
206            std::fflush(stdout);
207            return 3;
208        }
209#endif
210    }
211#endif
212#ifdef STRATA_VISION_METAL
213    if (gpu) {
214        // The Mac: the same program reads on the GPU (--gpu, ggml's Metal backend) or on the CPU.  With --gpu and no Metal device (a
215        // virtual machine without a GPU, say), mtmd would quietly use the CPU, which reads a picture in ~50 s: say so instead, and
216        // the server starts the program again without --gpu (serve/server.py, Vision._start) with one log line.
217        bool have_gpu = false;
218        for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
219            const auto type = ggml_backend_dev_type(ggml_backend_dev_get(i));
220            have_gpu = have_gpu || type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU;
221        }
222        if (!have_gpu) {
223            std::printf("ERR this Mac has no Metal GPU for the picture reader\n");
224            std::fflush(stdout);
225            return 3;
226        }
227    }
228#endif
229
230    const auto load_t0 = std::chrono::steady_clock::now();
231#if !defined(_WIN32) && !defined(__APPLE__)   // macOS has no posix_fadvise
232    // ask the OS for the projector file up front (128 KiB steps) so the loader's sequential reads find it cached;
233    // STRATA_READ_AHEAD=0 turns it off, as in the engine
234    if (const char* ra = std::getenv("STRATA_READ_AHEAD"); ra == nullptr || std::atoi(ra) != 0) {
235        const int fd = open(mmproj.c_str(), O_RDONLY);
236        if (fd >= 0) {
237            const off_t n = lseek(fd, 0, SEEK_END);
238            for (off_t at = 0; at < n; at += (off_t) (128 << 10))
239                (void) posix_fadvise(fd, at, std::min<off_t>((off_t) (128 << 10), n - at), POSIX_FADV_WILLNEED);
240            close(fd);
241        }
242    }
243#endif
244    // the vocabulary and header only: the weights (and their tensor types, which can be Strata-private ones such as
245    // Gyro's TQK6 / TQK7) are never touched - see gguf_meta.h
246    std::string how;
247    llama_model* text = strata_open_text_model(model, &how);
248    if (!text) { std::printf("ERR cannot open the text model %s (%s)\n", model.c_str(), how.c_str()); std::fflush(stdout); return 1; }
249
250    mtmd_context_params cp = mtmd_context_params_default();
251    cp.use_gpu = gpu;
252    cp.print_timings = false;
253    cp.warmup = false;
254    // On the CPU "auto" turns flash attention on.  ggml's fast (tiled) CPU kernel for it needs the head size, 72 in this
255    // encoder, to be a multiple of the vector width: 8 floats with AVX2 (the release builds), 16 with AVX-512 (a build
256    // from source on a CPU that has it), where ggml falls back to a kernel that is several times slower and accumulates
257    // in FP16.  A 1024x1024 picture on a Ryzen 7 7700X, 8 threads: AVX2 8-10 s with it, 14-15 s without; AVX-512 44 s
258    // with it (26% off the FP32 attention's output), 13 s without.
259    if (!gpu && !fa_given && ggml_cpu_has_avx512()) fa = LLAMA_FLASH_ATTN_TYPE_DISABLED;
260    cp.flash_attn_type = fa;
261    // on the CPU without --threads: one per core (mtmd's own default is 4 threads)
262    // (at most 16: a 256-thread server does not need 128 encoder threads; --threads overrides)
263    if (threads <= 0 && !gpu) threads = std::max(1u, std::min(16u, std::thread::hardware_concurrency() / 2));
264    if (threads > 0) cp.n_threads = threads;
265    if (max_tokens > 0) cp.image_max_tokens = max_tokens;
266    if (min_tokens > 0) cp.image_min_tokens = min_tokens;
267    mtmd_context* ctx = mtmd_init_from_file(mmproj.c_str(), text, cp);
268    if (!ctx || !mtmd_support_vision(ctx)) {
269        std::printf("ERR cannot load the vision encoder %s\n", mmproj.c_str());
270        std::fflush(stdout);
271        return 1;
272    }
273    std::fprintf(stderr, "strata-vision: model files loaded in %.1f s\n",
274                 std::chrono::duration<double>(std::chrono::steady_clock::now() - load_t0).count());
275    // a vocab-only model reports no hparams, so the width comes from the projector: its output is the model's input
276    int n_embd = 0;
277    {
278        gguf_init_params gp{true, nullptr};
279        gguf_context* gg = gguf_init_from_file(mmproj.c_str(), gp);
280        const int64_t k = gg ? gguf_find_key(gg, "clip.vision.projection_dim") : -1;
281        if (k >= 0) n_embd = (int) gguf_get_val_u32(gg, k);
282        if (gg) gguf_free(gg);
283    }
284    if (n_embd <= 0) { std::printf("ERR the vision encoder has no projection_dim\n"); std::fflush(stdout); return 1; }
285    // Warm up at the LARGEST picture before READY: the encoder's GPU work buffers are allocated now, not at the first
286    // real picture.  The server starts this process before the engine, so the engine sizes its expert cache from
287    // what is really left; allocating ~1 GB later, on a GPU the engine has filled, made Windows page GPU memory and
288    // the engine crawl to a standstill.  (A square image well above any cap; mtmd scales it to the token limit.)
289    // On the CPU there is no VRAM to reserve, and the warm-up would only delay the engine's start by one encode
290    // (~6 s at 1,024 tokens).
291    if (!gpu) std::fprintf(stderr, "strata-vision: on the CPU, %d threads, no warm-up\n", threads);
292    else {
293        const auto warm_t0 = std::chrono::steady_clock::now();
294        const uint32_t side = 2048;
295        std::vector<unsigned char> rgb((size_t) side * side * 3, 128);
296        mtmd_bitmap* bm = mtmd_bitmap_init(side, side, rgb.data());
297        mtmd_input_chunks* chunks = mtmd_input_chunks_init();
298        const std::string marker = mtmd_default_marker();
299        mtmd_input_text txt{marker.c_str(), marker.size(), false, true};
300        const mtmd_bitmap* bms[1] = {bm};
301        int warm_tokens = 0;
302        if (bm && mtmd_tokenize(ctx, chunks, &txt, bms, 1) == 0) {
303            for (size_t c = 0; c < mtmd_input_chunks_size(chunks); ++c) {
304                const mtmd_input_chunk* ch = mtmd_input_chunks_get(chunks, c);
305                if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE && mtmd_encode_chunk(ctx, ch) == 0)
306                    warm_tokens = (int) mtmd_input_chunk_get_n_tokens(ch);
307            }
308        }
309        std::fprintf(stderr, "strata-vision: warmed up at %d image tokens in %.1f s\n", warm_tokens,
310                     std::chrono::duration<double>(std::chrono::steady_clock::now() - warm_t0).count());
311        // I7 (#3690): a picture that became 93,700 image tokens under --max-tokens 1024. The limit is not applied by this build of mtmd for
312        // this model, and the log line above is the evidence to ask for.
313        if (max_tokens > 0 && warm_tokens > max_tokens + max_tokens / 8)
314            std::fprintf(stderr, "strata-vision: WARNING the warm-up picture became %d image tokens, over the limit of %d (--max-tokens): "
315                                 "the limit is not applied for this model; pictures over it are refused\n", warm_tokens, max_tokens);
316        mtmd_input_chunks_free(chunks);
317        if (bm) mtmd_bitmap_free(bm);
318    }
319    // the third word names the reader; a fourth, "fallback", says our tower failed before READY (a server reads only the start: "READY")
320    std::printf("READY %d mtmd%s\n", n_embd, own_fell_back ? " fallback" : "");
321    std::fflush(stdout);
322
323    std::string line;
324    while (std::getline(std::cin, line)) {
325        while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) line.pop_back();
326        if (line == "QUIT") break;
327        std::string img, out;
328        if (!parse_enc(line, img, out)) { std::printf("ERR expected: ENC <image> <output>\n"); std::fflush(stdout); continue; }
329        const auto t0 = std::chrono::steady_clock::now();
330        mtmd_helper_bitmap_wrapper bw = mtmd_helper_bitmap_init_from_file(ctx, img.c_str(), false,
331                                                                            mtmd_helper_init_opt_default());
332        if (!bw.bitmap) { std::printf("ERR cannot read the image %s\n", img.c_str()); std::fflush(stdout); continue; }
333        mtmd_input_chunks* chunks = mtmd_input_chunks_init();
334        const std::string prompt = mtmd_default_marker();
335        mtmd_input_text txt{prompt.c_str(), prompt.size(), false, true};
336        const mtmd_bitmap* bm[1] = {bw.bitmap};
337        std::string err;
338        const mtmd_input_chunk* ichunk = nullptr;
339        if (mtmd_tokenize(ctx, chunks, &txt, bm, 1) != 0) err = "the image could not be preprocessed";
340        for (size_t c = 0; err.empty() && c < mtmd_input_chunks_size(chunks); ++c) {
341            const mtmd_input_chunk* ch = mtmd_input_chunks_get(chunks, c);
342            if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_IMAGE) ichunk = ch;
343        }
344        if (err.empty() && !ichunk) err = "no image chunk";
345        if (err.empty() && mtmd_encode_chunk(ctx, ichunk) != 0) err = "the vision encoder failed";
346        if (err.empty()) {
347            const mtmd_image_tokens* it = mtmd_input_chunk_get_tokens_image(ichunk);
348            const int n = (int) mtmd_input_chunk_get_n_tokens(ichunk);
349            // the grid from the decoder positions (nx/ny getters are deprecated): x and y of the last token
350            const mtmd_decoder_pos last = mtmd_image_tokens_get_decoder_pos(it, 0, (size_t) n - 1);
351            const int nx = (int) last.x + 1, ny = (int) last.y + 1;
352            if (nx * ny != n) err = "the image grid is not rectangular (" + std::to_string(n) + " tokens)";
353            // never silently produce many times the budget (I7, #3690): over the limit (a rounding margin of an eighth) the picture is refused
354            if (err.empty() && max_tokens > 0 && n > max_tokens + max_tokens / 8)
355                err = "the picture became " + std::to_string(n) + " image tokens, over the limit of " + std::to_string(max_tokens) +
356                      " (vision.max_tokens); send a smaller picture or raise the limit";
357            const float* embd = mtmd_get_output_embd(ctx);
358            FILE* f = err.empty() ? std::fopen(out.c_str(), "wb") : nullptr;
359            if (err.empty() && !f) err = "cannot write " + out;
360            if (f) {
361                const int32_t hdr[5] = {0x31455653, n, nx, ny, n_embd};
362                const bool ok = std::fwrite(hdr, sizeof hdr, 1, f) == 1 &&
363                                std::fwrite(embd, sizeof(float) * (size_t) n_embd, (size_t) n, f) == (size_t) n;
364                std::fclose(f);
365                if (!ok) err = "short write to " + out;
366                const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
367                if (ok) std::printf("OK %d %d %d %.0f\n", n, nx, ny, ms);
368            }
369        }
370        if (!err.empty()) std::printf("ERR %s\n", err.c_str());
371        std::fflush(stdout);
372        mtmd_input_chunks_free(chunks);
373        mtmd_bitmap_free(bw.bitmap);
374        if (bw.video_ctx) mtmd_helper_video_free(bw.video_ctx);
375    }
376    mtmd_free(ctx);
377    llama_model_free(text);
378    llama_backend_free();
379    return 0;
380}