okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e4309aaf3
main
1"""tools/image/sdcpp_dit/apply.py - put Strata's own DiT matrix products (src/image/dit/dit_gemm.cu: our weight decoders, 2f16 activations, cuBLAS / hipBLAS GemmEx with f32 accumulation) into the native Qwen-Image-2.1 runner of a 3stable-diffusion.cpp checkout at the pinned commit. Step 4, piece D1: TEST BUILDS ONLY for now (build_variant.py 4--dit); setup does not apply it, so no user build changes. 5 6python tools/image/sdcpp_dit/apply.py third_party/stable-diffusion.cpp (after sdcpp_native/apply.py) 7 8What it does: 9* copies src/image/dit/dit_gemm.cu, src/image/te/te_dequant.cu and the headers they use into src/strata_dit/; 10* CMakeLists.txt: a static library strata_dit (CUDA or HIP language, its own flags) linked into the 11stable-diffusion library, with the cuBLAS / hipBLAS ggml links already; SD_STRATA_DIT defined; 12* the native runner (src/model/diffusion/qwen_image_2_1_native.hpp): with --model-args strata_dit_gemm=1 (and 13the native runner on), every product the runner sends through its gemm() - img_in and the four per block - runs 14on dit_gemm instead of a ggml_mul_mat graph; without the argument the runner is unchanged. On an error the 15runner goes back to ggml's product for the rest of the run (test-build log line, not user text).""" 16from __future__import annotations 17 18import shutil 19import sys 20from pathlib import Path 21 22HERE = Path (__file__ ).resolve ().parent 23REPO = HERE .parents [2 ] 24MARK = "// strata: own DiT GEMMs" 25 26FILES = [ 27 ("src/image/dit/dit_gemm.cu" ,"dit_gemm.cu" ), 28 ("src/image/te/te_dequant.cu" ,"te_dequant.cu" ), 29 ("include/strata/image/dit_gemm.hpp" ,"include/strata/image/dit_gemm.hpp" ), 30 ("include/strata/image/te_dequant.hpp" ,"include/strata/image/te_dequant.hpp" ), 31 ("include/strata/kernels/f16_bits.hpp" ,"include/strata/kernels/f16_bits.hpp" ), 32 ("include/strata/kernels/bf16_bits.hpp" ,"include/strata/kernels/bf16_bits.hpp" ), 33] 34HIP_COMPAT = "include/strata/hip_compat" 35 36NAT_INCLUDE_OLD = '#include "ggml-alloc.h"\n' 37NAT_INCLUDE_NEW = NAT_INCLUDE_OLD + "#ifdef SD_STRATA_DIT\n#include <cmath>\n#include <vector>\n#include \"strata/image/dit_gemm.hpp\" " + MARK + "\n#endif\n" 38NAT_FLAG_OLD = " bool fuse_qkv = true;\n" 39NAT_FLAG_NEW = NAT_FLAG_OLD + (" bool strata_gemm = false; " + MARK + " (--model-args strata_dit_gemm=1)\n" 40" int strata_groups = 15; // test builds, STRATA_DIT_GROUPS: 1 blocks + img_in, 2 timestep MLP +" 41" modulation + norm_out, 4 txt_in, 8 head\n" ) 42NAT_CTOR_OLD = " gbuf.resize(64 << 20);\n" 43NAT_CTOR_NEW = NAT_CTOR_OLD + ("#ifdef SD_STRATA_DIT\n" 44" strata_gemm = model_args != nullptr && std::strstr(model_args, \"strata_dit_gemm=1\") != nullptr;\n" 45" if (const char* gs = getenv(\"STRATA_DIT_GROUPS\")) strata_groups = std::atoi(gs);\n" 46"#endif\n" ) 47NAT_GEMM_OLD = """ void gemm(G& g, ggml_tensor* weight, ggml_tensor* src, ggml_tensor* dst, int64_t n) { 48ggml_tensor* y = ggml_mul_mat(g.ctx, weight, rows(g.ctx, src, n)); 49""" 50NAT_GEMM_NEW = """ void gemm(G& g, ggml_tensor* weight, ggml_tensor* src, ggml_tensor* dst, int64_t n) { 51#ifdef SD_STRATA_DIT 52if (strata_gemm && (strata_groups & 1)) { """ + MARK + """: y[n][N] packed into dst, as the ggml_mul_mat node below writes it 53const std::string e = strata::image::dit_gemm(qi21_stream(runtime_backend), (uint32_t) weight->type, 54weight->data, weight->ne[0], weight->ne[1], 55(const float*) src->data, (int64_t) (src->nb[1] / sizeof(float)), 56n, (float*) dst->data, weight->ne[1]); 57if (e.empty()) return; 58LOG_WARN("strata DiT GEMM (test build): %s; ggml's product from here on", e.c_str()); 59strata_gemm = false; 60} 61#endif 62ggml_tensor* y = ggml_mul_mat(g.ctx, weight, rows(g.ctx, src, n)); 63""" 64# D2: the prelude (timestep MLP, modulation, norm_out.linear), txt_in and the output head through dit_gemm too; the 65# element-wise steps between them stay small ggml graphs. Scratch in `gu` from float offset kscr() on (run() puts the 66# graphs' own unbound nodes at its start). 67NAT_HELPERS_OLD = " // ---------------------------------------------------------------- the transformer blocks\n" 68NAT_HELPERS_NEW = """#ifdef SD_STRATA_DIT 69""" + MARK + """: helpers for the prelude / txt_in / head 70// past what run() may give a graph's own intermediates (up to rows x C + a C-vector), 256-float aligned 71size_t kscr() const { return ((size_t) std::max(t_cap, l_cap) * C + 2 * C + 255) / 256 * 256; } 72bool sgemm(ggml_tensor* weight, const float* xin, int64_t ldx, int64_t n, float* y, int64_t ldy) { 73const std::string e = strata::image::dit_gemm(qi21_stream(runtime_backend), (uint32_t) weight->type, 74weight->data, weight->ne[0], weight->ne[1], xin, ldx, n, y, ldy); 75if (!e.empty()) LOG_WARN("strata DiT GEMM (test build): %s", e.c_str()); 76return e.empty(); 77} 78float* scr(size_t off) { return (float*) gu->data + kscr() + off; } 79ggml_tensor* sview(G& g, int64_t ne0, int64_t ne1, size_t off) { 80return ggml_view_2d(g.ctx, gu, ne0, ne1, ne0 * sizeof(float), (kscr() + off) * sizeof(float)); 81} 82#endif 83""" + NAT_HELPERS_OLD 84NAT_PRELUDE_OLD = """ ggml_backend_tensor_set(timein, tv, 0, sizeof(tv)); 85{ 86G g = begin(); 87ggml_tensor* te = ggml_timestep_embedding(g.ctx, timein, 256, 10000); 88""" 89NAT_PRELUDE_NEW = """ ggml_backend_tensor_set(timein, tv, 0, sizeof(tv)); 90#ifdef SD_STRATA_DIT 91if (strata_gemm && (strata_groups & 2)) { """ + MARK + """: timestep MLP, modulation and the final scale 92const size_t o1 = 512, o2 = o1 + 2 * C, o3 = o2 + 2 * C, o4 = o3 + 2 * C; 93{ G g = begin(); ggml_tensor* te = ggml_timestep_embedding(g.ctx, timein, 256, 10000); 94bind(te, gu, kscr() * sizeof(float)); run(g, {te}); } 95bool ok = sgemm(w("time_text_embed.timestep_embedder.linear_1.weight"), scr(0), 256, 2, scr(o1), C); 96{ G g = begin(); ggml_tensor* s1 = ggml_silu(g.ctx, sview(g, C, 2, o1)); 97bind(s1, gu, (kscr() + o2) * sizeof(float)); run(g, {s1}); } 98ok = ok && sgemm(w("time_text_embed.timestep_embedder.linear_2.weight"), scr(o2), C, 2, scr(o3), C); 99{ G g = begin(); ggml_tensor* s2 = ggml_silu(g.ctx, sview(g, C, 2, o3)); 100bind(s2, gu, (kscr() + o4) * sizeof(float)); run(g, {s2}); } 101ok = ok && sgemm(w("modulation.1.weight"), scr(o4), C, 2, (float*) mod->data, 4 * C); 102ok = ok && sgemm(w("norm_out.linear.weight"), scr(o4), C, 1, (float*) scale_out->data, C); 103if (!ok) { 104fail("the strata DiT GEMMs failed (test build)"); 105return QwenImage21Runner::compute(n_threads, inputs); 106} 107} else 108#endif 109{ 110G g = begin(); 111ggml_tensor* te = ggml_timestep_embedding(g.ctx, timein, 256, 10000); 112""" 113NAT_TXT_OLD = """ { 114// txt_in: zero-centered RMSNorm (weight + 1) -> in_layer -> GELU -> out_layer, into x 115""" 116NAT_TXT_NEW = """#ifdef SD_STRATA_DIT 117if (strata_gemm && (strata_groups & 4)) { """ + MARK + """: txt_in 118const size_t o2 = (size_t) Lt * C, o3 = 2 * (size_t) Lt * C; 119{ G g = begin(); 120ggml_tensor* t = ggml_rms_norm(g.ctx, rows(g.ctx, ctx_in, Lt), 1e-6f); 121ggml_tensor* nw = ggml_scale_bias(g.ctx, w("txt_in.text_norm.weight"), 1.f, 1.f); 122t = ggml_mul(g.ctx, t, nw); 123bind(t, gu, kscr() * sizeof(float)); run(g, {t}); } 124bool ok = sgemm(w("txt_in.in_layer.weight"), scr(0), config.context_dim, Lt, scr(o2), C); 125{ G g = begin(); ggml_tensor* s = ggml_gelu(g.ctx, sview(g, C, Lt, o2)); 126bind(s, gu, (kscr() + o3) * sizeof(float)); run(g, {s}); } 127ok = ok && sgemm(w("txt_in.out_layer.weight"), scr(o3), C, Lt, (float*) x->data, C); 128if (!ok) { 129fail("the strata DiT GEMMs failed (test build)"); 130return QwenImage21Runner::compute(n_threads, inputs); 131} 132} else 133#endif 134""" + NAT_TXT_OLD 135NAT_HEAD_OLD = """ { 136G g = begin(); 137ggml_tensor* t = ggml_norm(g.ctx, rows(g.ctx, x, T), 1e-6f); 138""" 139NAT_HEAD_NEW = """#ifdef SD_STRATA_DIT 140if (strata_gemm && (strata_groups & 8)) { """ + MARK + """: the output head 141{ G g = begin(); 142ggml_tensor* t = ggml_norm(g.ctx, rows(g.ctx, x, T), 1e-6f); 143t = ggml_mul(g.ctx, t, ggml_scale_bias(g.ctx, scale_out, 1.f, 1.f)); 144bind(t, gu, kscr() * sizeof(float)); run(g, {t}); } 145if (!sgemm(w("proj_out.weight"), scr(0), C, T, (float*) outp->data, config.out_channels)) { 146fail("the strata DiT GEMMs failed (test build)"); 147return QwenImage21Runner::compute(n_threads, inputs); 148} 149} else 150#endif 151""" + NAT_HEAD_OLD 152# Test builds only: STRATA_DIT_TRACE_DIR=<dir> writes, for one DiT call, the residual stream after each block (txt_NN.bin 153# for the text-prefix pass, img_NN.bin for the image pass; float32 rows x 4096), the prelude's outputs (mod.bin, 154# scale.bin, txtin.bin, imgin.bin), the velocity rows (out.bin), and trace.txt: per block the largest |value| of every 155# GEMM input (qkv, to_out, gate_up, out) and attention input (q, k, v). Changes no value (it only reads, after a sync). 156TRACE_HELPERS = """#ifdef SD_STRATA_DIT 157""" + MARK + """: trace (test builds; STRATA_DIT_TRACE_DIR) 158const char* trace_dir = getenv("STRATA_DIT_TRACE_DIR"); 159const int trace_block = getenv("STRATA_DIT_TRACE_BLOCK") ? std::atoi(getenv("STRATA_DIT_TRACE_BLOCK")) : -1; 160void trace_file(const std::string& name, ggml_tensor* t, size_t bytes) { 161ggml_backend_synchronize(runtime_backend); // tensor_get copies on another stream: wait for this one 162std::vector<char> buf(bytes); 163ggml_backend_tensor_get(t, buf.data(), 0, bytes); 164if (FILE* f = std::fopen((std::string(trace_dir) + "/" + name).c_str(), "wb")) { std::fwrite(buf.data(), 1, bytes, f); std::fclose(f); } 165} 166float trace_max(ggml_tensor* t, size_t count, bool half) { 167ggml_backend_synchronize(runtime_backend); 168std::vector<uint16_t> h16; 169std::vector<float> f32; 170float m = 0.f; 171if (half) { 172h16.resize(count); 173ggml_backend_tensor_get(t, h16.data(), 0, count * 2); 174for (uint16_t v : h16) { const float a = std::fabs(ggml_fp16_to_fp32(v)); if (!(a <= m)) m = a; } 175} else { 176f32.resize(count); 177ggml_backend_tensor_get(t, f32.data(), 0, count * 4); 178for (float v : f32) { const float a = std::fabs(v); if (!(a <= m)) m = a; } 179} 180return m; 181} 182void trace_line(const std::string& s) { 183if (FILE* f = std::fopen((std::string(trace_dir) + "/trace.txt").c_str(), "a")) { std::fprintf(f, "%s\\n", s.c_str()); std::fclose(f); } 184} 185#endif 186""" 187TR_QKV_OLD = """ 1e-6f); 188if (rc) break; 189const size_t pbytes = (size_t) L * D * sizeof(ggml_fp16_t); // one head's prefix rows 190""" 191TR_QKV_NEW = """ 1e-6f); 192if (rc) break; 193#ifdef SD_STRATA_DIT 194if (trace_dir && !prefix && i == trace_block) { // block detail: the qkv GEMM output, Q / K / V as attention reads them 195if (wqkv != nullptr) trace_file("blk_qkv.bin", gu, (size_t) n * 3 * C * sizeof(float)); 196trace_file("blk_q16.bin", q16, (size_t) H * n * D * (use_wmma ? 2 : 4)); 197trace_file("blk_k16.bin", kw, (size_t) H * kvt * D * 2); 198trace_file("blk_v16.bin", vw, (size_t) H * kvt * D * 2); 199} 200if (trace_dir) { """ + MARK + """: trace 201char tl[256]; 202std::snprintf(tl, sizeof tl, "%s %d qkv_in %.6g q %.6g k %.6g v %.6g", prefix ? "txt" : "img", i, 203trace_max(h, (size_t) n * C, false), trace_max(q16, (size_t) H * n * D, use_wmma), 204trace_max(kw, (size_t) H * kvt * D, true), trace_max(vw, (size_t) H * kvt * D, true)); 205trace_line(tl); 206} 207#endif 208const size_t pbytes = (size_t) L * D * sizeof(ggml_fp16_t); // one head's prefix rows 209""" 210TR_MID_OLD = """ rc = res_ln(X, Hh, m1, t1, Hh, m2); 211if (rc) break; 212""" 213TR_MID_NEW = TR_MID_OLD + """#ifdef SD_STRATA_DIT 214if (trace_dir && !prefix && i == trace_block) { // block detail: attention output, stream, LN2 output 215trace_file("blk_att.bin", att, (size_t) n * C * sizeof(float)); 216trace_file("blk_x_mid.bin", x, (size_t) n * C * sizeof(float)); 217trace_file("blk_ln2.bin", h, (size_t) n * C * sizeof(float)); 218} 219if (trace_dir) { 220char tl[160]; 221std::snprintf(tl, sizeof tl, "%s %d to_out_in %.6g gate_up_in %.6g", prefix ? "txt" : "img", i, 222trace_max(att, (size_t) n * C, false), trace_max(h, (size_t) n * C, false)); 223trace_line(tl); 224} 225#endif 226""" 227TR_SWI_OLD = """ rc = qi21_swiglu(s, (const float*) gu->data, (float*) mlp->data, (int) n, (int) F); 228if (rc) break; 229""" 230TR_SWI_NEW = TR_SWI_OLD + """#ifdef SD_STRATA_DIT 231if (trace_dir && !prefix && i == trace_block) trace_file("blk_act.bin", mlp, (size_t) n * F * sizeof(float)); 232if (trace_dir) { 233char tl[96]; 234std::snprintf(tl, sizeof tl, "%s %d out_in %.6g", prefix ? "txt" : "img", i, trace_max(mlp, (size_t) n * F, false)); 235trace_line(tl); 236} 237#endif 238""" 239TR_END_OLD = " rc = res_ln(X, Hh, m3, t3, last ? nullptr : Hh, m0);\n" 240TR_END_NEW = TR_END_OLD + """#ifdef SD_STRATA_DIT 241if (trace_dir && rc == 0) { 242char fn[32]; 243std::snprintf(fn, sizeof fn, "%s_%02d.bin", prefix ? "txt" : "img", i); 244trace_file(fn, x, (size_t) n * C * sizeof(float)); 245} 246#endif 247""" 248TR_MOD_OLD = " if (qi21_tanh(qi21_stream(runtime_backend), (const float*) mod->data, (float*) gates->data,\n" 249TR_MOD_NEW = """#ifdef SD_STRATA_DIT 250if (trace_dir) { trace_file("mod.bin", mod, 8 * C * sizeof(float)); trace_file("scale.bin", scale_out, C * sizeof(float)); } 251#endif 252""" + TR_MOD_OLD 253TR_TXT_OLD = " if (!blocks_pass(Lt, 1, pe_txt, 0)) {\n" 254TR_TXT_NEW = """#ifdef SD_STRATA_DIT 255if (trace_dir) trace_file("txtin.bin", x, (size_t) Lt * C * sizeof(float)); 256#endif 257""" + TR_TXT_OLD 258TR_IMG_OLD = " if (!blocks_pass(T, 0, pe_img, Lt)) {\n" 259TR_IMG_NEW = """#ifdef SD_STRATA_DIT 260if (trace_dir) trace_file("imgin.bin", x, (size_t) T * C * sizeof(float)); 261#endif 262""" + TR_IMG_OLD 263TR_OUT_OLD = " ggml_backend_tensor_get(outp, o.data(), 0, o.size() * sizeof(float));\n" 264TR_OUT_NEW = TR_OUT_OLD + """#ifdef SD_STRATA_DIT 265if (trace_dir) trace_file("out.bin", outp, o.size() * sizeof(float)); 266#endif 267""" 268CMAKE_OLD = "target_include_directories(${SD_LIB} PUBLIC . src include)\n" 269CMAKE_NEW = """if (SD_CUDA OR SD_HIPBLAS) # """ + MARK .lstrip ("/ " )+ """: src/strata_dit (tools/image/sdcpp_dit/apply.py) 270set(STRATA_DIT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src/strata_dit) 271set(STRATA_DIT_SRC ${STRATA_DIT_DIR}/dit_gemm.cu ${STRATA_DIT_DIR}/te_dequant.cu) 272if (SD_CUDA) 273enable_language(CUDA) 274find_package(CUDAToolkit REQUIRED) 275add_library(strata_dit STATIC ${STRATA_DIT_SRC}) 276if (NOT DEFINED CMAKE_CUDA_ARCHITECTURES) 277set_target_properties(strata_dit PROPERTIES CUDA_ARCHITECTURES native) 278endif() 279if (GGML_STATIC AND NOT WIN32) 280target_link_libraries(strata_dit PRIVATE CUDA::cudart_static CUDA::cublas_static CUDA::cublasLt_static) 281elseif (GGML_STATIC) 282target_link_libraries(strata_dit PRIVATE CUDA::cudart_static CUDA::cublas) 283else() 284target_link_libraries(strata_dit PRIVATE CUDA::cudart CUDA::cublas) 285endif() 286else() 287if (AMDGPU_TARGETS AND NOT GPU_TARGETS) 288set(GPU_TARGETS ${AMDGPU_TARGETS}) 289endif() 290if (GPU_TARGETS AND NOT CMAKE_HIP_ARCHITECTURES) 291set(CMAKE_HIP_ARCHITECTURES ${GPU_TARGETS}) 292endif() 293enable_language(HIP) 294find_package(hip REQUIRED) 295find_package(hipblas REQUIRED) 296set_source_files_properties(${STRATA_DIT_SRC} PROPERTIES LANGUAGE HIP) 297add_library(strata_dit STATIC ${STRATA_DIT_SRC}) 298target_link_libraries(strata_dit PRIVATE hip::host roc::hipblas) 299set_target_properties(strata_dit ${SD_LIB} PROPERTIES HIP_ARCHITECTURES "${CMAKE_HIP_ARCHITECTURES}") 300endif() 301target_include_directories(strata_dit PRIVATE ${STRATA_DIT_DIR} ${STRATA_DIT_DIR}/include) 302target_compile_features(strata_dit PRIVATE cxx_std_17) 303set_target_properties(strata_dit PROPERTIES POSITION_INDEPENDENT_CODE ON) 304target_link_libraries(${SD_LIB} PRIVATE strata_dit) 305target_include_directories(${SD_LIB} PRIVATE ${STRATA_DIT_DIR}/include) 306target_compile_definitions(${SD_LIB} PRIVATE SD_STRATA_DIT) 307endif() 308""" + CMAKE_OLD 309 310 311def edit (path :Path ,old :str ,new :str )-> None : 312text = path .read_text (encoding = "utf-8" ) 313if new in text : 314return 315if text .count (old )!= 1 : 316raise SystemExit (f" { path } : the expected code is not there (another stable-diffusion.cpp commit, or no native runner?)" ) 317path .write_bytes (text .replace (old ,new ).encode ("utf-8" )) 318 319 320def copy_sources (dst :Path )-> None : 321for src ,rel in FILES : 322 (dst / rel ).parent .mkdir (parents = True ,exist_ok = True ) 323shutil .copyfile (REPO / src ,dst / rel ) 324hc = dst / HIP_COMPAT 325hc .mkdir (parents = True ,exist_ok = True ) 326for f in sorted ((REPO / HIP_COMPAT ).iterdir ()): 327if f .is_file (): 328shutil .copyfile (f ,hc / f .name ) 329 330 331def apply (sd :Path )-> None : 332sd = Path (sd ) 333nat = sd / "src" / "model" / "diffusion" / "qwen_image_2_1_native.hpp" 334if not nat .is_file (): 335raise SystemExit (f" { nat } : the native runner is not applied (tools/image/sdcpp_native/apply.py first)" ) 336copy_sources (sd / "src" / "strata_dit" ) 337edit (nat ,NAT_INCLUDE_OLD ,NAT_INCLUDE_NEW ) 338edit (nat ,NAT_FLAG_OLD ,NAT_FLAG_NEW ) 339edit (nat ,NAT_CTOR_OLD ,NAT_CTOR_NEW ) 340edit (nat ,NAT_GEMM_OLD ,NAT_GEMM_NEW ) 341# helpers and trace helpers in one edit: a second apply finds the whole new text and changes nothing 342edit (nat ,NAT_HELPERS_OLD ,NAT_HELPERS_NEW .replace (NAT_HELPERS_OLD ,TRACE_HELPERS + NAT_HELPERS_OLD )) 343edit (nat ,NAT_PRELUDE_OLD ,NAT_PRELUDE_NEW ) 344edit (nat ,NAT_TXT_OLD ,NAT_TXT_NEW ) 345edit (nat ,NAT_HEAD_OLD ,NAT_HEAD_NEW ) 346for old ,new in ((TR_QKV_OLD ,TR_QKV_NEW ), (TR_MID_OLD ,TR_MID_NEW ), (TR_SWI_OLD ,TR_SWI_NEW ), (TR_END_OLD ,TR_END_NEW ), 347 (TR_MOD_OLD ,TR_MOD_NEW ), (TR_TXT_OLD ,TR_TXT_NEW ), (TR_IMG_OLD ,TR_IMG_NEW ), (TR_OUT_OLD ,TR_OUT_NEW )): 348edit (nat ,old ,new ) 349edit (sd / "CMakeLists.txt" ,CMAKE_OLD ,CMAKE_NEW ) 350 351 352if __name__ == "__main__" : 353if len (sys .argv )== 2 and not sys .argv [1 ].startswith ("-" ): 354apply (Path (sys .argv [1 ])) 355"Strata DiT GEMMs applied (native runner, --model-args strata_dit_gemm=1)" ) 356else : 357raise SystemExit (__doc__ )