okami.mom/strata

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

Niko1221Merge f-own-5b adfcf9028 into f-own-int (round 16: the strata-image test program and its parts, DiT runner, sampler, noise, PNG writer; hooked into no build)e4309aaf3

main
8.2 KiB184 linesraw
1// src/image/sample/qi21_sampler_check_main.cpp - test program strata-sampler-check (not shipped): Strata's Turbo
2// sampler (include/strata/image/qi21_sampler.hpp) against stable-diffusion.cpp's own stage dumps.
3//
4//   strata-sampler-check <dump dir> [<dump dir> ...] [--fixture OUT [--fixture-n N]]
5//   strata-sampler-check --fixture-check FILE
6//
7// Dump mode: each dir holds one picture's dumps of all 8 model calls (tools/image/gate/stage_hooks.py: dit_x_<k>,
8// dit_t_<k>, vel_<k>; and latent, the final latent).  Starting from dit_x_0 and feeding sd.cpp's own vel_<k>, our
9// chain must give dit_x_<k+1> byte for byte for every step, and dit_t_<k> must equal qi21_timestep(sigma_k); the last
10// step's result is compared with latent.bin when its size matches.  Prints per step the bytes-identical verdict and,
11// where not identical, the count of differing values and the largest difference in units in the last place.
12// --fixture OUT writes, from the first dir, N values per step (spread over the tensor) for the CPU test.
13// Fixture mode: the step on the stored values must give the stored results (tools/test_qi21_sampler.py).
14#include "strata/image/qi21_sampler.hpp"
15
16#include <algorithm>
17#include <cstdint>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <filesystem>
22#include <fstream>
23#include <string>
24#include <vector>
25
26namespace fs = std::filesystem;
27using namespace strata::image;
28
29namespace {
30
31bool read_f32(const fs::path& p, std::vector<float>& v) {
32    std::ifstream f(p, std::ios::binary);
33    if (!f) return false;
34    std::vector<char> raw((std::istreambuf_iterator<char>(f)), {});
35    v.resize(raw.size() / 4);
36    std::memcpy(v.data(), raw.data(), v.size() * 4);
37    return true;
38}
39
40uint32_t bits(float f) {
41    uint32_t b;
42    std::memcpy(&b, &f, 4);
43    return b;
44}
45
46// distance in units in the last place (signed-magnitude bits mapped to a monotonic integer line)
47int64_t ulps(float a, float b) {
48    auto key = [](float f) -> int64_t {
49        const uint32_t u = bits(f);
50        return (u & 0x80000000u) ? -(int64_t) (u & 0x7fffffffu) : (int64_t) u;
51    };
52    const int64_t d = key(a) - key(b);
53    return d < 0 ? -d : d;
54}
55
56struct Cmp { size_t differ = 0; int64_t max_ulp = 0; };
57Cmp compare(const std::vector<float>& a, const std::vector<float>& b) {
58    Cmp c;
59    for (size_t i = 0; i < a.size(); ++i)
60        if (bits(a[i]) != bits(b[i])) {
61            ++c.differ;
62            c.max_ulp = std::max(c.max_ulp, ulps(a[i], b[i]));
63        }
64    return c;
65}
66
67const char MAGIC[4] = {'Q', 'S', '1', 0};
68
69int fixture_check(const char* path) {
70    std::ifstream f(path, std::ios::binary);
71    char m[4];
72    int32_t steps = 0, n = 0;
73    if (!f.read(m, 4) || std::memcmp(m, MAGIC, 4) != 0 || !f.read((char*) &steps, 4) || !f.read((char*) &n, 4)) {
74        std::printf("SAMPLER-FIXTURE FAIL (cannot read %s)\n", path);
75        return 2;
76    }
77    const std::vector<float> sig = qi21_parse_sigmas(QI21_TURBO_SIGMAS);
78    int bad = 0;
79    for (int k = 0; k < steps; ++k) {
80        float s0, s1;
81        uint32_t tb;
82        std::vector<float> x(n), v(n), want(n);
83        f.read((char*) &s0, 4);
84        f.read((char*) &s1, 4);
85        f.read((char*) &tb, 4);
86        f.read((char*) x.data(), 4 * n);
87        f.read((char*) v.data(), 4 * n);
88        f.read((char*) want.data(), 4 * n);
89        if (!f) { std::printf("SAMPLER-FIXTURE FAIL (short file)\n"); return 2; }
90        const bool sig_ok = k + 1 < (int) sig.size() && bits(sig[k]) == bits(s0) && bits(sig[k + 1]) == bits(s1);
91        const bool t_ok = bits(qi21_timestep(s0)) == tb;
92        qi21_euler_step(x.data(), v.data(), (size_t) n, s0, s1);
93        const Cmp c = compare(x, want);
94        std::printf("step %d: sigma %s, t %s, x_next %s", k, sig_ok ? "same" : "DIFFERS", t_ok ? "same" : "DIFFERS",
95                    c.differ == 0 ? "identical" : "DIFFERS");
96        if (c.differ) std::printf(" (%zu of %d values, up to %lld ulp)", c.differ, n, (long long) c.max_ulp);
97        std::printf("\n");
98        bad += !sig_ok || !t_ok || c.differ != 0;
99    }
100    std::printf("SAMPLER-FIXTURE %s\n", bad ? "FAIL" : "PASS");
101    return bad ? 1 : 0;
102}
103
104}  // namespace
105
106int main(int argc, char** argv) {
107    if (argc >= 3 && std::strcmp(argv[1], "--fixture-check") == 0) return fixture_check(argv[2]);
108    std::vector<fs::path> dirs;
109    std::string fixture;
110    int fixture_n = 512;
111    for (int i = 1; i < argc; ++i) {
112        if (std::strcmp(argv[i], "--fixture") == 0 && i + 1 < argc) fixture = argv[++i];
113        else if (std::strcmp(argv[i], "--fixture-n") == 0 && i + 1 < argc) fixture_n = std::atoi(argv[++i]);
114        else dirs.emplace_back(argv[i]);
115    }
116    if (dirs.empty()) {
117        std::fprintf(stderr, "usage: strata-sampler-check <dump dir> [...] [--fixture OUT [--fixture-n N]] | --fixture-check FILE\n");
118        return 2;
119    }
120    const std::vector<float> sig = qi21_parse_sigmas(QI21_TURBO_SIGMAS);
121    const int steps = (int) sig.size() - 1;
122    int bad = 0;
123    std::ofstream fx;
124    for (size_t di = 0; di < dirs.size(); ++di) {
125        const fs::path& d = dirs[di];
126        const std::string tag = d.parent_path().filename().string() + "/" + d.filename().string();
127        std::vector<float> x;
128        if (!read_f32(d / "dit_x_0.bin", x)) {
129            std::printf("%s: dit_x_0 missing\n", tag.c_str());
130            ++bad;
131            continue;
132        }
133        const bool write_fx = di == 0 && !fixture.empty();
134        if (write_fx) {
135            fx.open(fixture, std::ios::binary);
136            const int32_t st = steps - 1, n = fixture_n;   // steps 0..6: each has sd.cpp's next input to compare with
137            fx.write(MAGIC, 4);
138            fx.write((const char*) &st, 4);
139            fx.write((const char*) &n, 4);
140        }
141        int first_bad = -1;
142        for (int k = 0; k < steps; ++k) {
143            std::vector<float> v, t, next;
144            if (!read_f32(d / ("vel_" + std::to_string(k) + ".bin"), v) ||
145                !read_f32(d / ("dit_t_" + std::to_string(k) + ".bin"), t) || v.size() != x.size() || t.empty()) {
146                std::printf("%s step %d: dumps missing\n", tag.c_str(), k);
147                ++bad;
148                break;
149            }
150            const bool t_ok = bits(qi21_timestep(sig[k])) == bits(t[0]);
151            const std::vector<float> xk = x;
152            qi21_euler_step(x.data(), v.data(), x.size(), sig[k], sig[k + 1]);
153            const bool last = k + 1 == steps;
154            const fs::path want_p = last ? d / "latent.bin" : d / ("dit_x_" + std::to_string(k + 1) + ".bin");
155            const bool have = read_f32(want_p, next) && next.size() == x.size();
156            Cmp c;
157            if (have) c = compare(x, next);
158            std::printf("%s step %d: sigma %.6g -> %.6g, t %s (%.4f), %s %s", tag.c_str(), k, sig[k], sig[k + 1],
159                        t_ok ? "identical" : "DIFFERS", t[0], last ? "latent.bin" : ("dit_x_" + std::to_string(k + 1)).c_str(),
160                        !have ? "not comparable (missing or another size)" : c.differ == 0 ? "byte-identical" : "DIFFERS");
161            if (have && c.differ)
162                std::printf(" (%zu of %zu values, largest %lld ulp)", c.differ, x.size(), (long long) c.max_ulp);
163            std::printf("\n");
164            const bool step_bad = !t_ok || (!last && (!have || c.differ != 0));
165            if (step_bad && first_bad < 0) first_bad = k;
166            bad += step_bad;
167            if (write_fx && !last) {
168                const uint32_t tb = bits(t[0]);
169                fx.write((const char*) &sig[k], 4);
170                fx.write((const char*) &sig[k + 1], 4);
171                fx.write((const char*) &tb, 4);
172                const size_t stride = std::max<size_t>(1, x.size() / (size_t) fixture_n);
173                const std::vector<float>* srcs[3] = {&xk, &v, &next};
174                for (const std::vector<float>* src : srcs)
175                    for (int i = 0; i < fixture_n; ++i) fx.write((const char*) &(*src)[(size_t) i * stride], 4);
176            }
177            if (!last && have) x = next;   // carry on from sd.cpp's own value, so one bad step does not hide the next
178        }
179        std::printf("%s: %s\n", tag.c_str(), first_bad < 0 ? "every step byte-identical"
180                                                           : ("first differing step " + std::to_string(first_bad)).c_str());
181    }
182    std::printf("SAMPLER-CHECK %s\n", bad ? "FAIL" : "PASS");
183    return bad ? 1 : 0;
184}