okami.mom/strata

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

Niko1221Merge f-qimage2 into f-144-relc106e9629

main
34.1 KiB601 linesraw
1// qwen_image_2_1_native.hpp - Strata's native Qwen-Image-2.1 DiT runner for stable-diffusion.cpp (CUDA / HIP builds).
2//
3// Copied into src/model/diffusion/ by tools/image/sdcpp_native/apply.py and chosen by model_builders.cpp when the
4// model args contain qwen_image_2_1_native=1.  sd.cpp keeps the text encoder, the VAE, the sampler and the RNG; this
5// runner replaces only QwenImage21Runner::compute (latent + timestep + text condition in, velocity out, on the host).
6//
7// Per step: the 32 blocks run on the image tokens only.  The text prefix (causal within the text, timestep-free:
8// its modulation row is the t = 0 one) goes through all blocks once per prompt and leaves each layer's K/V (fp16)
9// behind - the same prefix cache sd.cpp keeps.  GEMMs are ggml graphs on the runner's backend (the MMQ / BLAS
10// kernels sd.cpp uses, same numerics); LayerNorm+modulate, gate+residual, q/k RMSNorm+RoPE, SwiGLU and (on gfx11)
11// the image attention are Strata kernels (ggml/src/ggml-cuda/qi21-native.cu) on the backend's stream.  Anything this
12// runner does not cover (reference images, an unfused MLP, a CPU / Vulkan backend, too little VRAM) goes to the
13// stock runner.
14#ifndef __SD_MODEL_DIFFUSION_QWEN_IMAGE_2_1_NATIVE_H__
15#define __SD_MODEL_DIFFUSION_QWEN_IMAGE_2_1_NATIVE_H__
16
17#include <chrono>
18#include <cstdio>
19#include <cstring>
20#include <memory>
21
22#include "ggml-alloc.h"
23#include "ggml-backend.h"
24#include "ggml-cuda.h"
25#include "gguf.h"
26#include "model/diffusion/qwen_image_2_1.hpp"
27
28extern "C" {
29void* qi21_stream(ggml_backend_t backend);
30int qi21_has_wmma_attn(ggml_backend_t backend);
31int qi21_res_ln_mod(void* stream, float* x, const float* h, const float* g, float* out, const float* m, int T, int C,
32                    float eps);
33int qi21_qkv_post(void* stream, const float* q, const float* k, const float* v, int ld, const float* wq, const float* wk,
34                  const float* pe, void* qo, void* qlo, int q_f16, int q_tstride, void* ko, void* vo, int kv_tstride,
35                  int kv_off, int T, int H, float eps);
36int qi21_swiglu(void* stream, const float* gu, float* out, int T, int F);
37int qi21_tanh(void* stream, const float* in, float* out, int n);
38int qi21_res_ln_mod2(void* stream, float* x, const float* h, const float* tg, float* out, const float* m, int T, int C,
39                     float eps);
40int qi21_attn_causal(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride,
41                     float* out, int H, int Lq, int Lk, int causal);
42int qi21_attn_wmma(void* stream, const void* q, const void* qlo, int q_tstride, const void* k, const void* v,
43                   int kv_tstride, float* out, int H, int nq, int nkv);
44int qi21_memcpy_d2d(void* stream, void* dst, const void* src, size_t n);
45}
46
47namespace Qwen {
48
49    struct QwenImage21NativeRunner : public QwenImage21Runner {
50        static constexpr int64_t C = 4096, D = 128, H = 32, F = 12288;
51        std::string dit_path;
52        bool disabled = false;           // a failure: the stock runner from here on
53        bool loaded   = false;
54        bool wmma_attn = false;
55        bool timing    = false;
56        bool said_why  = false;
57        bool qsplit    = false;
58        bool exact_attn = false;
59        bool fast_ln    = true;
60        bool fuse_qkv   = true;
61
62        // weights (our own copy: the stock runner's params are never loaded, they load lazily on first use)
63        ggml_context* wctx               = nullptr;
64        ggml_backend_buffer_t wbuf       = nullptr;
65        std::map<std::string, ggml_tensor*> W;
66
67        // activations, sized for t_cap image tokens and l_cap prefix tokens
68        ggml_context* actx         = nullptr;
69        ggml_backend_buffer_t abuf = nullptr;
70        int64_t t_cap = 0, l_cap = 0;
71        ggml_tensor *x, *h, *q, *k, *v, *att, *gu, *mlp, *q16, *kw, *vw, *pe_img, *pe_txt, *latent, *outp, *timein,
72            *mod, *gates, *scale_out, *ctx_in, *pk, *pv;
73
74        // the prefix cache: per layer K/V of the text tokens (fp16, head-major), for one condition
75        uint64_t prefix_key = 0;
76        int64_t prefix_len  = -1;
77
78        std::vector<char> gbuf;          // ggml graph metadata arena
79
80        QwenImage21NativeRunner(ggml_backend_t backend, const String2TensorStorage& weights, const std::string& prefix,
81                                std::shared_ptr<RunnerWeightManager> weight_manager, const char* model_args,
82                                std::string dit_path)
83            : QwenImage21Runner(backend, weights, prefix, weight_manager, model_args), dit_path(std::move(dit_path)) {
84            timing = getenv("STRATA_QI_TIMING") != nullptr;
85            qsplit     = getenv("STRATA_QI_QSPLIT") != nullptr;      // measured: no accuracy gain, +7% step time
86            exact_attn = getenv("STRATA_QI_EXACT_ATTN") != nullptr;
87            fuse_qkv   = getenv("STRATA_QI_NO_QKV_FUSE") == nullptr;
88            fast_ln    = getenv("STRATA_QI_FAST_LN") != nullptr;    // measured: no gain on the 3060 (2.10 vs 2.10 s/step)
89            gbuf.resize(64 << 20);
90        }
91
92        ~QwenImage21NativeRunner() override { release(); }
93
94        std::string get_desc() override { return "qwen_image_2_1 (strata native)"; }
95
96        void release() {
97            if (abuf) ggml_backend_buffer_free(abuf);
98            if (actx) ggml_free(actx);
99            if (wbuf) ggml_backend_buffer_free(wbuf);
100            if (wctx) ggml_free(wctx);
101            abuf = nullptr; actx = nullptr; wbuf = nullptr; wctx = nullptr;
102            W.clear();
103            loaded = false;
104            t_cap = l_cap = 0;
105            prefix_len = -1;
106        }
107
108        void fail(const char* why) {
109            LOG_WARN("Qwen Image 2.1 native: %s; using the stock runner", why);
110            release();
111            disabled = true;
112        }
113
114        ggml_tensor* w(const std::string& name) {
115            auto it = W.find("model.diffusion_model." + name);
116            return it == W.end() ? nullptr : it->second;
117        }
118
119        // ---------------------------------------------------------------- weights
120        bool load_weights() {
121            ggml_context* meta = nullptr;
122            gguf_init_params gp{true, &meta};
123            gguf_context* g = gguf_init_from_file(dit_path.c_str(), gp);
124            if (g == nullptr) return false;
125            const int64_t n = gguf_get_n_tensors(g);
126            wctx = ggml_init({(size_t) (n + 8) * ggml_tensor_overhead(), nullptr, true});
127            struct Piece { ggml_tensor* t; size_t file_off, dst_off; };
128            std::vector<Piece> plan;
129            std::map<ggml_tensor*, ggml_type> widened;
130            const size_t base = gguf_get_data_offset(g);
131            // q, k and v of a block in one tensor when they have the same type (one GEMM, one activation quantize):
132            // rows stay rows, so the three weights are simply laid one after the other
133            auto qkv_name = [](int b, const char* w) {
134                return "model.diffusion_model.transformer_blocks." + std::to_string(b) + ".attn.to_" + w + ".weight";
135            };
136            std::map<std::string, std::pair<ggml_tensor*, size_t>> fused_part;   // q/k/v name -> (fused, offset)
137            if (fuse_qkv) {
138                for (int b = 0; b < config.num_layers; ++b) {
139                    ggml_tensor* tq = ggml_get_tensor(meta, qkv_name(b, "q").c_str());
140                    ggml_tensor* tk = ggml_get_tensor(meta, qkv_name(b, "k").c_str());
141                    ggml_tensor* tv = ggml_get_tensor(meta, qkv_name(b, "v").c_str());
142                    if (!tq || !tk || !tv || tq->type != tk->type || tq->type != tv->type || tq->ne[0] != tk->ne[0] ||
143                        tq->ne[1] != tk->ne[1] || tq->ne[1] != tv->ne[1])
144                        continue;
145                    ggml_tensor* f = ggml_new_tensor_2d(wctx, tq->type, tq->ne[0], 3 * tq->ne[1]);
146                    const std::string fname = "model.diffusion_model.transformer_blocks." + std::to_string(b) +
147                                              ".attn.qkv.weight";
148                    ggml_set_name(f, fname.c_str());
149                    W[fname] = f;
150                    const size_t nb = ggml_nbytes(tq);
151                    fused_part[qkv_name(b, "q")] = {f, 0};
152                    fused_part[qkv_name(b, "k")] = {f, nb};
153                    fused_part[qkv_name(b, "v")] = {f, 2 * nb};
154                }
155            }
156            for (int64_t i = 0; i < n; ++i) {
157                const char* name = gguf_get_tensor_name(g, i);
158                if (strncmp(name, "model.diffusion_model.", 22) != 0) continue;
159                auto fp = fused_part.find(name);
160                if (fp != fused_part.end()) {
161                    plan.push_back({fp->second.first, base + gguf_get_tensor_offset(g, i), fp->second.second});
162                    continue;
163                }
164                ggml_tensor* src = ggml_get_tensor(meta, name);
165                // a 1-D norm weight in BF16 / F16 is kept as F32 (elementwise ops on it then work on every backend)
166                const bool widen = ggml_n_dims(src) == 1 && src->type != GGML_TYPE_F32;
167                ggml_tensor* t   = widen ? ggml_new_tensor_1d(wctx, GGML_TYPE_F32, src->ne[0]) : ggml_dup_tensor(wctx, src);
168                if (widen) widened[t] = src->type;
169                ggml_set_name(t, name);
170                W[name] = t;
171                plan.push_back({t, base + gguf_get_tensor_offset(g, i), 0});
172            }
173            wbuf = ggml_backend_alloc_ctx_tensors(wctx, runtime_backend);
174            if (wbuf == nullptr) {
175                gguf_free(g);
176                ggml_free(meta);
177                return false;
178            }
179            FILE* f = fopen(dit_path.c_str(), "rb");
180            std::vector<char> stage(64 << 20);
181            bool ok = f != nullptr;
182            for (auto& [t, off, dst_off] : plan) {
183                if (!ok) break;
184                auto wi = widened.find(t);
185                const bool part = std::string(ggml_get_name(t)).find(".attn.qkv.") != std::string::npos;
186                const size_t nb = part ? ggml_nbytes(t) / 3
187                                       : wi == widened.end() ? ggml_nbytes(t) : ggml_row_size(wi->second, t->ne[0]);
188#ifdef _WIN32
189                ok = _fseeki64(f, (long long) off, SEEK_SET) == 0;
190#else
191                ok = fseeko(f, (off_t) off, SEEK_SET) == 0;
192#endif
193                if (wi != widened.end()) {
194                    std::vector<char> raw(nb);
195                    std::vector<float> f32(t->ne[0]);
196                    ok = fread(raw.data(), 1, nb, f) == nb;
197                    if (ok) {
198                        ggml_get_type_traits(wi->second)->to_float(raw.data(), f32.data(), t->ne[0]);
199                        ggml_backend_tensor_set(t, f32.data(), 0, f32.size() * sizeof(float));
200                    }
201                    continue;
202                }
203                for (size_t done = 0; ok && done < nb;) {
204                    const size_t c = std::min(stage.size(), nb - done);
205                    ok = fread(stage.data(), 1, c, f) == c;
206                    if (ok) ggml_backend_tensor_set(t, stage.data(), dst_off + done, c);
207                    done += c;
208                }
209            }
210            if (f) fclose(f);
211            gguf_free(g);
212            ggml_free(meta);
213            if (!ok) return false;
214            for (int i = 0; i < config.num_layers; ++i) {
215                const std::string b = "transformer_blocks." + std::to_string(i) + ".";
216                if (w(b + "attn.qkv.weight") == nullptr &&
217                    (!w(b + "attn.to_q.weight") || !w(b + "attn.to_k.weight") || !w(b + "attn.to_v.weight")))
218                    return false;
219                for (const char* s : {"attn.to_out.0.weight",
220                                      "attn.norm_q.weight", "attn.norm_k.weight", "img_mlp.gate_up.weight",
221                                      "img_mlp.out.weight"}) {
222                    if (w(b + s) == nullptr) return false;
223                }
224                if (w(b + "attn.norm_q.weight")->type != GGML_TYPE_F32 || w(b + "attn.norm_k.weight")->type != GGML_TYPE_F32)
225                    return false;
226            }
227            for (const char* s : {"img_in.weight", "txt_in.text_norm.weight", "txt_in.in_layer.weight", "txt_in.out_layer.weight",
228                                  "time_text_embed.timestep_embedder.linear_1.weight",
229                                  "time_text_embed.timestep_embedder.linear_2.weight", "modulation.1.weight",
230                                  "norm_out.linear.weight", "proj_out.weight"}) {
231                if (w(s) == nullptr) return false;
232            }
233            LOG_INFO("Qwen Image 2.1 native: %zu tensors, %.2f GB on %s%s", W.size(),
234                     ggml_backend_buffer_get_size(wbuf) / 1e9, ggml_backend_name(runtime_backend),
235                     wmma_attn ? " (Strata attention)" : "");
236            return true;
237        }
238
239        // ---------------------------------------------------------------- activations
240        bool alloc_acts(int64_t T, int64_t L) {
241            if (T <= t_cap && L <= l_cap) return true;
242            if (abuf) ggml_backend_buffer_free(abuf);
243            if (actx) ggml_free(actx);
244            t_cap = std::max(T, t_cap);
245            l_cap = std::max(L, l_cap);
246            const int64_t R = std::max(t_cap, l_cap);     // rows of the shared work buffers
247            actx  = ggml_init({64 * ggml_tensor_overhead(), nullptr, true});
248            x     = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);
249            h     = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);
250            q     = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);
251            k     = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);
252            v     = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);
253            att   = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);
254            gu    = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 2 * F, R);
255            mlp   = ggml_new_tensor_2d(actx, GGML_TYPE_F32, F, R);
256            q16   = ggml_new_tensor_3d(actx, GGML_TYPE_F32, D, R, H);     // fp16 or fp32 queries, head-major
257            kw    = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D, l_cap + t_cap, H);
258            vw    = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D, l_cap + t_cap, H);
259            pe_img = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 4 * D / 2, t_cap);
260            pe_txt = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 4 * D / 2, std::max<int64_t>(l_cap, 1));
261            latent = ggml_new_tensor_2d(actx, GGML_TYPE_F32, config.in_channels, t_cap);
262            outp   = ggml_new_tensor_2d(actx, GGML_TYPE_F32, config.out_channels, t_cap);
263            timein = ggml_new_tensor_1d(actx, GGML_TYPE_F32, 2);
264            mod    = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 4 * C, 2);
265            gates  = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 4 * C, 2);     // tanh(mod), the gate rows used
266            scale_out = ggml_new_tensor_1d(actx, GGML_TYPE_F32, C);
267            ctx_in = ggml_new_tensor_2d(actx, GGML_TYPE_F32, config.context_dim, std::max<int64_t>(l_cap, 1));
268            pk     = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D * H, std::max<int64_t>(l_cap, 1), config.num_layers);
269            pv     = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D * H, std::max<int64_t>(l_cap, 1), config.num_layers);
270            abuf   = ggml_backend_alloc_ctx_tensors(actx, runtime_backend);
271            prefix_len = -1;                               // the cache lived in the old buffer
272            return abuf != nullptr;
273        }
274
275        // ---------------------------------------------------------------- ggml graph helpers
276        struct G {
277            ggml_context* ctx;
278            ggml_cgraph* gf;
279        };
280        G begin() {
281            ggml_context* c = ggml_init({gbuf.size(), gbuf.data(), true});
282            return {c, ggml_new_graph_custom(c, 256, false)};
283        }
284        static ggml_tensor* rows(ggml_context* c, ggml_tensor* t, int64_t n, int64_t first = 0) {
285            return ggml_view_2d(c, t, t->ne[0], n, t->nb[1], first * t->nb[1]);
286        }
287        static void bind(ggml_tensor* node, ggml_tensor* storage, size_t offset = 0) {
288            node->data   = (char*) storage->data + offset;
289            node->buffer = storage->buffer;
290        }
291        // compute a graph on the backend's stream (no wait).  Nodes the caller did not bind get scratch space in
292        // `gu` (only the small prelude / head / txt_in graphs have such nodes, and gu is free then); views get
293        // their source's memory.
294        void run(G& g, std::initializer_list<ggml_tensor*> outs) {
295            for (auto* o : outs) ggml_build_forward_expand(g.gf, o);
296            size_t off = 0;
297            for (ggml_tensor* t = ggml_get_first_tensor(g.ctx); t; t = ggml_get_next_tensor(g.ctx, t)) {
298                if (t->view_src != nullptr) {
299                    t->data   = (char*) t->view_src->data + t->view_offs;
300                    t->buffer = t->view_src->buffer;
301                } else if (t->data == nullptr) {
302                    bind(t, gu, off);
303                    off += GGML_PAD(ggml_nbytes(t), 256);
304                    GGML_ASSERT(off <= ggml_nbytes(gu));
305                }
306            }
307            ggml_backend_graph_compute_async(runtime_backend, g.gf);
308            ggml_free(g.ctx);
309        }
310        // dst[N x n] = W . src[K x n] (rows `first..`)
311        void gemm(G& g, ggml_tensor* weight, ggml_tensor* src, ggml_tensor* dst, int64_t n) {
312            ggml_tensor* y = ggml_mul_mat(g.ctx, weight, rows(g.ctx, src, n));
313            bind(y, dst);
314            ggml_build_forward_expand(g.gf, y);
315        }
316
317        // ---------------------------------------------------------------- the transformer blocks
318        // rows [0, n) of x are the tokens; mrow = 0 (image) or 1 (text prefix); pe: per-token rope table;
319        // attention: image -> [cached prefix K/V of the layer, these tokens' K/V]; prefix -> causal over itself, and
320        // each layer's K/V goes into the prefix cache.
321        bool blocks_pass(int64_t n, int mrow, ggml_tensor* pe, int64_t L) {
322            void* s       = qi21_stream(runtime_backend);
323            const float* m = (const float*) mod->data + mrow * 4 * C;
324            const float *m0 = m, *m1 = m + C, *m2 = m + 2 * C, *m3 = m + 3 * C;
325            const float* tgr = (const float*) gates->data + mrow * 4 * C;   // tanh of the same row
326            const float *t1 = tgr + C, *t3 = tgr + 3 * C;
327            auto res_ln = [&](float* xx, const float* hh, const float* graw, const float* tgate, float* out,
328                              const float* mm) {
329                return fast_ln ? qi21_res_ln_mod2(s, xx, hh, tgate, out, mm, (int) n, (int) C, 1e-6f)
330                               : qi21_res_ln_mod(s, xx, hh, graw, out, mm, (int) n, (int) C, 1e-6f);
331            };
332            const bool prefix = mrow == 1;
333            const int64_t kvt = prefix ? n : L + n;       // keys per head in the work K/V
334            const bool use_wmma = !prefix && wmma_attn && !exact_attn;
335            // fp16 queries carry ~5e-4 relative error into logits that reach the tens here: the low half of each
336            // query (q - fp16(q)) goes through a second WMMA (STRATA_QI_QSPLIT=0 drops it).  It sits in the fp32-sized
337            // q16 buffer right after the fp16 high half.
338            const size_t qlo_off = (size_t) H * n * D * sizeof(ggml_fp16_t);
339            float* X = (float*) x->data;
340            float* Hh = (float*) h->data;
341            int rc = res_ln(X, nullptr, nullptr, nullptr, Hh, m0);
342            for (int i = 0; i < config.num_layers && rc == 0; ++i) {
343                const std::string b = "transformer_blocks." + std::to_string(i) + ".";
344                ggml_tensor* wqkv = w(b + "attn.qkv.weight");
345                const float *qs = (const float*) q->data, *ks = (const float*) k->data, *vs = (const float*) v->data;
346                int ldq = (int) C;
347                {
348                    G g = begin();
349                    if (wqkv != nullptr) {                 // [3C x n] into gu (free here), q | k | v per token
350                        gemm(g, wqkv, h, gu, n);
351                        qs = (const float*) gu->data;
352                        ks = qs + C;
353                        vs = qs + 2 * C;
354                        ldq = (int) (3 * C);
355                    } else {
356                        gemm(g, w(b + "attn.to_q.weight"), h, q, n);
357                        gemm(g, w(b + "attn.to_k.weight"), h, k, n);
358                        gemm(g, w(b + "attn.to_v.weight"), h, v, n);
359                    }
360                    run(g, {});
361                }
362                const int64_t off = prefix ? 0 : L;
363                rc = qi21_qkv_post(s, qs, ks, vs, ldq,
364                                   (const float*) w(b + "attn.norm_q.weight")->data,
365                                   (const float*) w(b + "attn.norm_k.weight")->data, (const float*) pe->data, q16->data,
366                                   use_wmma && qsplit ? (char*) q16->data + qlo_off : nullptr, use_wmma ? 1 : 0, (int) n, kw->data, vw->data, (int) kvt, (int) off, (int) n, (int) H,
367                                   1e-6f);
368                if (rc) break;
369                const size_t pbytes = (size_t) L * D * sizeof(ggml_fp16_t);   // one head's prefix rows
370                if (prefix) {
371                    // keep this layer's text K/V (head-major rows 0..n) in the prefix cache, as [H][n][D]
372                    for (int64_t hh = 0; hh < H && rc == 0; ++hh) {
373                        char* pkd = (char*) pk->data + i * pk->nb[2] + hh * n * D * sizeof(ggml_fp16_t);
374                        char* pvd = (char*) pv->data + i * pv->nb[2] + hh * n * D * sizeof(ggml_fp16_t);
375                        rc = qi21_memcpy_d2d(s, pkd, (char*) kw->data + hh * kvt * D * sizeof(ggml_fp16_t),
376                                             n * D * sizeof(ggml_fp16_t));
377                        rc |= qi21_memcpy_d2d(s, pvd, (char*) vw->data + hh * kvt * D * sizeof(ggml_fp16_t),
378                                              n * D * sizeof(ggml_fp16_t));
379                    }
380                    if (rc) break;
381                    rc = qi21_attn_causal(s, (const float*) q16->data, (int) n, kw->data, vw->data, (int) kvt,
382                                          (float*) att->data, (int) H, (int) n, (int) n, 1);
383                } else {
384                    for (int64_t hh = 0; hh < H && L > 0 && rc == 0; ++hh) {
385                        const char* pks = (const char*) pk->data + i * pk->nb[2] + hh * pbytes;
386                        const char* pvs = (const char*) pv->data + i * pv->nb[2] + hh * pbytes;
387                        rc = qi21_memcpy_d2d(s, (char*) kw->data + hh * kvt * D * sizeof(ggml_fp16_t), pks, pbytes);
388                        rc |= qi21_memcpy_d2d(s, (char*) vw->data + hh * kvt * D * sizeof(ggml_fp16_t), pvs, pbytes);
389                    }
390                    if (rc) break;
391                    if (exact_attn) {
392                        // reference: fp32 attention (fp16 K/V as every path has them), slow; STRATA_QI_EXACT_ATTN=1
393                        rc = qi21_attn_causal(s, (const float*) q16->data, (int) n, kw->data, vw->data, (int) kvt,
394                                              (float*) att->data, (int) H, (int) n, (int) kvt, 0);
395                    } else if (use_wmma) {
396                        rc = qi21_attn_wmma(s, q16->data, qsplit ? (char*) q16->data + qlo_off : nullptr, (int) n,
397                                            kw->data, vw->data, (int) kvt, (float*) att->data, (int) H, (int) n,
398                                            (int) kvt);
399                    } else {
400                        // ggml's flash attention (what sd.cpp runs on this backend)
401                        G g = begin();
402                        ggml_tensor* qt = ggml_view_3d(g.ctx, q16, D, n, H, D * sizeof(float), n * D * sizeof(float), 0);
403                        ggml_tensor* kt = ggml_view_3d(g.ctx, kw, D, kvt, H, D * sizeof(ggml_fp16_t),
404                                                       kvt * D * sizeof(ggml_fp16_t), 0);
405                        ggml_tensor* vt = ggml_view_3d(g.ctx, vw, D, kvt, H, D * sizeof(ggml_fp16_t),
406                                                       kvt * D * sizeof(ggml_fp16_t), 0);
407                        ggml_tensor* o  = ggml_flash_attn_ext(g.ctx, qt, kt, vt, nullptr, 1.f / sqrtf((float) D), 0, 0);
408                        ggml_flash_attn_ext_set_prec(o, GGML_PREC_F32);
409                        if (!ggml_backend_supports_op(runtime_backend, o)) {
410                            ggml_free(g.ctx);
411                            rc = 3;
412                            break;
413                        }
414                        bind(o, att);
415                        run(g, {o});
416                    }
417                }
418                if (rc) break;
419                {
420                    G g = begin();
421                    gemm(g, w(b + "attn.to_out.0.weight"), att, h, n);
422                    run(g, {});
423                }
424                rc = res_ln(X, Hh, m1, t1, Hh, m2);
425                if (rc) break;
426                {
427                    G g = begin();
428                    gemm(g, w(b + "img_mlp.gate_up.weight"), h, gu, n);
429                    run(g, {});
430                }
431                rc = qi21_swiglu(s, (const float*) gu->data, (float*) mlp->data, (int) n, (int) F);
432                if (rc) break;
433                {
434                    G g = begin();
435                    gemm(g, w(b + "img_mlp.out.weight"), mlp, h, n);
436                    run(g, {});
437                }
438                const bool last = i + 1 == config.num_layers;
439                rc = res_ln(X, Hh, m3, t3, last ? nullptr : Hh, m0);
440            }
441            if (rc) LOG_WARN("Qwen Image 2.1 native: a kernel failed (%d)", rc);
442            return rc == 0;
443        }
444
445        // ---------------------------------------------------------------- compute
446        sd::Tensor<float> compute(int n_threads, const DiffusionParams& inputs) override {
447            if (disabled) return QwenImage21Runner::compute(n_threads, inputs);
448            const auto& xin     = tensor_or_empty(inputs.x);
449            const auto& context = tensor_or_empty(inputs.context);
450            const auto* extra   = std::get_if<QwenImage21DiffusionExtra>(&inputs.extra);
451            const bool refs     = inputs.ref_latents && inputs.ref_image_params.pass_to_dit && !inputs.ref_latents->empty();
452            const char* why = nullptr;
453            if (xin.empty() || context.empty() || xin.dim() != 4 || xin.shape()[3] != 1 ||
454                xin.shape()[2] != config.in_channels || context.shape()[0] != config.context_dim ||
455                tensor_or_empty(inputs.timesteps).numel() != 1)
456                why = "unexpected input shapes";
457            else if (refs)
458                why = "reference images";
459            else if (!config.fused_mlp)
460                why = "an unfused MLP";
461            else if (!ggml_backend_is_cuda(runtime_backend))
462                why = "not a CUDA / HIP backend";
463            if (why != nullptr) {
464                if (!said_why) LOG_INFO("Qwen Image 2.1 native: %s; this step runs on the stock runner", why);
465                said_why = true;
466                return QwenImage21Runner::compute(n_threads, inputs);
467            }
468            const auto t0 = std::chrono::steady_clock::now();
469            if (!loaded) {
470                wmma_attn = qi21_has_wmma_attn(runtime_backend) && getenv("STRATA_QI_GGML_ATTN") == nullptr;
471                if (!load_weights()) {
472                    fail("could not load the DiT weights onto the GPU");
473                    return QwenImage21Runner::compute(n_threads, inputs);
474                }
475                loaded = true;
476            }
477            const int64_t Wd = xin.shape()[0], Hd = xin.shape()[1], T = Wd * Hd, Lt = context.shape()[1];
478            if (!alloc_acts(T, Lt)) {
479                fail("not enough GPU memory for the activations");
480                return QwenImage21Runner::compute(n_threads, inputs);
481            }
482            // rope tables: sd.cpp's own layout and embedding for [text, image]
483            std::vector<std::pair<int64_t, int64_t>> shapes{{Hd, Wd}};
484            QwenImage21Layout layout;
485            try {
486                layout = QwenImage21Layout::build(Lt, tensor_or_empty(extra ? extra->image_slots : nullptr), shapes);
487            } catch (const std::exception&) {
488                return QwenImage21Runner::compute(n_threads, inputs);
489            }
490            if (layout.segments.size() != 2 || layout.segments[0].image_index >= 0 || layout.prefix_length != Lt) {
491                if (!said_why) LOG_INFO("Qwen Image 2.1 native: images in the prompt; this step runs on the stock runner");
492                said_why = true;
493                return QwenImage21Runner::compute(n_threads, inputs);
494            }
495            Rope::Embedding emb;
496            emb.ids.assign(layout.positions.begin(), layout.positions.end());
497            emb.positions.token_count = emb.ids.size();
498            for (auto region : layout.rope_layout.images) emb.positions.images.push_back(region);
499            emb.values = Rope::embed_nd(emb.ids, 1, 10000.f, config.axes_dim, emb.layout, &emb.frequencies);
500            std::vector<float> pe_all = finish_rope_pe(std::move(emb));
501            const size_t per_tok = 4 * D / 2;
502            if (pe_all.size() != (size_t) (Lt + T) * per_tok) {
503                fail("unexpected rope table size");
504                return QwenImage21Runner::compute(n_threads, inputs);
505            }
506            ggml_backend_tensor_set(pe_img, pe_all.data() + Lt * per_tok, 0, T * per_tok * sizeof(float));
507            // timestep embedding -> modulation rows (image: t, prefix: 0) and the final scale
508            const float tv[2] = {inputs.timesteps->data()[0], 0.f};
509            ggml_backend_tensor_set(timein, tv, 0, sizeof(tv));
510            {
511                G g = begin();
512                ggml_tensor* te = ggml_timestep_embedding(g.ctx, timein, 256, 10000);
513                te = ggml_mul_mat(g.ctx, w("time_text_embed.timestep_embedder.linear_1.weight"), te);
514                te = ggml_silu(g.ctx, te);
515                te = ggml_mul_mat(g.ctx, w("time_text_embed.timestep_embedder.linear_2.weight"), te);
516                te = ggml_silu(g.ctx, te);
517                ggml_tensor* md = ggml_mul_mat(g.ctx, w("modulation.1.weight"), te);
518                ggml_tensor* sc = ggml_mul_mat(g.ctx, w("norm_out.linear.weight"),
519                                               ggml_view_1d(g.ctx, te, C, 0));
520                bind(md, mod);
521                bind(sc, scale_out);
522                run(g, {md, sc});
523            }
524            if (qi21_tanh(qi21_stream(runtime_backend), (const float*) mod->data, (float*) gates->data,
525                          (int) (8 * C)) != 0) {
526                fail("the gate kernel failed");
527                return QwenImage21Runner::compute(n_threads, inputs);
528            }
529            // the text prefix: once per condition
530            uint64_t key = extra != nullptr ? extra->prefix_id : 0;
531            {
532                uint64_t hsh = 1469598103934665603ull;
533                const unsigned char* p = (const unsigned char*) context.data();
534                const size_t nb = context.numel() * sizeof(float);
535                for (size_t i = 0; i < nb; i += 61) hsh = (hsh ^ p[i]) * 1099511628211ull;
536                key = key * 31 + hsh;
537            }
538            if (key != prefix_key || prefix_len != Lt) {
539                ggml_backend_tensor_set(pe_txt, pe_all.data(), 0, Lt * per_tok * sizeof(float));
540                ggml_backend_tensor_set(ctx_in, context.data(), 0, Lt * config.context_dim * sizeof(float));
541                {
542                    // txt_in: zero-centered RMSNorm (weight + 1) -> in_layer -> GELU -> out_layer, into x
543                    G g = begin();
544                    ggml_tensor* t  = ggml_rms_norm(g.ctx, rows(g.ctx, ctx_in, Lt), 1e-6f);
545                    ggml_tensor* nw = ggml_scale_bias(g.ctx, w("txt_in.text_norm.weight"), 1.f, 1.f);
546                    t               = ggml_mul(g.ctx, t, nw);
547                    t               = ggml_mul_mat(g.ctx, w("txt_in.in_layer.weight"), t);
548                    t               = ggml_gelu(g.ctx, t);
549                    t               = ggml_mul_mat(g.ctx, w("txt_in.out_layer.weight"), t);
550                    bind(t, x);
551                    run(g, {t});
552                }
553                if (!blocks_pass(Lt, 1, pe_txt, 0)) {
554                    fail("the text prefix pass failed");
555                    return QwenImage21Runner::compute(n_threads, inputs);
556                }
557                prefix_key = key;
558                prefix_len = Lt;
559            }
560            // the image tokens: patchify (patch 1: token h*W + w, channels), img_in, the blocks, the output head
561            {
562                std::vector<float> tok((size_t) T * config.in_channels);
563                const float* xs = xin.data();
564                for (int64_t c = 0; c < config.in_channels; ++c)
565                    for (int64_t t = 0; t < T; ++t) tok[(size_t) t * config.in_channels + c] = xs[(size_t) c * T + t];
566                ggml_backend_tensor_set(latent, tok.data(), 0, tok.size() * sizeof(float));
567                G g = begin();
568                gemm(g, w("img_in.weight"), latent, x, T);
569                run(g, {});
570            }
571            if (!blocks_pass(T, 0, pe_img, Lt)) {
572                fail("the image pass failed");
573                return QwenImage21Runner::compute(n_threads, inputs);
574            }
575            {
576                G g = begin();
577                ggml_tensor* t = ggml_norm(g.ctx, rows(g.ctx, x, T), 1e-6f);
578                t              = ggml_mul(g.ctx, t, ggml_scale_bias(g.ctx, scale_out, 1.f, 1.f));
579                t              = ggml_mul_mat(g.ctx, w("proj_out.weight"), t);
580                bind(t, outp);
581                run(g, {t});
582            }
583            ggml_backend_synchronize(runtime_backend);
584            std::vector<float> o((size_t) T * config.out_channels);
585            ggml_backend_tensor_get(outp, o.data(), 0, o.size() * sizeof(float));
586            sd::Tensor<float> result({Wd, Hd, config.out_channels, 1});
587            float* r = result.data();
588            for (int64_t c = 0; c < config.out_channels; ++c)
589                for (int64_t t = 0; t < T; ++t) r[(size_t) c * T + t] = o[(size_t) t * config.out_channels + c];
590            if (timing) {
591                const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
592                LOG_INFO("Qwen Image 2.1 native: step %.1f ms (%lld image tokens, prefix %lld)", ms, (long long) T,
593                         (long long) Lt);
594            }
595            return restore_trailing_singleton_dims(std::move(result), xin.dim());
596        }
597    };
598
599}  // namespace Qwen
600
601#endif  // __SD_MODEL_DIFFUSION_QWEN_IMAGE_2_1_NATIVE_H__