okami.mom/strata

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

Niko1221Merge f-own-5b e93b90250 into f-own-intd4eac2ca3

main
18.2 KiB391 linesraw
1// src/image/qi21_image_main.cpp - test program strata-image (step 5; not shipped, not called by the server, in no build
2// that ships): prompt + size + seed -> PNG with Strata's own parts only, no stable-diffusion.cpp and no ggml in the
3// process.  sd-cli stays the default and the fallback everywhere.
4//
5//   strata-image --te <Qwen3-VL text encoder .gguf> --dit <qwen-image-2.1 DiT .gguf> --vae <VAE .safetensors>
6//                --prompt TEXT -o OUT.png [--width 1024] [--height 1024] [--seed 42] [--steps 8]
7//                [--dump DIR] [--report FILE.json] [--threads N] [--plan auto|resident|te-released] [--te-mode auto|resident|streamed]
8//
9// The pipeline, part by part (each a tested piece of its own):
10//   tokens      Qwen2Tok + qwen_image_tokens (src/image/te/qwen2_tok.cpp; ids identical to sd.cpp's)
11//   condition   qwen3vl_te_encode (src/image/te/qwen3vl_te.cu) + qi21_condition (token weights, system rows dropped)
12//   noise       qi21_noise (Philox, the x86 stream sd.cpp computes on a PC) -> qi21_initial_latent at sigma 1
13//   8 steps     Turbo's sigmas (qi21_parse_sigmas(QI21_TURBO_SIGMAS)); per step qi21_dit_step at t = sigma x 1000
14//               (src/image/dit/qi21_dit.cu), then qi21_euler_step (sd.cpp's bytes given the same velocity)
15//   decode      wan_vae_denormalize + wan_vae_decode (src/image/vae/wan_vae.cu, row bands) + qi21_picture_to_unit
16//   PNG         qi21_picture_to_u8 + png_write_file (stored deflate blocks, the "parameters" text chunk)
17//
18// Memory, decided by the card's TOTAL memory (never its free memory), as the STEP 5 DESIGN note plans it:
19//   24 GB and up   "resident": the text encoder, the DiT and the VAE opened at the start and kept to the end;
20//   under 24 GB    "te-released": the text encoder opened, used and closed before the DiT and the VAE are opened
21//                  (under 14 GiB the text encoder itself streams its layers, its own auto mode).
22// --plan resident / te-released forces one plan (a measurement switch for the memory rows of smaller cards on a big
23// one; the pictures do not depend on it); --te-mode the text encoder's own mode (streamed = the under-14-GiB layout).
24// Only the GB10 row and the plans forced on one card are measured so far.
25//
26// Prints one line per stage (open, encode, steps, decode, png): wall time, the stage's own GPU time where a part
27// measures it, the parts' own device memory at the stage's end (each live part's peak so far), the device memory in
28// use as the driver reports it (sampled every 2 ms during the stage, largest value minus the value before the first
29// open), and the process's host peak (ru_maxrss).  --report writes the same as JSON.  --dump writes the stage tensors
30// with the names tools/image/gate/stage_hooks.py uses (tokens, cond, noise, dit_x_k, dit_t_k, vel_k, latent, vae_in,
31// vae_out; float32 / int32 with a .shape file) for the checks against sd.cpp's dumps.
32//
33// Build (CUDA; the noise table from `python tools/image/sdcpp_noise/apply.py --prepare NOISEINC`):
34//   nvcc -O3 -std=c++17 -arch=native -Iinclude -Isrc/image/te -Isrc/image/vae -Itools/image/sdcpp_noise -INOISEINC
35//        -Xcompiler -ffp-contract=off src/image/qi21_image_main.cpp src/image/pipeline/qi21_glue.cpp
36//        src/image/te/qwen2_tok.cpp src/image/te/qwen3vl_te.cu src/image/te/te_dequant.cu src/image/te/te_dequant_host.cpp
37//        src/image/dit/qi21_dit.cu src/image/dit/qi21_kernels.cu src/image/dit/dit_gemm.cu src/image/dit/qi21_rope.cpp
38//        src/image/vae/wan_vae.cu src/image/vae/qi21_pixels.cpp src/image/noise/qi21_noise.cpp
39//        src/image/sample/qi21_sampler.cpp src/image/png/png_write.cpp -lcublas -o strata-image
40// HIP: written against include/strata/hip_compat like the parts; not compiled yet (owed, p620).
41#include "strata/image/png_write.hpp"
42#include "strata/image/qi21_dit.hpp"
43#include "strata/image/qi21_image.hpp"
44#include "strata/image/qi21_noise.hpp"
45#include "strata/image/qi21_pixels.hpp"
46#include "strata/image/qi21_sampler.hpp"
47#include "strata/image/qwen2_tok.hpp"
48#include "strata/image/qwen3vl_te.hpp"
49#include "strata/image/wan_vae.hpp"
50
51#if defined(__HIP__) || defined(__HIPCC__) || defined(__HIP_PLATFORM_AMD__)
52#include "strata/hip_compat/cuda_runtime.h"
53#else
54#include <cuda_runtime.h>
55#endif
56
57#include <sys/resource.h>
58
59#include <algorithm>
60#include <atomic>
61#include <chrono>
62#include <cstdio>
63#include <cstdlib>
64#include <cstring>
65#include <filesystem>
66#include <fstream>
67#include <memory>
68#include <mutex>
69#include <string>
70#include <thread>
71#include <vector>
72
73namespace fs = std::filesystem;
74using namespace strata::image;
75
76namespace {
77
78using clk = std::chrono::steady_clock;
79
80double ms_since(clk::time_point t0) { return std::chrono::duration<double, std::milli>(clk::now() - t0).count(); }
81
82double host_peak_gb() {
83    struct rusage ru {};
84    getrusage(RUSAGE_SELF, &ru);
85    return ru.ru_maxrss * 1024.0 / 1e9;   // Linux: KiB
86}
87
88// The driver's view of device memory in use (total - free), sampled on a thread; reset() starts a new stage.
89class MemSampler {
90public:
91    MemSampler() {
92        size_t f = 0, t = 0;
93        cudaMemGetInfo(&f, &t);
94        base_ = t - f;
95        total_ = t;
96        stage_max_ = base_;
97        th_ = std::thread([this] {
98            while (!stop_) {
99                sample();
100                std::this_thread::sleep_for(std::chrono::milliseconds(2));
101            }
102        });
103    }
104    ~MemSampler() {
105        stop_ = true;
106        th_.join();
107    }
108    void sample() {
109        size_t f = 0, t = 0;
110        if (cudaMemGetInfo(&f, &t) != cudaSuccess) return;
111        std::lock_guard<std::mutex> g(mu_);
112        stage_max_ = std::max(stage_max_, t - f);
113    }
114    // the stage's largest value above the start, then a new stage
115    double take_stage_gb() {
116        sample();
117        std::lock_guard<std::mutex> g(mu_);
118        const double r = stage_max_ > base_ ? (stage_max_ - base_) / 1e9 : 0.0;
119        size_t f = 0, t = 0;
120        cudaMemGetInfo(&f, &t);
121        stage_max_ = t - f;
122        return r;
123    }
124    size_t total() const { return total_; }
125
126private:
127    size_t base_ = 0, total_ = 0, stage_max_ = 0;
128    std::mutex mu_;
129    std::atomic<bool> stop_{false};
130    std::thread th_;
131};
132
133struct Stage {
134    std::string name;
135    double wall_ms = 0, gpu_ms = -1;
136    double ours_gb = 0, driver_gb = 0, host_gb = 0;
137    std::string note;
138};
139
140bool write_bin(const fs::path& p, const void* data, size_t bytes) {
141    std::ofstream f(p, std::ios::binary);
142    f.write(static_cast<const char*>(data), (std::streamsize) bytes);
143    return (bool) f;
144}
145
146void dump_f32(const fs::path& dir, const std::string& name, const std::vector<float>& v, const std::string& shape) {
147    if (dir.empty()) return;
148    write_bin(dir / (name + ".bin"), v.data(), v.size() * 4);
149    std::ofstream(dir / (name + ".shape")) << shape << "\n";
150}
151
152std::string json_escape(const std::string& s) {
153    std::string o;
154    for (char c : s) {
155        if (c == '"' || c == '\\') o += '\\', o += c;
156        else if (c == '\n') o += "\\n";
157        else if ((unsigned char) c < 0x20) {
158            char b[8];
159            std::snprintf(b, sizeof b, "\\u%04x", c);
160            o += b;
161        } else o += c;
162    }
163    return o;
164}
165
166int usage() {
167    std::fprintf(stderr,
168                 "usage: strata-image --te TE.gguf --dit DIT.gguf --vae VAE.safetensors --prompt TEXT -o OUT.png\n"
169                 "                    [--width 1024] [--height 1024] [--seed 42] [--steps 8] [--dump DIR] [--report FILE]\n"
170                 "                    [--threads N] [--plan auto|resident|te-released] [--te-mode auto|resident|streamed]\n");
171    return 2;
172}
173
174}  // namespace
175
176int main(int argc, char** argv) {
177    std::string te_path, dit_path, vae_path, prompt, out_png, dump_dir, report_path, plan_arg = "auto";
178    int width = 1024, height = 1024, steps = 8, threads = 8, te_mode = 0;
179    uint64_t seed = 42;
180    bool have_prompt = false;
181    for (int i = 1; i < argc; ++i) {
182        const std::string a = argv[i];
183        auto next = [&]() -> const char* { return i + 1 < argc ? argv[++i] : nullptr; };
184        const char* v = nullptr;
185        if (a == "--te" && (v = next())) te_path = v;
186        else if (a == "--dit" && (v = next())) dit_path = v;
187        else if (a == "--vae" && (v = next())) vae_path = v;
188        else if (a == "--prompt" && (v = next())) prompt = v, have_prompt = true;
189        else if ((a == "-o" || a == "--output") && (v = next())) out_png = v;
190        else if (a == "--width" && (v = next())) width = std::atoi(v);
191        else if (a == "--height" && (v = next())) height = std::atoi(v);
192        else if (a == "--seed" && (v = next())) seed = std::strtoull(v, nullptr, 10);
193        else if (a == "--steps" && (v = next())) steps = std::atoi(v);
194        else if (a == "--dump" && (v = next())) dump_dir = v;
195        else if (a == "--report" && (v = next())) report_path = v;
196        else if (a == "--threads" && (v = next())) threads = std::max(1, std::atoi(v));
197        else if (a == "--plan" && (v = next())) plan_arg = v;
198        else if (a == "--te-mode" && (v = next()))
199            te_mode = !std::strcmp(v, "resident") ? 1 : !std::strcmp(v, "streamed") ? 2 : !std::strcmp(v, "auto") ? 0 : -1;
200        else return usage();
201    }
202    if (te_path.empty() || dit_path.empty() || vae_path.empty() || !have_prompt || out_png.empty()) return usage();
203    if (steps != 8) {
204        std::fprintf(stderr, "strata-image: --steps %d is not supported; this test program runs Turbo's 8-step "
205                             "schedule only\n", steps);
206        return 2;
207    }
208    if (width < 16 || height < 16 || width % 16 || height % 16) {
209        std::fprintf(stderr, "strata-image: width and height must be multiples of 16 (got %dx%d)\n", width, height);
210        return 2;
211    }
212    const std::vector<float> sigmas = qi21_parse_sigmas(QI21_TURBO_SIGMAS);
213    if ((int) sigmas.size() != steps + 1) {
214        std::fprintf(stderr, "strata-image: the Turbo schedule did not parse\n");
215        return 2;
216    }
217    const fs::path dump(dump_dir);
218    if (!dump.empty()) fs::create_directories(dump);
219    const int lw = width / 16, lh = height / 16;   // the latent: [64][lh][lw]
220
221    std::vector<Stage> stages;
222    MemSampler mem;
223    const size_t total = mem.total();
224    if ((plan_arg != "auto" && plan_arg != "resident" && plan_arg != "te-released") || te_mode < 0) return usage();
225    const bool resident = plan_arg == "auto" ? total >= (size_t) 24 * 1000 * 1000 * 1000 : plan_arg == "resident";
226    const char* plan = resident ? "resident" : "te-released";
227    std::printf("strata-image: %dx%d, seed %llu, %d steps; device memory %.1f GB total -> plan %s%s\n", width, height,
228                (unsigned long long) seed, steps, total / 1e9, plan, plan_arg == "auto" ? "" : " (forced by --plan)");
229
230    std::string err;
231    Qwen3VlTe* te = nullptr;
232    Qi21Dit* dit = nullptr;
233    WanVae* vae = nullptr;
234    Qwen3VlTeStats te_st;
235    Qi21DitStats dit_st;
236    WanVaeStats vae_st;
237    bool te_live = false, dit_live = false, vae_live = false;
238    auto ours_gb = [&]() {
239        double s = 0;
240        if (te_live) s += te_st.peak_bytes;
241        if (dit_live) s += dit_st.peak_bytes;
242        if (vae_live) s += vae_st.peak_bytes;
243        return s / 1e9;
244    };
245    auto fail = [&](const std::string& what) {
246        std::fprintf(stderr, "strata-image: %s\n", what.c_str());
247        if (te) qwen3vl_te_close(te);
248        if (dit) qi21_dit_close(dit);
249        if (vae) wan_vae_close(vae);
250        std::printf("STRATA-IMAGE FAIL\n");
251        return 1;
252    };
253    double open_ms = 0;
254    std::string open_note;
255    auto open_dit_vae = [&]() -> bool {
256        auto t0 = clk::now();
257        dit = qi21_dit_open(dit_path, -1, &err);
258        if (!dit) return false;
259        dit_live = true;
260        vae = wan_vae_open(vae_path, -1, &err, threads);
261        if (!vae) return false;
262        vae_live = true;
263        wan_vae_set_streaming(vae, true);
264        open_ms += ms_since(t0);
265        open_note += "dit: " + qi21_dit_open_report(dit) + "; vae: " + wan_vae_open_report(vae) + "; ";
266        return true;
267    };
268
269    // ---- open
270    auto t_open = clk::now();
271    std::unique_ptr<Qwen2Tok> tok = Qwen2Tok::from_gguf(te_path, &err);
272    if (!tok) return fail("tokenizer: " + err);
273    te = qwen3vl_te_open(te_path, -1, &err, te_mode, threads);
274    if (!te) return fail("text encoder: " + err);
275    te_live = true;
276    open_ms += ms_since(t_open);
277    open_note += "te: " + qwen3vl_te_open_report(te) + "; ";
278    if (resident && !open_dit_vae()) return fail("open: " + err);
279    stages.push_back({"open", open_ms, -1, 0, mem.take_stage_gb(), host_peak_gb(), open_note});
280
281    // ---- encode
282    auto t_enc = clk::now();
283    QwenImageTokens toks;
284    err = qwen_image_tokens(*tok, prompt, &toks);
285    if (!err.empty()) return fail("tokens: " + err);
286    const int n = (int) toks.ids.size(), C = qwen3vl_te_hidden(te);
287    std::vector<float> hidden((size_t) n * C);
288    err = qwen3vl_te_encode(te, toks.ids.data(), n, hidden.data(), &te_st);
289    if (!err.empty()) return fail("encode: " + err);
290    const std::vector<float> cond = qi21_condition(std::move(hidden), n, C, toks.weights, toks.n_system);
291    const int L = n - toks.n_system;
292    stages.push_back({"encode", ms_since(t_enc), te_st.encode_ms, ours_gb(), mem.take_stage_gb(), host_peak_gb(),
293                      std::to_string(n) + " tokens, " + std::to_string(L) + " condition rows" +
294                          (te_st.streamed ? ", streamed" : ", resident")});
295    if (!dump.empty()) {
296        write_bin(dump / "tokens.bin", toks.ids.data(), toks.ids.size() * 4);
297        std::ofstream(dump / "tokens.start") << toks.n_system << "\n";
298        dump_f32(dump, "cond", cond, std::to_string(C) + " " + std::to_string(L));
299    }
300    if (!resident) {
301        auto t0 = clk::now();
302        qwen3vl_te_close(te);
303        te = nullptr;
304        te_live = false;
305        open_ms = 0;
306        open_note.clear();
307        if (!open_dit_vae()) return fail("open: " + err);
308        stages[0].wall_ms += ms_since(t0);
309        stages[0].note += open_note;
310    }
311
312    // ---- 8 steps
313    auto t_steps = clk::now();
314    const size_t nl = (size_t) 64 * lh * lw;
315    if (qi21_dit_in_channels(dit) != 64 || qi21_dit_out_channels(dit) != 64 || qi21_dit_context_dim(dit) != C)
316        return fail("the DiT's channels do not match a 64-channel latent and the text encoder's width");
317    const std::vector<float> noise = qi21_noise(seed, (uint32_t) nl);
318    const std::string lshape = std::to_string(lw) + " " + std::to_string(lh) + " 64 1";
319    dump_f32(dump, "noise", noise, lshape);
320    std::vector<float> x = qi21_initial_latent(noise, sigmas[0]), vel(nl);
321    double dit_gpu_ms = 0;
322    std::string step_ms;
323    for (int k = 0; k < steps; ++k) {
324        const float t = qi21_timestep(sigmas[(size_t) k]);
325        dump_f32(dump, "dit_x_" + std::to_string(k), x, lshape);
326        dump_f32(dump, "dit_t_" + std::to_string(k), std::vector<float>{t}, "1");
327        Qi21DitStats st;
328        err = qi21_dit_step(dit, x.data(), lw, lh, cond.data(), L, t, vel.data(), &st);
329        if (!err.empty()) return fail("step " + std::to_string(k) + ": " + err);
330        dit_st.peak_bytes = std::max(dit_st.peak_bytes, st.peak_bytes);
331        dit_st.weight_bytes = st.weight_bytes;
332        dit_gpu_ms += st.step_ms;
333        step_ms += (k ? " " : "") + std::to_string((int) (st.step_ms + 0.5));
334        dump_f32(dump, "vel_" + std::to_string(k), vel, lshape);
335        qi21_euler_step(x.data(), vel.data(), nl, sigmas[(size_t) k], sigmas[(size_t) k + 1]);
336    }
337    dump_f32(dump, "latent", x, lshape);
338    stages.push_back({"steps", ms_since(t_steps), dit_gpu_ms, ours_gb(), mem.take_stage_gb(), host_peak_gb(),
339                      "per step ms: " + step_ms});
340
341    // ---- decode
342    auto t_dec = clk::now();
343    wan_vae_denormalize(x.data(), lh, lw);
344    dump_f32(dump, "vae_in", x, lshape);
345    const int W = 16 * lw, H = 16 * lh, PC = 4;
346    std::vector<float> pic((size_t) PC * W * H);
347    err = wan_vae_decode(vae, x.data(), lh, lw, pic.data(), &vae_st);
348    if (!err.empty()) return fail("decode: " + err);
349    qi21_picture_to_unit(pic.data(), pic.size());
350    dump_f32(dump, "vae_out", pic, std::to_string(W) + " " + std::to_string(H) + " " + std::to_string(PC) + " 1");
351    stages.push_back({"decode", ms_since(t_dec), vae_st.decode_ms, ours_gb(), mem.take_stage_gb(), host_peak_gb(), ""});
352
353    // ---- PNG
354    auto t_png = clk::now();
355    std::vector<uint8_t> px((size_t) W * H * PC);
356    qi21_picture_to_u8(pic.data(), W, H, PC, px.data());
357    err = png_write_file(out_png, px.data(), W, H, PC,
358                         qi21_parameters_text(prompt, steps, seed, width, height, fs::path(dit_path).filename().string()));
359    if (!err.empty()) return fail("png: " + err);
360    stages.push_back({"png", ms_since(t_png), -1, ours_gb(), mem.take_stage_gb(), host_peak_gb(), out_png});
361
362    double total_ms = 0;
363    for (const Stage& s : stages) {
364        total_ms += s.wall_ms;
365        std::printf("stage %-6s %9.1f ms", s.name.c_str(), s.wall_ms);
366        if (s.gpu_ms >= 0) std::printf(" (gpu %.1f ms)", s.gpu_ms);
367        std::printf(" | parts' own device memory %.3f GB | driver in use %.3f GB | host peak %.3f GB | %s\n",
368                    s.ours_gb, s.driver_gb, s.host_gb, s.note.c_str());
369    }
370    std::printf("total %.1f ms; text encoder weights %.3f GB, DiT weights %.3f GB, VAE weights %.3f GB\n", total_ms,
371                te_st.weight_bytes / 1e9, dit_st.weight_bytes / 1e9, vae_st.weight_bytes / 1e9);
372    if (!report_path.empty()) {
373        std::ofstream r(report_path);
374        r << "{\"width\": " << width << ", \"height\": " << height << ", \"seed\": " << seed << ", \"steps\": " << steps
375          << ", \"plan\": \"" << plan << "\", \"device_total_gb\": " << total / 1e9 << ", \"total_ms\": " << total_ms
376          << ", \"te_weight_gb\": " << te_st.weight_bytes / 1e9 << ", \"dit_weight_gb\": " << dit_st.weight_bytes / 1e9
377          << ", \"vae_weight_gb\": " << vae_st.weight_bytes / 1e9 << ", \"stages\": [";
378        for (size_t i = 0; i < stages.size(); ++i) {
379            const Stage& s = stages[i];
380            r << (i ? ", " : "") << "{\"name\": \"" << s.name << "\", \"wall_ms\": " << s.wall_ms << ", \"gpu_ms\": "
381              << s.gpu_ms << ", \"ours_gb\": " << s.ours_gb << ", \"driver_gb\": " << s.driver_gb << ", \"host_gb\": "
382              << s.host_gb << ", \"note\": \"" << json_escape(s.note) << "\"}";
383        }
384        r << "]}\n";
385    }
386    if (te) qwen3vl_te_close(te);
387    qi21_dit_close(dit);
388    wan_vae_close(vae);
389    std::printf("STRATA-IMAGE PASS %s\n", out_png.c_str());
390    return 0;
391}