okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e4309aaf3
main
1// src/image/dit/qi21_dit.cu - see include/strata/image/qi21_dit.hpp. 2// 3// One step, as the native runner (tools/image/sdcpp_native/qwen_image_2_1_native.hpp) with the D1+D2 GEMMs computes it: 4// prelude emb = sinusoid([t, 0], 256); te = silu(linear_2(silu(linear_1(emb)))); mod = modulation.1(te) (row 0 for 5// the image tokens, row 1 = t 0 for the text); scale = norm_out.linear(te row 0) 6// prefix (once per condition) x = out_layer(gelu(in_layer(RMSNorm(cond) (w + 1)))); 32 blocks over the text rows, 7// causal attention with f32 queries (attn_exact); each block's K / V (f16) kept in the prefix cache 8// image x = img_in(latent tokens); 32 blocks over the image rows, keys = [the block's cached text K / V; these 9// tokens' K / V], f16 queries (attn_fast; attn_exact where the card has no fast kernel) 10// block h = LN(x)(1 + m0); qkv = h W^T (one GEMM over q | k | v); per-head RMSNorm + RoPE; attention; 11// x += to_out(att) tanh(m1); h = LN(x)(1 + m2); gu = h Wgu^T; a = up silu(gate); x += out(a) tanh(m3) 12// head LN(x)(1 + scale) -> proj_out 13#include "strata/image/qi21_dit.hpp" 14 15#include "qi21_kernels.hpp" 16#include "strata/image/dit_gemm.hpp" 17#include "strata/image/qi21_rope.hpp" 18#include "strata/image/te_dequant.hpp" 19 20#define STRATA_GGUF_MAIN_DISABLED 1 21#include "strata/artifact/gguf_reader.hpp" 22 23#if defined(__HIP__) || defined(__HIPCC__) || defined(__HIP_PLATFORM_AMD__) 24#include "strata/hip_compat/cuda_runtime.h" 25#else 26#include <cuda_runtime.h> 27#endif 28 29#include <algorithm> 30#include <chrono> 31#include <cstdio> 32#include <cstring> 33#include <map> 34#include <memory> 35#include <set> 36#include <string> 37#include <type_traits> 38#include <vector> 39 40namespace strata::image { 41namespace { 42 43constexpr int HD = 128; 44constexpr float EPS = 1e-6f; 45const std::string PFX = "model.diffusion_model."; 46 47#define DIT_CUDA(x) \ 48 do { \ 49 cudaError_t e_ = (x); \ 50 if (e_ != cudaSuccess) return std::string("qi21_dit: ") + #x + ": " + cudaGetErrorString(e_); \ 51 } while (0) 52#define DIT_TRY(x) \ 53 do { \ 54 std::string r_ = (x); \ 55 if (!r_.empty()) return r_; \ 56 } while (0) 57#define DIT_K(x) \ 58 do { \ 59 int r_ = (x); \ 60 if (r_ != 0) return std::string("qi21_dit: kernel ") + #x + " returned " + std::to_string(r_); \ 61 } while (0) 62 63struct W2 { // a 2-D weight on the device: rows of K values, N rows, raw blocks of `type` 64 uint32_t type = 0; 65 size_t off = 0; 66 int64_t K = 0, N = 0; 67}; 68 69struct Block { 70 W2 qkv; // q | k | v rows one after the other (N = 3C) when fused, else q only 71 W2 k, v; // used when not fused 72 bool fused = false; 73 W2 out, gate_up, down; 74 size_t nq = 0, nk = 0; // float offsets of norm_q / norm_k in the norm buffer 75}; 76 77} // namespace 78 79struct Qi21Dit { 80 std::unique_ptr<strata::GgufFile> file; 81 int device = 0; 82 int C = 0, F = 0, H = 0, in_ch = 0, out_ch = 0, ctx_dim = 0, t_dim = 0, n_layer = 0; 83 bool fast_attn = false; 84 std::vector<Block> blocks; 85 W2 img_in, txt_in1, txt_in2, lin1, lin2, modw, norm_out, proj_out; 86 size_t text_norm = 0; 87 cudaStream_t stream = nullptr; 88 cudaEvent_t ev[3] = {nullptr, nullptr, nullptr}; 89 uint8_t* d_w = nullptr; 90 float* d_norm = nullptr; 91 size_t weight_bytes = 0, norm_bytes = 0; 92 double open_ms = 0; 93 std::vector<std::string> unused; 94 // work, sized for t_cap image tokens and l_cap text tokens 95 int64_t t_cap = 0, l_cap = 0; 96 float *x = nullptr, *h = nullptr, *gu = nullptr, *q16 = nullptr; 97 uint16_t *h16 = nullptr, *a16 = nullptr, *m16 = nullptr; // GEMM inputs, written f16 by the kernels before them 98 bool f16_resident = false; // weights decoded to f16 once at open (measurement) 99 double decode_ms = 0; 100 uint16_t *kw = nullptr, *vw = nullptr, *pk = nullptr, *pv = nullptr; 101 float *pe_img = nullptr, *pe_txt = nullptr, *latent = nullptr, *outp = nullptr, *ctx_in = nullptr; 102 float *tin = nullptr, *emb = nullptr, *te1 = nullptr, *te2 = nullptr, *mod = nullptr, *scale = nullptr; 103 size_t work_bytes = 0, peak_bytes = 0; 104 std::vector<void*> work; 105 // the prefix cache 106 uint64_t prefix_key = 0; 107 int64_t prefix_len = -1; 108}; 109 110namespace { 111 112std::string find2(Qi21Dit* d, const std::string& name, int64_t K, int64_t N, W2& w, size_t& off, bool align, 113 std::vector<std::pair<const strata::TensorInfo*, size_t>>& plan, std::set<std::string>& used) { 114 const strata::TensorInfo* t = d->file->find(PFX + name); 115 if (!t) return "qi21_dit: tensor " + name + " missing"; 116 if (t->shape.size() != 2 || (int64_t) t->shape[0] != K || (int64_t) t->shape[1] != N) 117 return "qi21_dit: tensor " + name + " has an unexpected shape"; 118 const size_t rb = te_row_bytes(t->type, K); 119 if (rb == 0 || !te_type_supported(t->type)) 120 return "qi21_dit: tensor " + name + " has type " + t->type_name() + ", which the DiT does not read"; 121 w = {t->type, off, K, N}; 122 plan.emplace_back(t, off); 123 used.insert(PFX + name); 124 off += rb * (size_t) N; 125 if (align) off = (off + 255) / 256 * 256; 126 return std::string(); 127} 128 129std::string find1(Qi21Dit* d, const std::string& name, int64_t n, size_t& at, std::vector<float>& host, 130 std::set<std::string>& used) { 131 const strata::TensorInfo* t = d->file->find(PFX + name); 132 if (!t) return "qi21_dit: tensor " + name + " missing"; 133 if ((int64_t) t->elements() != n) return "qi21_dit: tensor " + name + " has an unexpected size"; 134 at = host.size(); 135 host.resize(at + (size_t) n); 136 used.insert(PFX + name); 137 return te_dequant_f32_host(t->type, d->file->tensor_data(*t), n, 1, host.data() + at); 138} 139 140std::string shape_of(Qi21Dit* d, const std::string& name, int64_t& ne0, int64_t& ne1) { 141 const strata::TensorInfo* t = d->file->find(PFX + name); 142 if (!t || t->shape.size() != 2) return "qi21_dit: tensor " + name + " missing or not 2-D"; 143 ne0 = (int64_t) t->shape[0]; 144 ne1 = (int64_t) t->shape[1]; 145 return std::string(); 146} 147 148// host -> device through a pinned chunk pair, async on the stream 149std::string upload(Qi21Dit* d, uint8_t* dst, const uint8_t* src, size_t n, uint8_t* pinned[2], cudaEvent_t pin_ev[2], 150 size_t chunk, int& next) { 151 for (size_t done = 0; done < n;) { 152 const int b = next; 153 next ^= 1; 154 DIT_CUDA(cudaEventSynchronize(pin_ev[b])); 155 const size_t c = std::min(chunk, n - done); 156 std::memcpy(pinned[b], src + done, c); 157 DIT_CUDA(cudaMemcpyAsync(dst + done, pinned[b], c, cudaMemcpyHostToDevice, d->stream)); 158 DIT_CUDA(cudaEventRecord(pin_ev[b], d->stream)); 159 done += c; 160 } 161 return std::string(); 162} 163 164// QI21_DIT_F16_RESIDENT (a measurement for cards with room, not a memory plan): every 2-D weight decoded once to f16 165// into its own buffer (the same f16 values dit_gemm decodes on every call), the raw blocks freed; the GEMMs then 166// read the f16 weights in place. 167std::string to_f16_resident(Qi21Dit* d) { 168 const auto t0 = std::chrono::steady_clock::now(); 169 std::vector<W2*> ws; 170 for (Block& B : d->blocks) { 171 ws.push_back(&B.qkv); 172 if (!B.fused) { 173 ws.push_back(&B.k); 174 ws.push_back(&B.v); 175 } 176 ws.push_back(&B.out); 177 ws.push_back(&B.gate_up); 178 ws.push_back(&B.down); 179 } 180 for (W2* w : {&d->img_in, &d->txt_in1, &d->txt_in2, &d->lin1, &d->lin2, &d->modw, &d->norm_out, &d->proj_out}) 181 ws.push_back(w); 182 size_t total = 0; 183 for (const W2* w : ws) total += ((size_t) w->K * (size_t) w->N * sizeof(uint16_t) + 255) / 256 * 256; 184 uint8_t* f16 = nullptr; 185 DIT_CUDA(cudaMalloc((void**) &f16, total)); 186 size_t off = 0; 187 for (W2* w : ws) { 188 const std::string e = te_dequant_f16(w->type, d->d_w + w->off, w->K, w->N, 189 reinterpret_cast<uint16_t*>(f16 + off), d->stream); 190 if (!e.empty()) { 191 cudaFree(f16); 192 return "qi21_dit: " + e; 193 } 194 w->type = TE_F16; 195 w->off = off; 196 off += ((size_t) w->K * (size_t) w->N * sizeof(uint16_t) + 255) / 256 * 256; 197 } 198 DIT_CUDA(cudaStreamSynchronize(d->stream)); 199 DIT_CUDA(cudaFree(d->d_w)); 200 d->d_w = f16; 201 d->weight_bytes = total; 202 d->decode_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count(); 203 return std::string(); 204} 205 206std::string open_impl(Qi21Dit* d, const std::string& path, int device) { 207 const auto t0 = std::chrono::steady_clock::now(); 208 d->file = std::make_unique<strata::GgufFile>(path); 209 std::set<std::string> used; 210 int64_t a = 0, b = 0; 211 DIT_TRY(shape_of(d, "img_in.weight", a, b)); 212 d->in_ch = (int) a; 213 d->C = (int) b; 214 DIT_TRY(shape_of(d, "proj_out.weight", a, b)); 215 d->out_ch = (int) b; 216 DIT_TRY(shape_of(d, "txt_in.in_layer.weight", a, b)); 217 d->ctx_dim = (int) a; 218 DIT_TRY(shape_of(d, "time_text_embed.timestep_embedder.linear_1.weight", a, b)); 219 d->t_dim = (int) a; 220 DIT_TRY(shape_of(d, "transformer_blocks.0.img_mlp.gate_up.weight", a, b)); 221 d->F = (int) (b / 2); 222 const int C = d->C, F = d->F; 223 if (C % HD != 0 || (C / HD) % 8 != 0 || C > 8192) return "qi21_dit: unexpected model width"; 224 d->H = C / HD; 225 while (d->file->find(PFX + "transformer_blocks." + std::to_string(d->n_layer) + ".attn.to_out.0.weight")) ++d->n_layer; 226 if (d->n_layer == 0) return "qi21_dit: no transformer blocks"; 227 228 std::vector<std::pair<const strata::TensorInfo*, size_t>> plan; 229 std::vector<float> norms; 230 size_t off = 0; 231 d->blocks.resize(d->n_layer); 232 for (int i = 0; i < d->n_layer; ++i) { 233 Block& B = d->blocks[i]; 234 const std::string p = "transformer_blocks." + std::to_string(i) + "."; 235 const strata::TensorInfo* tq = d->file->find(PFX + p + "attn.to_q.weight"); 236 const strata::TensorInfo* tk = d->file->find(PFX + p + "attn.to_k.weight"); 237 const strata::TensorInfo* tv = d->file->find(PFX + p + "attn.to_v.weight"); 238 B.fused = tq && tk && tv && tq->type == tk->type && tq->type == tv->type; 239 DIT_TRY(find2(d, p + "attn.to_q.weight", C, C, B.qkv, off, !B.fused, plan, used)); 240 DIT_TRY(find2(d, p + "attn.to_k.weight", C, C, B.k, off, !B.fused, plan, used)); 241 DIT_TRY(find2(d, p + "attn.to_v.weight", C, C, B.v, off, true, plan, used)); 242 if (B.fused) B.qkv.N = 3 * C; // the three tensors' rows one after the other: one weight of 3C rows 243 DIT_TRY(find2(d, p + "attn.to_out.0.weight", C, C, B.out, off, true, plan, used)); 244 DIT_TRY(find2(d, p + "img_mlp.gate_up.weight", C, 2 * F, B.gate_up, off, true, plan, used)); 245 DIT_TRY(find2(d, p + "img_mlp.out.weight", F, C, B.down, off, true, plan, used)); 246 DIT_TRY(find1(d, p + "attn.norm_q.weight", HD, B.nq, norms, used)); 247 DIT_TRY(find1(d, p + "attn.norm_k.weight", HD, B.nk, norms, used)); 248 } 249 DIT_TRY(find2(d, "img_in.weight", d->in_ch, C, d->img_in, off, true, plan, used)); 250 DIT_TRY(find2(d, "txt_in.in_layer.weight", d->ctx_dim, C, d->txt_in1, off, true, plan, used)); 251 DIT_TRY(find2(d, "txt_in.out_layer.weight", C, C, d->txt_in2, off, true, plan, used)); 252 DIT_TRY(find2(d, "time_text_embed.timestep_embedder.linear_1.weight", d->t_dim, C, d->lin1, off, true, plan, used)); 253 DIT_TRY(find2(d, "time_text_embed.timestep_embedder.linear_2.weight", C, C, d->lin2, off, true, plan, used)); 254 DIT_TRY(find2(d, "modulation.1.weight", C, 4 * C, d->modw, off, true, plan, used)); 255 DIT_TRY(find2(d, "norm_out.linear.weight", C, C, d->norm_out, off, true, plan, used)); 256 DIT_TRY(find2(d, "proj_out.weight", C, d->out_ch, d->proj_out, off, true, plan, used)); 257 DIT_TRY(find1(d, "txt_in.text_norm.weight", d->ctx_dim, d->text_norm, norms, used)); 258 for (const auto& t : d->file->tensors()) 259 if (t.name.compare(0, PFX.size(), PFX) == 0 && !used.count(t.name)) d->unused.push_back(t.name); 260 d->weight_bytes = off; 261 d->norm_bytes = norms.size() * sizeof(float); 262 263 if (device >= 0) DIT_CUDA(cudaSetDevice(device)); 264 DIT_CUDA(cudaGetDevice(&d->device)); 265 d->fast_attn = qi21::has_fast_attn(d->device) != 0; 266 DIT_CUDA(cudaStreamCreateWithFlags(&d->stream, cudaStreamNonBlocking)); 267 for (auto& e : d->ev) DIT_CUDA(cudaEventCreate(&e)); 268 DIT_CUDA(cudaMalloc((void**) &d->d_w, d->weight_bytes)); 269 DIT_CUDA(cudaMalloc((void**) &d->d_norm, d->norm_bytes)); 270 constexpr size_t CHUNK = 32u << 20; 271 uint8_t* pinned[2] = {nullptr, nullptr}; 272 cudaEvent_t pin_ev[2] = {nullptr, nullptr}; 273 std::string err; 274 for (int i = 0; i < 2 && err.empty(); ++i) { 275 if (cudaMallocHost((void**) &pinned[i], CHUNK) != cudaSuccess) err = "qi21_dit: cudaMallocHost failed"; 276 else if (cudaEventCreateWithFlags(&pin_ev[i], cudaEventDisableTiming) != cudaSuccess) err = "qi21_dit: event"; 277 } 278 int next = 0; 279 for (const auto& [t, o] : plan) { 280 if (!err.empty()) break; 281 err = upload(d, d->d_w + o, d->file->tensor_data(*t), te_row_bytes(t->type, (int64_t) t->shape[0]) * t->shape[1], 282 pinned, pin_ev, CHUNK, next); 283 } 284 if (err.empty()) 285 err = upload(d, reinterpret_cast<uint8_t*>(d->d_norm), reinterpret_cast<const uint8_t*>(norms.data()), 286 d->norm_bytes, pinned, pin_ev, CHUNK, next); 287 if (err.empty() && cudaStreamSynchronize(d->stream) != cudaSuccess) err = "qi21_dit: upload failed"; 288 for (int i = 0; i < 2; ++i) { 289 if (pinned[i]) cudaFreeHost(pinned[i]); 290 if (pin_ev[i]) cudaEventDestroy(pin_ev[i]); 291 } 292 if (err.empty() && d->f16_resident) err = to_f16_resident(d); 293 d->open_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count(); 294 return err; 295} 296 297std::string alloc(Qi21Dit* d, int64_t T, int64_t L) { 298 if (T <= d->t_cap && L <= d->l_cap) return std::string(); 299 for (void* p : d->work) cudaFree(p); 300 d->work.clear(); 301 d->work_bytes = 0; 302 d->t_cap = std::max(T, d->t_cap); 303 d->l_cap = std::max(L, d->l_cap); 304 d->prefix_len = -1; // the cache lived in the old buffers 305 const int64_t R = std::max(d->t_cap, d->l_cap), Lc = std::max<int64_t>(d->l_cap, 1); 306 const int64_t C = d->C, F = d->F, H = d->H; 307 auto get = [&](auto*& p, size_t bytes) -> std::string { 308 bytes = (bytes + 255) / 256 * 256; 309 void* q = nullptr; 310 DIT_CUDA(cudaMalloc(&q, bytes)); 311 d->work.push_back(q); 312 d->work_bytes += bytes; 313 p = static_cast<std::remove_reference_t<decltype(p)>>(q); 314 return std::string(); 315 }; 316 const size_t f4 = sizeof(float), h2 = sizeof(uint16_t); 317 DIT_TRY(get(d->x, R * C * f4)); 318 DIT_TRY(get(d->h, R * C * f4)); 319 DIT_TRY(get(d->gu, R * std::max<int64_t>({2 * F, 3 * C, d->ctx_dim}) * f4)); 320 DIT_TRY(get(d->h16, R * C * h2)); 321 DIT_TRY(get(d->a16, R * C * h2)); 322 DIT_TRY(get(d->m16, R * F * h2)); 323 DIT_TRY(get(d->q16, H * R * HD * f4)); 324 DIT_TRY(get(d->kw, H * (d->l_cap + d->t_cap) * HD * h2)); 325 DIT_TRY(get(d->vw, H * (d->l_cap + d->t_cap) * HD * h2)); 326 DIT_TRY(get(d->pk, (size_t) d->n_layer * H * Lc * HD * h2)); 327 DIT_TRY(get(d->pv, (size_t) d->n_layer * H * Lc * HD * h2)); 328 DIT_TRY(get(d->pe_img, d->t_cap * (HD / 2) * 4 * f4)); 329 DIT_TRY(get(d->pe_txt, Lc * (HD / 2) * 4 * f4)); 330 DIT_TRY(get(d->latent, d->t_cap * d->in_ch * f4)); 331 DIT_TRY(get(d->outp, d->t_cap * d->out_ch * f4)); 332 DIT_TRY(get(d->ctx_in, Lc * d->ctx_dim * f4)); 333 DIT_TRY(get(d->tin, 2 * f4)); 334 DIT_TRY(get(d->emb, 2 * d->t_dim * f4)); 335 DIT_TRY(get(d->te1, 2 * C * f4)); 336 DIT_TRY(get(d->te2, 2 * C * f4)); 337 DIT_TRY(get(d->mod, 2 * 4 * C * f4)); 338 DIT_TRY(get(d->scale, C * f4)); 339 return std::string(); 340} 341 342const uint8_t* wp(const Qi21Dit* d, const W2& w) { return d->d_w + w.off; } 343 344// y[n][N] (stride ldy) = x[n][K] (stride ldx) . W^T 345std::string mm(Qi21Dit* d, const W2& w, const float* x, int64_t ldx, int64_t n, float* y, int64_t ldy) { 346 return dit_gemm(d->stream, w.type, wp(d, w), w.K, w.N, x, ldx, n, y, ldy); 347} 348 349// the same with f16 rows (row stride ldx elements) written by the kernel before the GEMM 350std::string mm16(Qi21Dit* d, const W2& w, const uint16_t* x16, int64_t ldx, int64_t n, float* y, int64_t ldy) { 351 return dit_gemm_x16(d->stream, w.type, wp(d, w), w.K, w.N, x16, ldx, n, y, ldy); 352} 353 354// the 32 blocks over rows [0, n) of x; prefix: the text (mod row 1, causal, K / V into the prefix cache); otherwise the 355// image tokens (mod row 0) attending [cached text K / V of the block (L rows); their own]. 356std::string blocks_pass(Qi21Dit* d, int64_t n, bool prefix, const float* pe, int64_t L) { 357 void* s = d->stream; 358 const int64_t C = d->C, F = d->F, H = d->H, D = HD; 359 const float* m = d->mod + (prefix ? 4 * C : 0); 360 const float *m0 = m, *m1 = m + C, *m2 = m + 2 * C, *m3 = m + 3 * C; 361 const int64_t kvt = prefix ? n : L + n; 362 const bool fast = !prefix && d->fast_attn; 363 float* X = d->x; 364 float* Hh = d->h; 365 const size_t hb = sizeof(uint16_t); 366 DIT_K(qi21::res_ln_mod_f16(s, X, nullptr, nullptr, d->h16, m0, (int) n, (int) C, EPS)); 367 for (int i = 0; i < d->n_layer; ++i) { 368 const Block& B = d->blocks[i]; 369 const float *qs = d->gu, *ks = d->gu + C, *vs = d->gu + 2 * C; 370 int64_t ld = 3 * C; 371 if (B.fused) { 372 DIT_TRY(mm16(d, B.qkv, d->h16, C, n, d->gu, 3 * C)); 373 } else { 374 W2 q = B.qkv; 375 q.N = C; 376 DIT_TRY(mm16(d, q, d->h16, C, n, d->gu, 3 * C)); 377 DIT_TRY(mm16(d, B.k, d->h16, C, n, d->gu + C, 3 * C)); 378 DIT_TRY(mm16(d, B.v, d->h16, C, n, d->gu + 2 * C, 3 * C)); 379 } 380 DIT_K(qi21::qkv_post(s, qs, ks, vs, (int) ld, d->d_norm + B.nq, d->d_norm + B.nk, pe, d->q16, fast ? 1 : 0, 381 (int) n, d->kw, d->vw, (int) kvt, (int) (prefix ? 0 : L), (int) n, (int) H, EPS)); 382 const size_t pbytes = (size_t) L * D * hb; // one head's prefix rows 383 uint16_t* pkl = d->pk + (size_t) i * H * std::max<int64_t>(d->l_cap, 1) * D; 384 uint16_t* pvl = d->pv + (size_t) i * H * std::max<int64_t>(d->l_cap, 1) * D; 385 if (prefix) { 386 for (int64_t hh = 0; hh < H; ++hh) { 387 DIT_CUDA(cudaMemcpyAsync(pkl + hh * n * D, d->kw + hh * kvt * D, n * D * hb, cudaMemcpyDeviceToDevice, 388 d->stream)); 389 DIT_CUDA(cudaMemcpyAsync(pvl + hh * n * D, d->vw + hh * kvt * D, n * D * hb, cudaMemcpyDeviceToDevice, 390 d->stream)); 391 } 392 DIT_K(qi21::attn_exact_f16(s, d->q16, (int) n, d->kw, d->vw, (int) kvt, d->a16, (int) H, (int) n, (int) n, 1)); 393 } else { 394 for (int64_t hh = 0; hh < H && L > 0; ++hh) { 395 DIT_CUDA(cudaMemcpyAsync(d->kw + hh * kvt * D, pkl + hh * L * D, pbytes, cudaMemcpyDeviceToDevice, 396 d->stream)); 397 DIT_CUDA(cudaMemcpyAsync(d->vw + hh * kvt * D, pvl + hh * L * D, pbytes, cudaMemcpyDeviceToDevice, 398 d->stream)); 399 } 400 if (fast) 401 DIT_K(qi21::attn_fast_f16(s, d->q16, (int) n, d->kw, d->vw, (int) kvt, d->a16, (int) H, (int) n, (int) kvt)); 402 else 403 DIT_K(qi21::attn_exact_f16(s, d->q16, (int) n, d->kw, d->vw, (int) kvt, d->a16, (int) H, (int) n, (int) kvt, 404 0)); 405 } 406 DIT_TRY(mm16(d, B.out, d->a16, C, n, Hh, C)); 407 DIT_K(qi21::res_ln_mod_f16(s, X, Hh, m1, d->h16, m2, (int) n, (int) C, EPS)); 408 DIT_TRY(mm16(d, B.gate_up, d->h16, C, n, d->gu, 2 * F)); 409 DIT_K(qi21::swiglu_f16(s, d->gu, d->m16, (int) n, (int) F)); 410 DIT_TRY(mm16(d, B.down, d->m16, F, n, Hh, C)); 411 const bool last = i + 1 == d->n_layer; 412 DIT_K(qi21::res_ln_mod_f16(s, X, Hh, m3, last ? nullptr : d->h16, m0, (int) n, (int) C, EPS)); 413 } 414 return std::string(); 415} 416 417std::string step_impl(Qi21Dit* d, const float* latent, int W, int Hd, const float* cond, int L, float t, float* vel, 418 Qi21DitStats* st) { 419 const int64_t T = (int64_t) W * Hd, C = d->C; 420 DIT_CUDA(cudaSetDevice(d->device)); 421 DIT_TRY(alloc(d, T, L)); 422 void* s = d->stream; 423 DIT_CUDA(cudaEventRecord(d->ev[0], d->stream)); 424 // rope tables (sd.cpp's layout and embedding, src/image/dit/qi21_rope.cpp: byte-identical to sd.cpp's) 425 const std::vector<float> pe = qi21_rope_table(qi21_positions(L, Hd, W)); 426 const size_t per_tok = (HD / 2) * 4; 427 if (pe.size() != (size_t) (L + T) * per_tok) return "qi21_dit: unexpected rope table size"; 428 DIT_CUDA(cudaMemcpyAsync(d->pe_img, pe.data() + (size_t) L * per_tok, T * per_tok * sizeof(float), 429 cudaMemcpyHostToDevice, d->stream)); 430 // prelude 431 const float tv[2] = {t, 0.f}; 432 DIT_CUDA(cudaMemcpyAsync(d->tin, tv, sizeof(tv), cudaMemcpyHostToDevice, d->stream)); 433 DIT_K(qi21::timestep_embedding(s, d->tin, d->emb, 2, d->t_dim, 10000.f)); 434 DIT_TRY(mm(d, d->lin1, d->emb, d->t_dim, 2, d->te1, C)); 435 DIT_K(qi21::silu(s, d->te1, 2 * C)); 436 DIT_TRY(mm(d, d->lin2, d->te1, C, 2, d->te2, C)); 437 DIT_K(qi21::silu(s, d->te2, 2 * C)); 438 DIT_TRY(mm(d, d->modw, d->te2, C, 2, d->mod, 4 * C)); 439 DIT_TRY(mm(d, d->norm_out, d->te2, C, 1, d->scale, C)); 440 // the text prefix, once per condition 441 uint64_t key = 1469598103934665603ull; 442 { 443 const unsigned char* p = reinterpret_cast<const unsigned char*>(cond); 444 const size_t nb = (size_t) L * d->ctx_dim * sizeof(float); 445 for (size_t i = 0; i < nb; ++i) key = (key ^ p[i]) * 1099511628211ull; 446 } 447 const bool run_prefix = key != d->prefix_key || d->prefix_len != L; 448 if (run_prefix) { 449 DIT_CUDA(cudaMemcpyAsync(d->pe_txt, pe.data(), (size_t) L * per_tok * sizeof(float), cudaMemcpyHostToDevice, 450 d->stream)); 451 DIT_CUDA(cudaMemcpyAsync(d->ctx_in, cond, (size_t) L * d->ctx_dim * sizeof(float), cudaMemcpyHostToDevice, 452 d->stream)); 453 DIT_K(qi21::rms_norm_w1(s, d->ctx_in, d->d_norm + d->text_norm, d->gu, L, d->ctx_dim, EPS)); 454 DIT_TRY(mm(d, d->txt_in1, d->gu, d->ctx_dim, L, d->h, C)); 455 DIT_K(qi21::gelu_tanh(s, d->h, (int64_t) L * C)); 456 DIT_TRY(mm(d, d->txt_in2, d->h, C, L, d->x, C)); 457 DIT_TRY(blocks_pass(d, L, true, d->pe_txt, 0)); 458 d->prefix_key = key; 459 d->prefix_len = L; 460 } 461 DIT_CUDA(cudaEventRecord(d->ev[1], d->stream)); 462 // the image tokens: patch 1, token h * W + w, channels 463 { 464 std::vector<float> tok((size_t) T * d->in_ch); 465 for (int64_t c = 0; c < d->in_ch; ++c) 466 for (int64_t i = 0; i < T; ++i) tok[(size_t) i * d->in_ch + c] = latent[(size_t) c * T + i]; 467 DIT_CUDA(cudaMemcpyAsync(d->latent, tok.data(), tok.size() * sizeof(float), cudaMemcpyHostToDevice, d->stream)); 468 DIT_TRY(mm(d, d->img_in, d->latent, d->in_ch, T, d->x, C)); 469 DIT_CUDA(cudaStreamSynchronize(d->stream)); // tok leaves scope 470 } 471 DIT_TRY(blocks_pass(d, T, false, d->pe_img, L)); 472 // head: LN(x) (1 + scale) -> proj_out 473 DIT_K(qi21::res_ln_mod_f16(s, d->x, nullptr, nullptr, d->h16, d->scale, (int) T, (int) C, EPS)); 474 DIT_TRY(mm16(d, d->proj_out, d->h16, C, T, d->outp, d->out_ch)); 475 DIT_CUDA(cudaEventRecord(d->ev[2], d->stream)); 476 std::vector<float> o((size_t) T * d->out_ch); 477 DIT_CUDA(cudaMemcpyAsync(o.data(), d->outp, o.size() * sizeof(float), cudaMemcpyDeviceToHost, d->stream)); 478 DIT_CUDA(cudaStreamSynchronize(d->stream)); 479 for (int64_t c = 0; c < d->out_ch; ++c) 480 for (int64_t i = 0; i < T; ++i) vel[(size_t) c * T + i] = o[(size_t) i * d->out_ch + c]; 481 const size_t total = d->weight_bytes + d->norm_bytes + d->work_bytes + dit_gemm_buffer_bytes(); 482 d->peak_bytes = std::max(d->peak_bytes, total); 483 if (st) { 484 float ms = 0, pms = 0; 485 cudaEventElapsedTime(&ms, d->ev[0], d->ev[2]); 486 cudaEventElapsedTime(&pms, d->ev[0], d->ev[1]); 487 st->step_ms = ms; 488 st->prefix_ran = run_prefix; 489 st->prefix_ms = run_prefix ? pms : 0; 490 st->weight_bytes = d->weight_bytes + d->norm_bytes; 491 st->work_bytes = d->work_bytes + dit_gemm_buffer_bytes(); 492 st->peak_bytes = d->peak_bytes; 493 } 494 return std::string(); 495} 496 497} // namespace 498 499Qi21Dit* qi21_dit_open(const std::string& gguf_path, int device, std::string* err, int flags) { 500 auto* d = new Qi21Dit(); 501 d->f16_resident = (flags & QI21_DIT_F16_RESIDENT) != 0; 502 std::string e; 503 try { 504 e = open_impl(d, gguf_path, device); 505 } catch (const std::exception& x) { 506 e = std::string("qi21_dit: ") + x.what(); 507 } 508 if (!e.empty()) { 509 if (err) *err = e; 510 qi21_dit_close(d); 511 return nullptr; 512 } 513 return d; 514} 515 516int qi21_dit_in_channels(const Qi21Dit* d) { return d->in_ch; } 517int qi21_dit_out_channels(const Qi21Dit* d) { return d->out_ch; } 518int qi21_dit_context_dim(const Qi21Dit* d) { return d->ctx_dim; } 519 520std::string qi21_dit_step(Qi21Dit* d, const float* latent, int W, int H, const float* cond, int L, float t, float* velocity, 521 Qi21DitStats* stats) { 522 if (!d || W <= 0 || H <= 0 || L <= 0) return "qi21_dit: bad arguments"; 523 return step_impl(d, latent, W, H, cond, L, t, velocity, stats); 524} 525 526std::string qi21_dit_open_report(const Qi21Dit* d) { 527 char b[512]; 528 int fused = 0; 529 for (const auto& B : d->blocks) fused += B.fused; 530 std::snprintf(b, sizeof b, 531 "%d blocks, width %d, ffn %d, heads %d, in %d, out %d, context %d; weights %.3f GB + norms %.1f KB on " 532 "device %d; q|k|v fused in %d blocks; attention %s; open %.0f ms; %zu tensors not used", 533 d->n_layer, d->C, d->F, d->H, d->in_ch, d->out_ch, d->ctx_dim, d->weight_bytes / 1e9, 534 d->norm_bytes / 1e3, d->device, fused, d->fast_attn ? "fast (mma / WMMA)" : "exact (f32)", d->open_ms, 535 d->unused.size()); 536 std::string r = b; 537 for (size_t i = 0; i < d->unused.size() && i < 8; ++i) r += (i ? ", " : ": ") + d->unused[i]; 538 if (d->f16_resident) { 539 std::snprintf(b, sizeof b, "; weights f16-resident (decoded once at open, %.0f ms)", d->decode_ms); 540 r += b; 541 } 542 return r; 543} 544 545void qi21_dit_close(Qi21Dit* d) { 546 if (!d) return; 547 for (void* p : d->work) cudaFree(p); 548 if (d->d_w) cudaFree(d->d_w); 549 if (d->d_norm) cudaFree(d->d_norm); 550 for (auto& e : d->ev) 551 if (e) cudaEventDestroy(e); 552 if (d->stream) cudaStreamDestroy(d->stream); 553 dit_gemm_release(); 554 delete d; 555} 556 557} // namespace strata::image