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
10.3 KiB228 linesraw
1// tools/vision/own/image_prep.cpp - see image_prep.h
2//
3// The resize below is a port of llama.cpp's tools/mtmd/mtmd-image.cpp (resize_pillow, calc_size_preserved_ratio, img_tool::resize),
4// itself adapted from Pillow's Resample.c.  llama.cpp: MIT, Copyright (c) 2023-2026 The ggml authors.  Pillow: HPND.
5#include "image_prep.h"
6
7#include <algorithm>
8#include <cmath>
9#include <cstdio>
10#include <cstring>
11
12#define STBI_NO_STDIO
13#define STB_IMAGE_STATIC            // private to this file: the mtmd build of strata-vision has its own copy of stb_image
14#define STB_IMAGE_IMPLEMENTATION
15#include "stb_image.h"
16
17namespace strata_vit {
18
19bool image_decode(const uint8_t* data, size_t n, ImageU8& out, std::string& err) {
20    int nx = 0, ny = 0, nc = 0;
21    if (n == 0 || n > 0x7FFFFFFFu) { err = "the picture is empty or too large"; return false; }
22    unsigned char* px = stbi_load_from_memory(data, (int) n, &nx, &ny, &nc, 3);
23    if (!px) { err = std::string("cannot decode the picture: ") + stbi_failure_reason(); return false; }
24    out.w = nx;
25    out.h = ny;
26    out.rgb.assign(px, px + (size_t) nx * ny * 3);
27    stbi_image_free(px);
28    return true;
29}
30
31bool image_load_file(const std::string& path, ImageU8& out, std::string& err) {
32    FILE* f = std::fopen(path.c_str(), "rb");
33    if (!f) { err = "cannot open " + path; return false; }
34    std::vector<uint8_t> buf;
35    uint8_t tmp[1 << 16];
36    size_t k;
37    while ((k = std::fread(tmp, 1, sizeof tmp, f)) > 0) buf.insert(buf.end(), tmp, tmp + k);
38    std::fclose(f);
39    return image_decode(buf.data(), buf.size(), out, err);
40}
41
42Size2 smart_resize(int width, int height, int align, int min_pixels, int max_pixels) {
43    if (width <= 0 || height <= 0 || align <= 0) return {0, 0};
44    // the same float arithmetic as mtmd (calc_size_preserved_ratio with longest_edge off)
45    auto round_by_factor = [align](float x) { return static_cast<int>(std::round(x / static_cast<float>(align))) * align; };
46    auto ceil_by_factor = [align](float x) { return static_cast<int>(std::ceil(x / static_cast<float>(align))) * align; };
47    auto floor_by_factor = [align](float x) { return static_cast<int>(std::floor(x / static_cast<float>(align))) * align; };
48    int w_bar = std::max(align, round_by_factor((float) width));
49    int h_bar = std::max(align, round_by_factor((float) height));
50    if (max_pixels > 0 && h_bar * w_bar > max_pixels) {
51        const auto beta = std::sqrt(static_cast<float>(height) * width / max_pixels);
52        h_bar = std::max(align, floor_by_factor(height / beta));
53        w_bar = std::max(align, floor_by_factor(width / beta));
54    } else if (min_pixels > 0 && h_bar * w_bar < min_pixels) {
55        const auto beta = std::sqrt(static_cast<float>(min_pixels) / (static_cast<float>(height) * width));
56        h_bar = ceil_by_factor(height * beta);
57        w_bar = ceil_by_factor(width * beta);
58    }
59    return {w_bar, h_bar};
60}
61
62namespace {
63
64const int PRECISION_BITS = 32 - 8 - 2;   // 22 fractional bits: 32 - 8 (uint8 pixels) - 2 (headroom for the accumulation)
65
66double bicubic(double x) {               // Pillow's a = -0.5
67    if (x < 0.0) x = -x;
68    constexpr double a = -0.5;
69    if (x < 1.0) return ((a + 2.0) * x - (a + 3.0)) * x * x + 1;
70    if (x < 2.0) return (((x - 5) * x + 8) * x - 4) * a;
71    return 0.0;
72}
73
74uint8_t clip8(int v) { return v < 0 ? 0 : v > 255 ? 255 : (uint8_t) v; }
75
76// the filter coefficients of one dimension: bounds[2 i] first input pixel, bounds[2 i + 1] their count; weights in fixed point; returns the kernel size
77int precompute_weights(int in_size, int out_size, std::vector<int>& bounds, std::vector<int32_t>& weights) {
78    double filterscale, scale;
79    filterscale = scale = (double) in_size / out_size;
80    if (filterscale < 1.0) filterscale = 1.0;
81    const double support = 2.0 * filterscale;
82    const int ksize = (int) std::ceil(support) * 2 + 1;
83    std::vector<double> pre((size_t) out_size * ksize);
84    bounds.resize((size_t) out_size * 2);
85    for (int xx = 0; xx < out_size; ++xx) {
86        const double center = (xx + 0.5) * scale;
87        double ww = 0.0;
88        const double ss = 1.0 / filterscale;
89        int xmin = (int) (center - support + 0.5);
90        if (xmin < 0) xmin = 0;
91        int xmax = (int) (center + support + 0.5);
92        if (xmax > in_size) xmax = in_size;
93        xmax -= xmin;
94        int x = 0;
95        for (; x < xmax; ++x) {
96            const double w = bicubic((x + xmin - center + 0.5) * ss);
97            pre[(size_t) xx * ksize + x] = w;
98            ww += w;
99        }
100        for (x = 0; x < xmax; ++x)
101            if (ww != 0.0) pre[(size_t) xx * ksize + x] /= ww;
102        for (; x < ksize; ++x) pre[(size_t) xx * ksize + x] = 0;
103        bounds[(size_t) xx * 2 + 0] = xmin;
104        bounds[(size_t) xx * 2 + 1] = xmax;
105    }
106    weights.resize((size_t) out_size * ksize);
107    const double fxp_scale = std::ldexp(1.0, PRECISION_BITS);
108    for (size_t i = 0; i < weights.size(); ++i) {
109        const double rounded = pre[i] * fxp_scale + (pre[i] < 0 ? -0.5 : 0.5);   // Pillow: add 0.5 then truncate toward zero
110        weights[i] = (int32_t) rounded;
111    }
112    return ksize;
113}
114
115std::vector<uint8_t> resample_horizontal(const uint8_t* src, int in_nx, int in_ny, int out_nx, int ksize, const std::vector<int>& bounds,
116                                         const std::vector<int32_t>& weights) {
117    std::vector<uint8_t> out((size_t) out_nx * in_ny * 3);
118    for (int yy = 0; yy < in_ny; ++yy) {
119        const uint8_t* src_row = src + (size_t) yy * in_nx * 3;
120        uint8_t* dst_row = out.data() + (size_t) yy * out_nx * 3;
121        for (int xx = 0; xx < out_nx; ++xx) {
122            const int xmin = bounds[(size_t) xx * 2 + 0], xcnt = bounds[(size_t) xx * 2 + 1];
123            const int32_t* k = &weights[(size_t) xx * ksize];
124            const uint8_t* p = src_row + (size_t) xmin * 3;
125            int32_t ss0 = 1 << (PRECISION_BITS - 1), ss1 = ss0, ss2 = ss0;
126            for (int x = 0; x < xcnt; ++x) {
127                ss0 += p[0] * k[x];
128                ss1 += p[1] * k[x];
129                ss2 += p[2] * k[x];
130                p += 3;
131            }
132            dst_row[xx * 3 + 0] = clip8(ss0 >> PRECISION_BITS);
133            dst_row[xx * 3 + 1] = clip8(ss1 >> PRECISION_BITS);
134            dst_row[xx * 3 + 2] = clip8(ss2 >> PRECISION_BITS);
135        }
136    }
137    return out;
138}
139
140std::vector<uint8_t> resample_vertical(const uint8_t* src, int in_nx, int out_ny, int ksize, const std::vector<int>& bounds,
141                                       const std::vector<int32_t>& weight) {
142    const size_t row_elems = (size_t) in_nx * 3;
143    std::vector<uint8_t> out(row_elems * out_ny);
144    std::vector<int32_t> acc(row_elems);
145    for (int yy = 0; yy < out_ny; ++yy) {
146        const int ymin = bounds[(size_t) yy * 2 + 0], ycnt = bounds[(size_t) yy * 2 + 1];
147        const int32_t* k = &weight[(size_t) yy * ksize];
148        std::fill(acc.begin(), acc.end(), 1 << (PRECISION_BITS - 1));
149        for (int y = 0; y < ycnt; ++y) {
150            const uint8_t* src_row = src + (size_t) (ymin + y) * row_elems;
151            const int32_t w = k[y];
152            for (size_t i = 0; i < row_elems; ++i) acc[i] += src_row[i] * w;
153        }
154        uint8_t* dst_row = out.data() + (size_t) yy * row_elems;
155        for (size_t i = 0; i < row_elems; ++i) dst_row[i] = clip8(acc[i] >> PRECISION_BITS);
156    }
157    return out;
158}
159
160}  // namespace
161
162void resize_bicubic(const ImageU8& img, ImageU8& dst, int target_w, int target_h) {
163    const bool need_h = target_w != img.w, need_v = target_h != img.h;
164    std::vector<int> bh, bv;
165    std::vector<int32_t> wh, wv;
166    int kh = 0, kv = 0;
167    if (need_h) kh = precompute_weights(img.w, target_w, bh, wh);
168    if (need_v) kv = precompute_weights(img.h, target_h, bv, wv);
169    std::vector<uint8_t> res;
170    if (need_h && need_v) {
171        auto tmp = resample_horizontal(img.rgb.data(), img.w, img.h, target_w, kh, bh, wh);
172        res = resample_vertical(tmp.data(), target_w, target_h, kv, bv, wv);
173    } else if (need_h) {
174        res = resample_horizontal(img.rgb.data(), img.w, img.h, target_w, kh, bh, wh);
175    } else if (need_v) {
176        res = resample_vertical(img.rgb.data(), img.w, target_h, kv, bv, wv);
177    } else {
178        res = img.rgb;
179    }
180    dst.w = target_w;
181    dst.h = target_h;
182    dst.rgb = std::move(res);
183}
184
185void resize_pad_ceil(const ImageU8& src, ImageU8& dst, Size2 target) {
186    if (src.w == target.w && src.h == target.h) { dst = src; return; }
187    const float scale_w = static_cast<float>(target.w) / src.w;
188    const float scale_h = static_cast<float>(target.h) / src.h;
189    const float scale = std::min(scale_w, scale_h);
190    const int new_w = std::min(static_cast<int>(std::ceil(src.w * scale)), target.w);
191    const int new_h = std::min(static_cast<int>(std::ceil(src.h * scale)), target.h);
192    ImageU8 resized;
193    resize_bicubic(src, resized, new_w, new_h);
194    ImageU8 out;
195    out.w = target.w;
196    out.h = target.h;
197    out.rgb.assign((size_t) target.w * target.h * 3, 0);   // black canvas
198    const int ox = (target.w - new_w) / 2, oy = (target.h - new_h) / 2;
199    for (int y = 0; y < new_h; ++y) {
200        std::memcpy(&out.rgb[((size_t) (y + oy) * target.w + ox) * 3], &resized.rgb[(size_t) y * new_w * 3], (size_t) new_w * 3);
201    }
202    dst = std::move(out);
203}
204
205Size2 prepared_size(int w, int h, const VitGeometry& g, int min_tokens, int max_tokens) {
206    const int patch_area = g.patch * g.patch * g.merge * g.merge;
207    const int min_px = (min_tokens > 0 ? min_tokens : g.min_tokens) * patch_area;
208    const int max_px = (max_tokens > 0 ? max_tokens : g.max_tokens) * patch_area;
209    return smart_resize(w, h, g.align(), min_px, max_px);
210}
211
212bool prepare_image(const ImageU8& src, const VitGeometry& g, int min_tokens, int max_tokens, PreparedImage& out, std::string& err, ImageU8* resized) {
213    if (src.w <= 0 || src.h <= 0 || src.rgb.size() != (size_t) src.w * src.h * 3) { err = "the picture is empty"; return false; }
214    const Size2 t = prepared_size(src.w, src.h, g, min_tokens, max_tokens);
215    if (t.w <= 0 || t.h <= 0) { err = "the picture has no usable size"; return false; }
216    ImageU8 r;
217    resize_pad_ceil(src, r, t);
218    out.w = t.w;
219    out.h = t.h;
220    const size_t n = (size_t) t.w * t.h;
221    out.chw.resize(3 * n);
222    for (size_t i = 0; i < n; ++i)
223        for (int c = 0; c < 3; ++c) out.chw[c * n + i] = ((float) r.rgb[i * 3 + c] / 255.0f - g.mean[c]) / g.stdv[c];
224    if (resized) *resized = std::move(r);
225    return true;
226}
227
228}  // namespace strata_vit