Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
Images (I2): native Qwen-Image-2.1 DiT runner inside stable-diffusion.cpp, opt-in
Niko12215be585a2cfbd
diff --git a/tools/image/sdcpp_native/apply.py b/tools/image/sdcpp_native/apply.pynew file mode 100644index 000000000..343b9b25f--- /dev/null+++ b/tools/image/sdcpp_native/apply.py@@ -0,0 +1,75 @@+"""tools/image/sdcpp_native/apply.py - put Strata's native Qwen-Image-2.1 DiT runner into a stable-diffusion.cpp+checkout at the pinned commit (tools/image/qimage.py SD_CPP_COMMIT). Idempotent; the stock runner stays the+default: sd-cli uses the native one only with --model-args qwen_image_2_1_native=1 (serve/images.py adds it when the+config's "native" is true), and only in CUDA / HIP builds.++ python tools/image/sdcpp_native/apply.py third_party/stable-diffusion.cpp++Two new files (the kernels into ggml/src/ggml-cuda/, which ggml-cuda and ggml-hip compile by glob; the runner into+src/model/diffusion/) and two small edits (model_builders.cpp picks the runner; CMakeLists.txt defines SD_QI_NATIVE+for CUDA / HIP builds)."""+from __future__ import annotations++import shutil+import sys+from pathlib import Path++HERE = Path(__file__).resolve().parent+MARK = "// strata: native Qwen-Image-2.1 runner"++BUILDER_OLD = """ if (version == VERSION_QWEN_IMAGE_2_1) {+ result.diffusion = std::make_shared<Qwen::QwenImage21Runner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),+ tensor_storage_map,+ "model.diffusion_model",+ weight_manager,+ sd_ctx_params->model_args);+"""+BUILDER_NEW = """ if (version == VERSION_QWEN_IMAGE_2_1) {+#ifdef SD_QI_NATIVE+ """ + MARK + """ (--model-args qwen_image_2_1_native=1)+ if (sd_ctx_params->model_args != nullptr &&+ std::strstr(sd_ctx_params->model_args, "qwen_image_2_1_native=1") != nullptr &&+ sd_ctx_params->diffusion_model_path != nullptr && sd_ctx_params->diffusion_model_path[0] != 0) {+ result.diffusion = std::make_shared<Qwen::QwenImage21NativeRunner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),+ tensor_storage_map,+ "model.diffusion_model",+ weight_manager,+ sd_ctx_params->model_args,+ sd_ctx_params->diffusion_model_path);+ } else+#endif+ result.diffusion = std::make_shared<Qwen::QwenImage21Runner>(ctx.backends.runtime_backend(SDBackendModule::DIFFUSION),+ tensor_storage_map,+ "model.diffusion_model",+ weight_manager,+ sd_ctx_params->model_args);+"""+INCLUDE_OLD = '#include "model/diffusion/minit2i.hpp"\n'+INCLUDE_NEW = INCLUDE_OLD + "#ifdef SD_QI_NATIVE\n#include \"model/diffusion/qwen_image_2_1_native.hpp\" " + MARK + "\n#endif\n"+CMAKE_OLD = "target_include_directories(${SD_LIB} PUBLIC . src include)\n"+CMAKE_NEW = ("if (SD_CUDA OR SD_HIPBLAS) # " + MARK.lstrip("/ ") + "\n"+ " target_compile_definitions(${SD_LIB} PRIVATE SD_QI_NATIVE)\nendif()\n" + CMAKE_OLD)+++def edit(path: Path, old: str, new: str) -> None:+ text = path.read_text(encoding="utf-8")+ if new in text:+ return+ if text.count(old) != 1:+ raise SystemExit(f"{path}: the expected code is not there (another stable-diffusion.cpp commit?)")+ path.write_text(text.replace(old, new), encoding="utf-8")+++def apply(sd: Path) -> None:+ sd = Path(sd)+ shutil.copy2(HERE / "qi21-native.cu", sd / "ggml" / "src" / "ggml-cuda" / "qi21-native.cu")+ shutil.copy2(HERE / "qwen_image_2_1_native.hpp", sd / "src" / "model" / "diffusion" / "qwen_image_2_1_native.hpp")+ builders = sd / "src" / "pipeline" / "model_builders.cpp"+ edit(builders, INCLUDE_OLD, INCLUDE_NEW)+ edit(builders, BUILDER_OLD, BUILDER_NEW)+ edit(sd / "CMakeLists.txt", CMAKE_OLD, CMAKE_NEW)+++if __name__ == "__main__":+ apply(Path(sys.argv[1]))+ print("native Qwen-Image-2.1 runner applied")diff --git a/tools/image/sdcpp_native/qi21-native.cu b/tools/image/sdcpp_native/qi21-native.cunew file mode 100644index 000000000..87e7d7fc4--- /dev/null+++ b/tools/image/sdcpp_native/qi21-native.cu@@ -0,0 +1,357 @@+// qi21-native.cu - Strata's native kernels for the Qwen-Image-2.1 DiT inside stable-diffusion.cpp (CUDA and HIP).+//+// Copied into ggml/src/ggml-cuda/ by tools/image/sdcpp_native/apply.py, so ggml-cuda and ggml-hip compile it with+// their own toolchain and vendor headers. The host side (qwen_image_2_1_native.hpp) runs the GEMMs as ggml graphs+// on the same backend and calls these launchers on the backend's own stream, so everything stays stream-ordered.+//+// qi21_res_ln_mod x += h * tanh(g) (optional), then out = LayerNorm(x) * (1 + m) (no affine, eps)+// qi21_qkv_post per head: RMSNorm(q|k) * w, 3-axis RoPE from sd.cpp's pe table, K/V to fp16, head-major+// qi21_swiglu out = up * silu(gate) (gate = first half of the fused gate_up output)+// qi21_attn_causal plain fp32 attention for the text prefix (causal; once per prompt)+// qi21_attn_wmma gfx11 WMMA flash attention (fp16 in, fp32 softmax and accumulation) for the image tokens+#include "common.cuh"+#include "ggml-backend-impl.h"++#include <cstdint>++namespace {++constexpr int QI_D = 128;++__device__ __forceinline__ float qi_block_sum(float v, float* red) {+ // blockDim.x is a multiple of 32 and <= 1024+ for (int off = 16; off > 0; off >>= 1) v += __shfl_xor_sync(0xffffffff, v, off, 32);+ const int w = threadIdx.x >> 5, l = threadIdx.x & 31;+ __syncthreads();+ if (l == 0) red[w] = v;+ __syncthreads();+ const int nw = blockDim.x >> 5;+ float s = threadIdx.x < nw ? red[threadIdx.x] : 0.f;+ if (w == 0) {+ for (int off = 16; off > 0; off >>= 1) s += __shfl_xor_sync(0xffffffff, s, off, 32);+ if (l == 0) red[0] = s;+ }+ __syncthreads();+ return red[0];+}++template <bool RES, bool LN>+__global__ void __launch_bounds__(256) k_res_ln_mod(float* __restrict__ x, const float* __restrict__ h,+ const float* __restrict__ g, float* __restrict__ out,+ const float* __restrict__ m, int C, float eps) {+ __shared__ float red[32];+ const size_t row = blockIdx.x;+ float* xr = x + row * C;+ float v[32];+ int n = 0;+ float s = 0.f;+ for (int c = threadIdx.x; c < C; c += blockDim.x) {+ float a = xr[c];+ if (RES) {+ a += h[row * C + c] * tanhf(g[c]);+ xr[c] = a;+ }+ v[n++] = a;+ s += a;+ }+ if (!LN) return;+ const float mean = qi_block_sum(s, red) / C;+ float q = 0.f;+ for (int i = 0; i < n; ++i) q += (v[i] - mean) * (v[i] - mean);+ const float inv = rsqrtf(qi_block_sum(q, red) / C + eps);+ n = 0;+ for (int c = threadIdx.x; c < C; c += blockDim.x) out[row * C + c] = (v[n++] - mean) * inv * (1.f + m[c]);+}++// grid (T, H), block 128: one head of one token. src rows have stride ld (floats).+template <typename QT>+__global__ void __launch_bounds__(QI_D) k_qkv_post(const float* __restrict__ q, const float* __restrict__ k,+ const float* __restrict__ v, int ld, const float* __restrict__ wq,+ const float* __restrict__ wk, const float* __restrict__ pe,+ QT* __restrict__ qo, half* __restrict__ qlo, int q_tstride,+ half* __restrict__ ko,+ half* __restrict__ vo, int kv_tstride, int kv_off, float eps) {+ __shared__ float red[32];+ __shared__ float buf[QI_D];+ const int t = blockIdx.x, hh = blockIdx.y, d = threadIdx.x;+ const size_t src = (size_t) t * ld + hh * QI_D + d;+ const float* p = pe + ((size_t) t * (QI_D / 2) + (d >> 1)) * 4;+ for (int which = 0; which < 2; ++which) {+ const float x = which == 0 ? q[src] : k[src];+ const float ss = qi_block_sum(x * x, red);+ const float y = x * rsqrtf(ss / QI_D + eps) * (which == 0 ? wq[d] : wk[d]);+ buf[d] = y;+ __syncthreads();+ const float x0 = buf[d & ~1], x1 = buf[d | 1];+ const float r = (d & 1) ? p[2] * x0 + p[3] * x1 : p[0] * x0 + p[1] * x1;+ __syncthreads();+ if (which == 0) {+ const size_t qi = ((size_t) hh * q_tstride + t) * QI_D + d;+ qo[qi] = (QT) r;+ if (qlo != nullptr) qlo[qi] = __float2half(r - __half2float(__float2half(r)));+ } else {+ ko[((size_t) hh * kv_tstride + kv_off + t) * QI_D + d] = __float2half(r);+ }+ }+ vo[((size_t) hh * kv_tstride + kv_off + t) * QI_D + d] = __float2half(v[src]);+}++__global__ void k_swiglu(const float* __restrict__ gu, float* __restrict__ out, int F, int64_t n) {+ const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;+ if (i >= n) return;+ const int64_t t = i / F, c = i % F;+ const float g = gu[t * 2 * F + c], u = gu[t * 2 * F + F + c];+ out[i] = u * (g / (1.f + expf(-g)));+}++// grid (Lq, H), block 128, dynamic smem Lk floats. q fp32 head-major [H][q_tstride][128], k/v fp16 [H][kv_tstride][128],+// out token-major [Lq][H*128]. causal: query i sees keys 0..i.+__global__ void __launch_bounds__(QI_D) k_attn_causal(const float* __restrict__ q, int q_tstride,+ const half* __restrict__ k, const half* __restrict__ v,+ int kv_tstride, float* __restrict__ out, int H, int Lk,+ int causal, float scale) {+ extern __shared__ float s[];+ __shared__ float red[32];+ __shared__ float qs[QI_D];+ const int i = blockIdx.x, hh = blockIdx.y, d = threadIdx.x;+ qs[d] = q[((size_t) hh * q_tstride + i) * QI_D + d];+ __syncthreads();+ const int n = causal ? i + 1 : Lk;+ float mx = -INFINITY;+ for (int j = d; j < n; j += QI_D) {+ const half* kr = k + ((size_t) hh * kv_tstride + j) * QI_D;+ float dot = 0.f;+ for (int c = 0; c < QI_D; ++c) dot += qs[c] * __half2float(kr[c]);+ s[j] = dot * scale;+ mx = fmaxf(mx, s[j]);+ }+ // block max+ for (int off = 16; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor_sync(0xffffffff, mx, off, 32));+ __syncthreads();+ if ((d & 31) == 0) red[d >> 5] = mx;+ __syncthreads();+ mx = red[0];+ for (int w = 1; w < QI_D / 32; ++w) mx = fmaxf(mx, red[w]);+ __syncthreads();+ float sum = 0.f;+ for (int j = d; j < n; j += QI_D) {+ s[j] = expf(s[j] - mx);+ sum += s[j];+ }+ sum = qi_block_sum(sum, red);+ float acc = 0.f;+ for (int j = 0; j < n; ++j) acc += s[j] * __half2float(v[((size_t) hh * kv_tstride + j) * QI_D + d]);+ out[(size_t) i * H * QI_D + hh * QI_D + d] = acc / sum;+}++#if defined(GGML_USE_HIP)+typedef _Float16 qi_h16 __attribute__((ext_vector_type(16)));+typedef float qi_f8 __attribute__((ext_vector_type(8)));+constexpr int FA_BQ = 128, FA_BKV = 64, FA_NW = 8, FA_KLD = QI_D + 8, FA_VLD = FA_BKV + 8, FA_PLD = FA_BKV + 8;++__device__ __forceinline__ qi_h16 qi_ld16(const _Float16* p) {+ const uint4 a = *reinterpret_cast<const uint4*>(p), b = *reinterpret_cast<const uint4*>(p + 8);+ const uint32_t w[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w};+ return __builtin_bit_cast(qi_h16, w);+}++// gfx11 WMMA flash attention: q fp16 head-major [H][q_tstride][128], k/v fp16 head-major [H][kv_tstride][128]+// (no mask), out fp32 token-major [nq][H*128]. 8 waves x 16 query rows; 64-key tiles through LDS (V transposed).+template <bool LO>+__global__ void __launch_bounds__(FA_NW * 32) k_attn_wmma(const _Float16* __restrict__ Q, const _Float16* __restrict__ Qlo,+ int q_tstride,+ const _Float16* __restrict__ K, const _Float16* __restrict__ V,+ int kv_tstride, float* __restrict__ O, int H, int nq, int nkv,+ float scale_log2) {+#if defined(RDNA3)+ __shared__ __align__(16) _Float16 sK[FA_BKV][FA_KLD];+ __shared__ __align__(16) _Float16 sVt[QI_D][FA_VLD];+ __shared__ __align__(16) _Float16 sP[FA_NW][16][FA_PLD];+ const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, l16 = lane & 15, hi = lane >> 4;+ const int head = blockIdx.y, q0 = blockIdx.x * FA_BQ + wave * 16;+ const _Float16* Qh = Q + (size_t) head * q_tstride * QI_D;+ const _Float16* Kh = K + (size_t) head * kv_tstride * QI_D;+ const _Float16* Vh = V + (size_t) head * kv_tstride * QI_D;+ qi_h16 qa[QI_D / 16], ql[LO ? QI_D / 16 : 1];+ {+ const int qr = min(q0 + l16, nq - 1);+ for (int c = 0; c < QI_D / 16; ++c) qa[c] = qi_ld16(Qh + (size_t) qr * QI_D + c * 16);+ if (LO) {+ const _Float16* Ql = Qlo + (size_t) head * q_tstride * QI_D;+ for (int c = 0; c < QI_D / 16; ++c) ql[c] = qi_ld16(Ql + (size_t) qr * QI_D + c * 16);+ }+ }+ qi_f8 o[QI_D / 16];+ for (int c = 0; c < QI_D / 16; ++c) o[c] = qi_f8{};+ float m[8], l[8];+ for (int i = 0; i < 8; ++i) { m[i] = -INFINITY; l[i] = 0.f; }+ for (int k0 = 0; k0 < nkv; k0 += FA_BKV) {+ __syncthreads();+ for (int e = tid * 8; e < FA_BKV * QI_D; e += FA_NW * 32 * 8) {+ const int r = e / QI_D, c = e % QI_D, key = k0 + r;+ uint4 kv = make_uint4(0, 0, 0, 0);+ if (key < nkv) kv = *reinterpret_cast<const uint4*>(Kh + (size_t) key * QI_D + c);+ *reinterpret_cast<uint4*>(&sK[r][c]) = kv;+ }+ for (int e = tid; e < (FA_BKV / 4) * (QI_D / 8); e += FA_NW * 32) {+ const int r4 = (e / (QI_D / 8)) * 4, c = (e % (QI_D / 8)) * 8;+ _Float16 vv[4][8];+ for (int j = 0; j < 4; ++j) {+ uint4 x = make_uint4(0, 0, 0, 0);+ if (k0 + r4 + j < nkv) x = *reinterpret_cast<const uint4*>(Vh + (size_t) (k0 + r4 + j) * QI_D + c);+ *reinterpret_cast<uint4*>(vv[j]) = x;+ }+ for (int dd = 0; dd < 8; ++dd) {+ _Float16 w4[4] = {vv[0][dd], vv[1][dd], vv[2][dd], vv[3][dd]};+ *reinterpret_cast<uint2*>(&sVt[c + dd][r4]) = *reinterpret_cast<uint2*>(w4);+ }+ }+ __syncthreads();+ qi_f8 s[FA_BKV / 16];+ for (int t = 0; t < FA_BKV / 16; ++t) {+ s[t] = qi_f8{};+ for (int c = 0; c < QI_D / 16; ++c) {+ const qi_h16 kb = qi_ld16(&sK[t * 16 + l16][c * 16]);+ s[t] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(qa[c], kb, s[t]);+ if (LO) s[t] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(ql[LO ? c : 0], kb, s[t]);+ }+ }+ float alpha[8];+ for (int i = 0; i < 8; ++i) {+ float mx = -INFINITY;+ for (int t = 0; t < FA_BKV / 16; ++t) {+ const float val = k0 + t * 16 + l16 < nkv ? s[t][i] * scale_log2 : -INFINITY;+ s[t][i] = val;+ mx = fmaxf(mx, val);+ }+ for (int off = 1; off < 16; off <<= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 32));+ const float mnew = fmaxf(m[i], mx);+ alpha[i] = exp2f(m[i] - mnew);+ float sum = 0.f;+ for (int t = 0; t < FA_BKV / 16; ++t) {+ const float pv = exp2f(s[t][i] - mnew);+ s[t][i] = pv;+ sum += pv;+ }+ for (int off = 1; off < 16; off <<= 1) sum += __shfl_xor(sum, off, 32);+ l[i] = l[i] * alpha[i] + sum;+ m[i] = mnew;+ }+ for (int c = 0; c < QI_D / 16; ++c)+ for (int i = 0; i < 8; ++i) o[c][i] *= alpha[i];+ for (int t = 0; t < FA_BKV / 16; ++t)+ for (int i = 0; i < 8; ++i) sP[wave][2 * i + hi][t * 16 + l16] = (_Float16) s[t][i];+ __builtin_amdgcn_s_waitcnt(0);+ __builtin_amdgcn_wave_barrier();+ for (int kc = 0; kc < FA_BKV / 16; ++kc) {+ const qi_h16 pa = qi_ld16(&sP[wave][l16][kc * 16]);+ for (int c = 0; c < QI_D / 16; ++c)+ o[c] = __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(pa, qi_ld16(&sVt[c * 16 + l16][kc * 16]), o[c]);+ }+ }+ for (int c = 0; c < QI_D / 16; ++c)+ for (int i = 0; i < 8; ++i) {+ const int row = q0 + 2 * i + hi;+ if (row < nq) O[(size_t) row * H * QI_D + head * QI_D + c * 16 + l16] = o[c][i] / l[i];+ }+#else+ __builtin_trap();+#endif+}+#endif // GGML_USE_HIP++inline cudaStream_t qi_s(void* s) { return static_cast<cudaStream_t>(s); }++} // namespace++extern "C" {++void* qi21_stream(ggml_backend_t backend) {+ return static_cast<ggml_backend_cuda_context*>(backend->context)->stream();+}++// 1 when this backend's GPU runs qi21_attn_wmma (an RDNA3 / gfx11 card in a HIP build)+int qi21_has_wmma_attn(ggml_backend_t backend) {+#if defined(GGML_USE_HIP)+ const int dev = static_cast<ggml_backend_cuda_context*>(backend->context)->device;+ return GGML_CUDA_CC_IS_RDNA3(ggml_cuda_info().devices[dev].cc) ? 1 : 0;+#else+ (void) backend;+ return 0;+#endif+}++int qi21_res_ln_mod(void* stream, float* x, const float* h, const float* g, float* out, const float* m, int T, int C,+ float eps) {+ if (C > 32 * 256) return 1;+ if (h != nullptr && out != nullptr)+ k_res_ln_mod<true, true><<<T, 256, 0, qi_s(stream)>>>(x, h, g, out, m, C, eps);+ else if (h != nullptr)+ k_res_ln_mod<true, false><<<T, 256, 0, qi_s(stream)>>>(x, h, g, out, m, C, eps);+ else+ k_res_ln_mod<false, true><<<T, 256, 0, qi_s(stream)>>>(x, h, g, out, m, C, eps);+ return cudaGetLastError() == cudaSuccess ? 0 : 2;+}++int qi21_qkv_post(void* stream, const float* q, const float* k, const float* v, int ld, const float* wq, const float* wk,+ const float* pe, void* qo, void* qlo, int q_f16, int q_tstride, void* ko, void* vo, int kv_tstride,+ int kv_off, int T, int H, float eps) {+ const dim3 grid(T, H);+ if (q_f16)+ k_qkv_post<half><<<grid, QI_D, 0, qi_s(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<half*>(qo),+ static_cast<half*>(qlo), q_tstride,+ static_cast<half*>(ko), static_cast<half*>(vo), kv_tstride,+ kv_off, eps);+ else+ k_qkv_post<float><<<grid, QI_D, 0, qi_s(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<float*>(qo), nullptr,+ q_tstride,+ static_cast<half*>(ko), static_cast<half*>(vo), kv_tstride,+ kv_off, eps);+ return cudaGetLastError() == cudaSuccess ? 0 : 2;+}++int qi21_swiglu(void* stream, const float* gu, float* out, int T, int F) {+ const int64_t n = (int64_t) T * F;+ k_swiglu<<<(unsigned) ((n + 255) / 256), 256, 0, qi_s(stream)>>>(gu, out, F, n);+ return cudaGetLastError() == cudaSuccess ? 0 : 2;+}++int qi21_attn_causal(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride,+ float* out, int H, int Lq, int Lk, int causal) {+ const size_t smem = (size_t) Lk * sizeof(float);+ if (smem > 48 * 1024) return 1;+ k_attn_causal<<<dim3(Lq, H), QI_D, smem, qi_s(stream)>>>(q, q_tstride, static_cast<const half*>(k),+ static_cast<const half*>(v), kv_tstride, out, H, Lk,+ causal, 1.f / sqrtf((float) QI_D));+ return cudaGetLastError() == cudaSuccess ? 0 : 2;+}++int qi21_attn_wmma(void* stream, const void* q, const void* qlo, int q_tstride, const void* k, const void* v,+ int kv_tstride, float* out, int H, int nq, int nkv) {+#if defined(GGML_USE_HIP)+ const dim3 grid((nq + FA_BQ - 1) / FA_BQ, H);+ const float sl = (float) (1.0 / sqrt((double) QI_D) * 1.4426950408889634);+ if (qlo != nullptr)+ k_attn_wmma<true><<<grid, FA_NW * 32, 0, qi_s(stream)>>>(static_cast<const _Float16*>(q),+ static_cast<const _Float16*>(qlo), q_tstride,+ static_cast<const _Float16*>(k),+ static_cast<const _Float16*>(v), kv_tstride, out, H,+ nq, nkv, sl);+ else+ k_attn_wmma<false><<<grid, FA_NW * 32, 0, qi_s(stream)>>>(static_cast<const _Float16*>(q), nullptr, q_tstride,+ static_cast<const _Float16*>(k),+ static_cast<const _Float16*>(v), kv_tstride, out, H,+ nq, nkv, sl);+ return cudaGetLastError() == cudaSuccess ? 0 : 2;+#else+ (void) stream; (void) q; (void) qlo; (void) q_tstride; (void) k; (void) v; (void) kv_tstride; (void) out; (void) H; (void) nq;+ (void) nkv;+ return 1;+#endif+}++int qi21_memcpy_d2d(void* stream, void* dst, const void* src, size_t n) {+ return cudaMemcpyAsync(dst, src, n, cudaMemcpyDeviceToDevice, qi_s(stream)) == cudaSuccess ? 0 : 2;+}++} // extern "C"diff --git a/tools/image/sdcpp_native/qwen_image_2_1_native.hpp b/tools/image/sdcpp_native/qwen_image_2_1_native.hppnew file mode 100644index 000000000..9740a1534--- /dev/null+++ b/tools/image/sdcpp_native/qwen_image_2_1_native.hpp@@ -0,0 +1,535 @@+// qwen_image_2_1_native.hpp - Strata's native Qwen-Image-2.1 DiT runner for stable-diffusion.cpp (CUDA / HIP builds).+//+// Copied into src/model/diffusion/ by tools/image/sdcpp_native/apply.py and chosen by model_builders.cpp when the+// model args contain qwen_image_2_1_native=1. sd.cpp keeps the text encoder, the VAE, the sampler and the RNG; this+// runner replaces only QwenImage21Runner::compute (latent + timestep + text condition in, velocity out, on the host).+//+// Per step: the 32 blocks run on the image tokens only. The text prefix (causal within the text, timestep-free:+// its modulation row is the t = 0 one) goes through all blocks once per prompt and leaves each layer's K/V (fp16)+// behind - the same prefix cache sd.cpp keeps. GEMMs are ggml graphs on the runner's backend (the MMQ / BLAS+// kernels sd.cpp uses, same numerics); LayerNorm+modulate, gate+residual, q/k RMSNorm+RoPE, SwiGLU and (on gfx11)+// the image attention are Strata kernels (ggml/src/ggml-cuda/qi21-native.cu) on the backend's stream. Anything this+// runner does not cover (reference images, an unfused MLP, a CPU / Vulkan backend, too little VRAM) goes to the+// stock runner.+#ifndef __SD_MODEL_DIFFUSION_QWEN_IMAGE_2_1_NATIVE_H__+#define __SD_MODEL_DIFFUSION_QWEN_IMAGE_2_1_NATIVE_H__++#include <chrono>+#include <cstdio>+#include <cstring>+#include <memory>++#include "ggml-alloc.h"+#include "ggml-backend.h"+#include "ggml-cuda.h"+#include "gguf.h"+#include "model/diffusion/qwen_image_2_1.hpp"++extern "C" {+void* qi21_stream(ggml_backend_t backend);+int qi21_has_wmma_attn(ggml_backend_t backend);+int qi21_res_ln_mod(void* stream, float* x, const float* h, const float* g, float* out, const float* m, int T, int C,+ float eps);+int qi21_qkv_post(void* stream, const float* q, const float* k, const float* v, int ld, const float* wq, const float* wk,+ const float* pe, void* qo, void* qlo, int q_f16, int q_tstride, void* ko, void* vo, int kv_tstride,+ int kv_off, int T, int H, float eps);+int qi21_swiglu(void* stream, const float* gu, float* out, int T, int F);+int qi21_attn_causal(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride,+ float* out, int H, int Lq, int Lk, int causal);+int qi21_attn_wmma(void* stream, const void* q, const void* qlo, int q_tstride, const void* k, const void* v,+ int kv_tstride, float* out, int H, int nq, int nkv);+int qi21_memcpy_d2d(void* stream, void* dst, const void* src, size_t n);+}++namespace Qwen {++ struct QwenImage21NativeRunner : public QwenImage21Runner {+ static constexpr int64_t C = 4096, D = 128, H = 32, F = 12288;+ std::string dit_path;+ bool disabled = false; // a failure: the stock runner from here on+ bool loaded = false;+ bool wmma_attn = false;+ bool timing = false;+ bool said_why = false;+ bool qsplit = false;+ bool exact_attn = false;++ // weights (our own copy: the stock runner's params are never loaded, they load lazily on first use)+ ggml_context* wctx = nullptr;+ ggml_backend_buffer_t wbuf = nullptr;+ std::map<std::string, ggml_tensor*> W;++ // activations, sized for t_cap image tokens and l_cap prefix tokens+ ggml_context* actx = nullptr;+ ggml_backend_buffer_t abuf = nullptr;+ int64_t t_cap = 0, l_cap = 0;+ ggml_tensor *x, *h, *q, *k, *v, *att, *gu, *mlp, *q16, *kw, *vw, *pe_img, *pe_txt, *latent, *outp, *timein,+ *mod, *scale_out, *ctx_in, *pk, *pv;++ // the prefix cache: per layer K/V of the text tokens (fp16, head-major), for one condition+ uint64_t prefix_key = 0;+ int64_t prefix_len = -1;++ std::vector<char> gbuf; // ggml graph metadata arena++ QwenImage21NativeRunner(ggml_backend_t backend, const String2TensorStorage& weights, const std::string& prefix,+ std::shared_ptr<RunnerWeightManager> weight_manager, const char* model_args,+ std::string dit_path)+ : QwenImage21Runner(backend, weights, prefix, weight_manager, model_args), dit_path(std::move(dit_path)) {+ timing = getenv("STRATA_QI_TIMING") != nullptr;+ qsplit = getenv("STRATA_QI_QSPLIT") != nullptr; // measured: no accuracy gain, +7% step time+ exact_attn = getenv("STRATA_QI_EXACT_ATTN") != nullptr;+ gbuf.resize(64 << 20);+ }++ ~QwenImage21NativeRunner() override { release(); }++ std::string get_desc() override { return "qwen_image_2_1 (strata native)"; }++ void release() {+ if (abuf) ggml_backend_buffer_free(abuf);+ if (actx) ggml_free(actx);+ if (wbuf) ggml_backend_buffer_free(wbuf);+ if (wctx) ggml_free(wctx);+ abuf = nullptr; actx = nullptr; wbuf = nullptr; wctx = nullptr;+ W.clear();+ loaded = false;+ t_cap = l_cap = 0;+ prefix_len = -1;+ }++ void fail(const char* why) {+ LOG_WARN("Qwen Image 2.1 native: %s; using the stock runner", why);+ release();+ disabled = true;+ }++ ggml_tensor* w(const std::string& name) {+ auto it = W.find("model.diffusion_model." + name);+ return it == W.end() ? nullptr : it->second;+ }++ // ---------------------------------------------------------------- weights+ bool load_weights() {+ ggml_context* meta = nullptr;+ gguf_init_params gp{true, &meta};+ gguf_context* g = gguf_init_from_file(dit_path.c_str(), gp);+ if (g == nullptr) return false;+ const int64_t n = gguf_get_n_tensors(g);+ wctx = ggml_init({(size_t) (n + 8) * ggml_tensor_overhead(), nullptr, true});+ std::vector<std::pair<ggml_tensor*, size_t>> plan;+ std::map<ggml_tensor*, ggml_type> widened;+ const size_t base = gguf_get_data_offset(g);+ for (int64_t i = 0; i < n; ++i) {+ const char* name = gguf_get_tensor_name(g, i);+ if (strncmp(name, "model.diffusion_model.", 22) != 0) continue;+ ggml_tensor* src = ggml_get_tensor(meta, name);+ // a 1-D norm weight in BF16 / F16 is kept as F32 (elementwise ops on it then work on every backend)+ const bool widen = ggml_n_dims(src) == 1 && src->type != GGML_TYPE_F32;+ ggml_tensor* t = widen ? ggml_new_tensor_1d(wctx, GGML_TYPE_F32, src->ne[0]) : ggml_dup_tensor(wctx, src);+ if (widen) widened[t] = src->type;+ ggml_set_name(t, name);+ W[name] = t;+ plan.push_back({t, base + gguf_get_tensor_offset(g, i)});+ }+ wbuf = ggml_backend_alloc_ctx_tensors(wctx, runtime_backend);+ if (wbuf == nullptr) {+ gguf_free(g);+ ggml_free(meta);+ return false;+ }+ FILE* f = fopen(dit_path.c_str(), "rb");+ std::vector<char> stage(64 << 20);+ bool ok = f != nullptr;+ for (auto& [t, off] : plan) {+ if (!ok) break;+ auto wi = widened.find(t);+ const size_t nb = wi == widened.end() ? ggml_nbytes(t)+ : ggml_row_size(wi->second, t->ne[0]);+#ifdef _WIN32+ ok = _fseeki64(f, (long long) off, SEEK_SET) == 0;+#else+ ok = fseeko(f, (off_t) off, SEEK_SET) == 0;+#endif+ if (wi != widened.end()) {+ std::vector<char> raw(nb);+ std::vector<float> f32(t->ne[0]);+ ok = fread(raw.data(), 1, nb, f) == nb;+ if (ok) {+ ggml_get_type_traits(wi->second)->to_float(raw.data(), f32.data(), t->ne[0]);+ ggml_backend_tensor_set(t, f32.data(), 0, f32.size() * sizeof(float));+ }+ continue;+ }+ for (size_t done = 0; ok && done < nb;) {+ const size_t c = std::min(stage.size(), nb - done);+ ok = fread(stage.data(), 1, c, f) == c;+ if (ok) ggml_backend_tensor_set(t, stage.data(), done, c);+ done += c;+ }+ }+ if (f) fclose(f);+ gguf_free(g);+ ggml_free(meta);+ if (!ok) return false;+ for (int i = 0; i < config.num_layers; ++i) {+ const std::string b = "transformer_blocks." + std::to_string(i) + ".";+ for (const char* s : {"attn.to_q.weight", "attn.to_k.weight", "attn.to_v.weight", "attn.to_out.0.weight",+ "attn.norm_q.weight", "attn.norm_k.weight", "img_mlp.gate_up.weight",+ "img_mlp.out.weight"}) {+ if (w(b + s) == nullptr) return false;+ }+ if (w(b + "attn.norm_q.weight")->type != GGML_TYPE_F32 || w(b + "attn.norm_k.weight")->type != GGML_TYPE_F32)+ return false;+ }+ for (const char* s : {"img_in.weight", "txt_in.text_norm.weight", "txt_in.in_layer.weight", "txt_in.out_layer.weight",+ "time_text_embed.timestep_embedder.linear_1.weight",+ "time_text_embed.timestep_embedder.linear_2.weight", "modulation.1.weight",+ "norm_out.linear.weight", "proj_out.weight"}) {+ if (w(s) == nullptr) return false;+ }+ LOG_INFO("Qwen Image 2.1 native: %zu tensors, %.2f GB on %s%s", W.size(),+ ggml_backend_buffer_get_size(wbuf) / 1e9, ggml_backend_name(runtime_backend),+ wmma_attn ? " (WMMA attention)" : "");+ return true;+ }++ // ---------------------------------------------------------------- activations+ bool alloc_acts(int64_t T, int64_t L) {+ if (T <= t_cap && L <= l_cap) return true;+ if (abuf) ggml_backend_buffer_free(abuf);+ if (actx) ggml_free(actx);+ t_cap = std::max(T, t_cap);+ l_cap = std::max(L, l_cap);+ const int64_t R = std::max(t_cap, l_cap); // rows of the shared work buffers+ actx = ggml_init({64 * ggml_tensor_overhead(), nullptr, true});+ x = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);+ h = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);+ q = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);+ k = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);+ v = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);+ att = ggml_new_tensor_2d(actx, GGML_TYPE_F32, C, R);+ gu = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 2 * F, R);+ mlp = ggml_new_tensor_2d(actx, GGML_TYPE_F32, F, R);+ q16 = ggml_new_tensor_3d(actx, GGML_TYPE_F32, D, R, H); // fp16 or fp32 queries, head-major+ kw = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D, l_cap + t_cap, H);+ vw = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D, l_cap + t_cap, H);+ pe_img = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 4 * D / 2, t_cap);+ pe_txt = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 4 * D / 2, std::max<int64_t>(l_cap, 1));+ latent = ggml_new_tensor_2d(actx, GGML_TYPE_F32, config.in_channels, t_cap);+ outp = ggml_new_tensor_2d(actx, GGML_TYPE_F32, config.out_channels, t_cap);+ timein = ggml_new_tensor_1d(actx, GGML_TYPE_F32, 2);+ mod = ggml_new_tensor_2d(actx, GGML_TYPE_F32, 4 * C, 2);+ scale_out = ggml_new_tensor_1d(actx, GGML_TYPE_F32, C);+ ctx_in = ggml_new_tensor_2d(actx, GGML_TYPE_F32, config.context_dim, std::max<int64_t>(l_cap, 1));+ pk = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D * H, std::max<int64_t>(l_cap, 1), config.num_layers);+ pv = ggml_new_tensor_3d(actx, GGML_TYPE_F16, D * H, std::max<int64_t>(l_cap, 1), config.num_layers);+ abuf = ggml_backend_alloc_ctx_tensors(actx, runtime_backend);+ prefix_len = -1; // the cache lived in the old buffer+ return abuf != nullptr;+ }++ // ---------------------------------------------------------------- ggml graph helpers+ struct G {+ ggml_context* ctx;+ ggml_cgraph* gf;+ };+ G begin() {+ ggml_context* c = ggml_init({gbuf.size(), gbuf.data(), true});+ return {c, ggml_new_graph_custom(c, 256, false)};+ }+ static ggml_tensor* rows(ggml_context* c, ggml_tensor* t, int64_t n, int64_t first = 0) {+ return ggml_view_2d(c, t, t->ne[0], n, t->nb[1], first * t->nb[1]);+ }+ static void bind(ggml_tensor* node, ggml_tensor* storage, size_t offset = 0) {+ node->data = (char*) storage->data + offset;+ node->buffer = storage->buffer;+ }+ // compute a graph on the backend's stream (no wait). Nodes the caller did not bind get scratch space in+ // `gu` (only the small prelude / head / txt_in graphs have such nodes, and gu is free then); views get+ // their source's memory.+ void run(G& g, std::initializer_list<ggml_tensor*> outs) {+ for (auto* o : outs) ggml_build_forward_expand(g.gf, o);+ size_t off = 0;+ for (ggml_tensor* t = ggml_get_first_tensor(g.ctx); t; t = ggml_get_next_tensor(g.ctx, t)) {+ if (t->view_src != nullptr) {+ t->data = (char*) t->view_src->data + t->view_offs;+ t->buffer = t->view_src->buffer;+ } else if (t->data == nullptr) {+ bind(t, gu, off);+ off += GGML_PAD(ggml_nbytes(t), 256);+ GGML_ASSERT(off <= ggml_nbytes(gu));+ }+ }+ ggml_backend_graph_compute_async(runtime_backend, g.gf);+ ggml_free(g.ctx);+ }+ // dst[N x n] = W . src[K x n] (rows `first..`)+ void gemm(G& g, ggml_tensor* weight, ggml_tensor* src, ggml_tensor* dst, int64_t n) {+ ggml_tensor* y = ggml_mul_mat(g.ctx, weight, rows(g.ctx, src, n));+ bind(y, dst);+ ggml_build_forward_expand(g.gf, y);+ }++ // ---------------------------------------------------------------- the transformer blocks+ // rows [0, n) of x are the tokens; mrow = 0 (image) or 1 (text prefix); pe: per-token rope table;+ // attention: image -> [cached prefix K/V of the layer, these tokens' K/V]; prefix -> causal over itself, and+ // each layer's K/V goes into the prefix cache.+ bool blocks_pass(int64_t n, int mrow, ggml_tensor* pe, int64_t L) {+ void* s = qi21_stream(runtime_backend);+ const float* m = (const float*) mod->data + mrow * 4 * C;+ const float *m0 = m, *m1 = m + C, *m2 = m + 2 * C, *m3 = m + 3 * C;+ const bool prefix = mrow == 1;+ const int64_t kvt = prefix ? n : L + n; // keys per head in the work K/V+ const bool use_wmma = !prefix && wmma_attn && !exact_attn;+ // fp16 queries carry ~5e-4 relative error into logits that reach the tens here: the low half of each+ // query (q - fp16(q)) goes through a second WMMA (STRATA_QI_QSPLIT=0 drops it). It sits in the fp32-sized+ // q16 buffer right after the fp16 high half.+ const size_t qlo_off = (size_t) H * n * D * sizeof(ggml_fp16_t);+ float* X = (float*) x->data;+ float* Hh = (float*) h->data;+ int rc = qi21_res_ln_mod(s, X, nullptr, nullptr, Hh, m0, (int) n, (int) C, 1e-6f);+ for (int i = 0; i < config.num_layers && rc == 0; ++i) {+ const std::string b = "transformer_blocks." + std::to_string(i) + ".";+ {+ G g = begin();+ gemm(g, w(b + "attn.to_q.weight"), h, q, n);+ gemm(g, w(b + "attn.to_k.weight"), h, k, n);+ gemm(g, w(b + "attn.to_v.weight"), h, v, n);+ run(g, {});+ }+ const int64_t off = prefix ? 0 : L;+ rc = qi21_qkv_post(s, (const float*) q->data, (const float*) k->data, (const float*) v->data, (int) C,+ (const float*) w(b + "attn.norm_q.weight")->data,+ (const float*) w(b + "attn.norm_k.weight")->data, (const float*) pe->data, q16->data,+ 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,+ 1e-6f);+ if (rc) break;+ const size_t pbytes = (size_t) L * D * sizeof(ggml_fp16_t); // one head's prefix rows+ if (prefix) {+ // keep this layer's text K/V (head-major rows 0..n) in the prefix cache, as [H][n][D]+ for (int64_t hh = 0; hh < H && rc == 0; ++hh) {+ char* pkd = (char*) pk->data + i * pk->nb[2] + hh * n * D * sizeof(ggml_fp16_t);+ char* pvd = (char*) pv->data + i * pv->nb[2] + hh * n * D * sizeof(ggml_fp16_t);+ rc = qi21_memcpy_d2d(s, pkd, (char*) kw->data + hh * kvt * D * sizeof(ggml_fp16_t),+ n * D * sizeof(ggml_fp16_t));+ rc |= qi21_memcpy_d2d(s, pvd, (char*) vw->data + hh * kvt * D * sizeof(ggml_fp16_t),+ n * D * sizeof(ggml_fp16_t));+ }+ if (rc) break;+ rc = qi21_attn_causal(s, (const float*) q16->data, (int) n, kw->data, vw->data, (int) kvt,+ (float*) att->data, (int) H, (int) n, (int) n, 1);+ } else {+ for (int64_t hh = 0; hh < H && L > 0 && rc == 0; ++hh) {+ const char* pks = (const char*) pk->data + i * pk->nb[2] + hh * pbytes;+ const char* pvs = (const char*) pv->data + i * pv->nb[2] + hh * pbytes;+ rc = qi21_memcpy_d2d(s, (char*) kw->data + hh * kvt * D * sizeof(ggml_fp16_t), pks, pbytes);+ rc |= qi21_memcpy_d2d(s, (char*) vw->data + hh * kvt * D * sizeof(ggml_fp16_t), pvs, pbytes);+ }+ if (rc) break;+ if (exact_attn) {+ // reference: fp32 attention (fp16 K/V as every path has them), slow; STRATA_QI_EXACT_ATTN=1+ rc = qi21_attn_causal(s, (const float*) q16->data, (int) n, kw->data, vw->data, (int) kvt,+ (float*) att->data, (int) H, (int) n, (int) kvt, 0);+ } else if (use_wmma) {+ rc = qi21_attn_wmma(s, q16->data, qsplit ? (char*) q16->data + qlo_off : nullptr, (int) n,+ kw->data, vw->data, (int) kvt, (float*) att->data, (int) H, (int) n,+ (int) kvt);+ } else {+ // ggml's flash attention (what sd.cpp runs on this backend)+ G g = begin();+ ggml_tensor* qt = ggml_view_3d(g.ctx, q16, D, n, H, D * sizeof(float), n * D * sizeof(float), 0);+ ggml_tensor* kt = ggml_view_3d(g.ctx, kw, D, kvt, H, D * sizeof(ggml_fp16_t),+ kvt * D * sizeof(ggml_fp16_t), 0);+ ggml_tensor* vt = ggml_view_3d(g.ctx, vw, D, kvt, H, D * sizeof(ggml_fp16_t),+ kvt * D * sizeof(ggml_fp16_t), 0);+ ggml_tensor* o = ggml_flash_attn_ext(g.ctx, qt, kt, vt, nullptr, 1.f / sqrtf((float) D), 0, 0);+ ggml_flash_attn_ext_set_prec(o, GGML_PREC_F32);+ if (!ggml_backend_supports_op(runtime_backend, o)) {+ ggml_free(g.ctx);+ rc = 3;+ break;+ }+ bind(o, att);+ run(g, {o});+ }+ }+ if (rc) break;+ {+ G g = begin();+ gemm(g, w(b + "attn.to_out.0.weight"), att, h, n);+ run(g, {});+ }+ rc = qi21_res_ln_mod(s, X, Hh, m1, Hh, m2, (int) n, (int) C, 1e-6f);+ if (rc) break;+ {+ G g = begin();+ gemm(g, w(b + "img_mlp.gate_up.weight"), h, gu, n);+ run(g, {});+ }+ rc = qi21_swiglu(s, (const float*) gu->data, (float*) mlp->data, (int) n, (int) F);+ if (rc) break;+ {+ G g = begin();+ gemm(g, w(b + "img_mlp.out.weight"), mlp, h, n);+ run(g, {});+ }+ const bool last = i + 1 == config.num_layers;+ rc = qi21_res_ln_mod(s, X, Hh, m3, last ? nullptr : Hh, m0, (int) n, (int) C, 1e-6f);+ }+ if (rc) LOG_WARN("Qwen Image 2.1 native: a kernel failed (%d)", rc);+ return rc == 0;+ }++ // ---------------------------------------------------------------- compute+ sd::Tensor<float> compute(int n_threads, const DiffusionParams& inputs) override {+ if (disabled) return QwenImage21Runner::compute(n_threads, inputs);+ const auto& xin = tensor_or_empty(inputs.x);+ const auto& context = tensor_or_empty(inputs.context);+ const auto* extra = std::get_if<QwenImage21DiffusionExtra>(&inputs.extra);+ const bool refs = inputs.ref_latents && inputs.ref_image_params.pass_to_dit && !inputs.ref_latents->empty();+ const char* why = nullptr;+ if (xin.empty() || context.empty() || xin.dim() != 4 || xin.shape()[3] != 1 ||+ xin.shape()[2] != config.in_channels || context.shape()[0] != config.context_dim ||+ tensor_or_empty(inputs.timesteps).numel() != 1)+ why = "unexpected input shapes";+ else if (refs)+ why = "reference images";+ else if (!config.fused_mlp)+ why = "an unfused MLP";+ else if (!ggml_backend_is_cuda(runtime_backend))+ why = "not a CUDA / HIP backend";+ if (why != nullptr) {+ if (!said_why) LOG_INFO("Qwen Image 2.1 native: %s; this step runs on the stock runner", why);+ said_why = true;+ return QwenImage21Runner::compute(n_threads, inputs);+ }+ const auto t0 = std::chrono::steady_clock::now();+ if (!loaded) {+ wmma_attn = qi21_has_wmma_attn(runtime_backend) && getenv("STRATA_QI_GGML_ATTN") == nullptr;+ if (!load_weights()) {+ fail("could not load the DiT weights onto the GPU");+ return QwenImage21Runner::compute(n_threads, inputs);+ }+ loaded = true;+ }+ const int64_t Wd = xin.shape()[0], Hd = xin.shape()[1], T = Wd * Hd, Lt = context.shape()[1];+ if (!alloc_acts(T, Lt)) {+ fail("not enough GPU memory for the activations");+ return QwenImage21Runner::compute(n_threads, inputs);+ }+ // rope tables: sd.cpp's own layout and embedding for [text, image]+ std::vector<std::pair<int64_t, int64_t>> shapes{{Hd, Wd}};+ QwenImage21Layout layout;+ try {+ layout = QwenImage21Layout::build(Lt, tensor_or_empty(extra ? extra->image_slots : nullptr), shapes);+ } catch (const std::exception&) {+ return QwenImage21Runner::compute(n_threads, inputs);+ }+ if (layout.segments.size() != 2 || layout.segments[0].image_index >= 0 || layout.prefix_length != Lt) {+ if (!said_why) LOG_INFO("Qwen Image 2.1 native: images in the prompt; this step runs on the stock runner");+ said_why = true;+ return QwenImage21Runner::compute(n_threads, inputs);+ }+ Rope::Embedding emb;+ emb.ids.assign(layout.positions.begin(), layout.positions.end());+ emb.positions.token_count = emb.ids.size();+ for (auto region : layout.rope_layout.images) emb.positions.images.push_back(region);+ emb.values = Rope::embed_nd(emb.ids, 1, 10000.f, config.axes_dim, emb.layout, &emb.frequencies);+ std::vector<float> pe_all = finish_rope_pe(std::move(emb));+ const size_t per_tok = 4 * D / 2;+ if (pe_all.size() != (size_t) (Lt + T) * per_tok) {+ fail("unexpected rope table size");+ return QwenImage21Runner::compute(n_threads, inputs);+ }+ ggml_backend_tensor_set(pe_img, pe_all.data() + Lt * per_tok, 0, T * per_tok * sizeof(float));+ // timestep embedding -> modulation rows (image: t, prefix: 0) and the final scale+ const float tv[2] = {inputs.timesteps->data()[0], 0.f};+ ggml_backend_tensor_set(timein, tv, 0, sizeof(tv));+ {+ G g = begin();+ ggml_tensor* te = ggml_timestep_embedding(g.ctx, timein, 256, 10000);+ te = ggml_mul_mat(g.ctx, w("time_text_embed.timestep_embedder.linear_1.weight"), te);+ te = ggml_silu(g.ctx, te);+ te = ggml_mul_mat(g.ctx, w("time_text_embed.timestep_embedder.linear_2.weight"), te);+ te = ggml_silu(g.ctx, te);+ ggml_tensor* md = ggml_mul_mat(g.ctx, w("modulation.1.weight"), te);+ ggml_tensor* sc = ggml_mul_mat(g.ctx, w("norm_out.linear.weight"),+ ggml_view_1d(g.ctx, te, C, 0));+ bind(md, mod);+ bind(sc, scale_out);+ run(g, {md, sc});+ }+ // the text prefix: once per condition+ uint64_t key = extra != nullptr ? extra->prefix_id : 0;+ {+ uint64_t hsh = 1469598103934665603ull;+ const unsigned char* p = (const unsigned char*) context.data();+ const size_t nb = context.numel() * sizeof(float);+ for (size_t i = 0; i < nb; i += 61) hsh = (hsh ^ p[i]) * 1099511628211ull;+ key = key * 31 + hsh;+ }+ if (key != prefix_key || prefix_len != Lt) {+ ggml_backend_tensor_set(pe_txt, pe_all.data(), 0, Lt * per_tok * sizeof(float));+ ggml_backend_tensor_set(ctx_in, context.data(), 0, Lt * config.context_dim * sizeof(float));+ {+ // txt_in: zero-centered RMSNorm (weight + 1) -> in_layer -> GELU -> out_layer, into x+ G g = begin();+ ggml_tensor* t = ggml_rms_norm(g.ctx, rows(g.ctx, ctx_in, Lt), 1e-6f);+ ggml_tensor* nw = ggml_scale_bias(g.ctx, w("txt_in.text_norm.weight"), 1.f, 1.f);+ t = ggml_mul(g.ctx, t, nw);+ t = ggml_mul_mat(g.ctx, w("txt_in.in_layer.weight"), t);+ t = ggml_gelu(g.ctx, t);+ t = ggml_mul_mat(g.ctx, w("txt_in.out_layer.weight"), t);+ bind(t, x);+ run(g, {t});+ }+ if (!blocks_pass(Lt, 1, pe_txt, 0)) {+ fail("the text prefix pass failed");+ return QwenImage21Runner::compute(n_threads, inputs);+ }+ prefix_key = key;+ prefix_len = Lt;+ }+ // the image tokens: patchify (patch 1: token h*W + w, channels), img_in, the blocks, the output head+ {+ std::vector<float> tok((size_t) T * config.in_channels);+ const float* xs = xin.data();+ for (int64_t c = 0; c < config.in_channels; ++c)+ for (int64_t t = 0; t < T; ++t) tok[(size_t) t * config.in_channels + c] = xs[(size_t) c * T + t];+ ggml_backend_tensor_set(latent, tok.data(), 0, tok.size() * sizeof(float));+ G g = begin();+ gemm(g, w("img_in.weight"), latent, x, T);+ run(g, {});+ }+ if (!blocks_pass(T, 0, pe_img, Lt)) {+ fail("the image pass failed");+ return QwenImage21Runner::compute(n_threads, inputs);+ }+ {+ G g = begin();+ ggml_tensor* t = ggml_norm(g.ctx, rows(g.ctx, x, T), 1e-6f);+ t = ggml_mul(g.ctx, t, ggml_scale_bias(g.ctx, scale_out, 1.f, 1.f));+ t = ggml_mul_mat(g.ctx, w("proj_out.weight"), t);+ bind(t, outp);+ run(g, {t});+ }+ ggml_backend_synchronize(runtime_backend);+ std::vector<float> o((size_t) T * config.out_channels);+ ggml_backend_tensor_get(outp, o.data(), 0, o.size() * sizeof(float));+ sd::Tensor<float> result({Wd, Hd, config.out_channels, 1});+ float* r = result.data();+ for (int64_t c = 0; c < config.out_channels; ++c)+ for (int64_t t = 0; t < T; ++t) r[(size_t) c * T + t] = o[(size_t) t * config.out_channels + c];+ if (timing) {+ const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();+ LOG_INFO("Qwen Image 2.1 native: step %.1f ms (%lld image tokens, prefix %lld)", ms, (long long) T,+ (long long) Lt);+ }+ return restore_trailing_singleton_dims(std::move(result), xin.dim());+ }+ };++} // namespace Qwen++#endif // __SD_MODEL_DIFFUSION_QWEN_IMAGE_2_1_NATIVE_H__