mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-04 15:28:40 +00:00
image: Qwen-Image-2.1 DiT step without ggml, and the strata-dit-step test program (D4, first piece)
One DiT step (latent + text condition + timestep -> velocity) in our own code, CUDA:
- src/image/dit/qi21_dit.cu, include/strata/image/qi21_dit.hpp: the weights read with
strata/artifact/gguf_reader.hpp into one device buffer as the file's bytes (q, k, v of a
block one after the other: one GEMM), 1-D norms as f32; own buffers and stream; every
multiply through dit_gemm (D1+D2); the text prefix once per condition with its K / V kept,
as the native runner does.
- src/image/dit/qi21_kernels.cu: the native runner's kernels moved out of the sd.cpp patch
(LayerNorm + modulate + gated residual, q/k RMSNorm + RoPE + f16 K/V, SwiGLU, the causal /
exact attention, the mma.sync attention for sm_80+, the gfx11 WMMA attention), plus the
steps ggml still did: timestep sinusoid, SiLU, GELU (tanh form), txt_in's RMSNorm.
The sd.cpp patch keeps its own copy for the test builds.
- src/image/dit/qi21_dit_step_main.cpp: strata-dit-step <dit.gguf> <out> <dump dirs>
[--repeat N], on the stage-hook dumps of what sd.cpp fed its DiT.
- tools/image/gate/dit_step_check.py (+ test_dit_step_check.py, CPU): the velocity against
dit_ref's f32 result, both emulations, the D1+D2 test build, stock and native.
Not used by any build or by sd-cli; sd.cpp stays the default and the fallback. HIP is
written but not compiled (no card tonight).
Measured on the GB10 (dgxspark-20261111-0538-11fc), Q8_0, velocity rel L2 to f32:
512 p0: ours 0.00055 | float32-sum emulation 0.00052 (1.061) | exact-sum 0.00046 (1.179)
| D1+D2 test build 0.00050 | stock 0.00658 | native 0.00570 | ours vs D1+D2 0.00026
512 p5: ours 0.00058 | 0.00098 (0.594) | 0.00055 (1.061) | 0.00114 | 0.00492 | 0.00612
| ours vs D1+D2 0.00107
1024 p0: ours 0.00045 | 0.00050 (0.901) | 0.00056 (0.809) | 0.00049 | 0.00535 | 0.00518
| ours vs D1+D2 0.00023
Three runs per case (the first with the text prefix pass) byte-identical.
Step time: 512 369-391 ms (first run with the prefix 588-716 ms), 1024 1316-1326 ms
(first 1524 ms). sd-cli sampling at 1024 divided by 8 steps (host side included): native
1.54 s, D1+D2 1.57 s, stock 2.45 s.
Device memory of the DiT's own buffers: 8.12 GB at 512, 8.91 GB at 1024 (weights 7.64 GB
= the GGUF's size, work 0.48 / 1.27 GB incl. the GEMM's f16 buffers).
This commit is contained in:
1 parent
09d67a33d4
commit
1705c8b9f0
7 files changed
+1461
No files matched your search
@@ -0,0 +1,47 @@
|
||||
// include/strata/image/qi21_dit.hpp - Strata's Qwen-Image-2.1 DiT without ggml (step 4, D4): one denoising step,
|
||||
// latent + text condition + timestep -> velocity, on CUDA / HIP.
|
||||
//
|
||||
// The weights come from the DiT GGUF through our own reader (strata/artifact/gguf_reader.hpp) into one device buffer
|
||||
// as the file's bytes (Q8_0 / Q4_K / Q6_K ... blocks; q, k and v of a block laid one after the other, so one GEMM
|
||||
// reads all three); the 1-D norm weights as f32. Every multiply is dit_gemm (the weight decoded to f16, activations
|
||||
// to f16, float32 sums); the element-wise steps and the attention are src/image/dit/qi21_kernels.cu. The text prefix
|
||||
// (causal within the text, modulation row t = 0) runs once per condition and leaves each block's K / V behind, as the
|
||||
// native runner in stable-diffusion.cpp does; a step with the same condition reuses it.
|
||||
//
|
||||
// Test program only so far (strata-dit-step); nothing in a build or in sd-cli calls it.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace strata::image {
|
||||
|
||||
struct Qi21Dit;
|
||||
|
||||
struct Qi21DitStats {
|
||||
double step_ms = 0; // this call, the stream's events (prefix pass included when it ran)
|
||||
double prefix_ms = 0; // the text prefix pass when it ran in this call, else 0
|
||||
bool prefix_ran = false;
|
||||
size_t weight_bytes = 0; // weights on the device (raw blocks + f32 norms)
|
||||
size_t work_bytes = 0; // activations, K / V, the prefix cache, the GEMM's f16 buffers
|
||||
size_t peak_bytes = 0; // weight_bytes + work_bytes at their largest so far
|
||||
};
|
||||
|
||||
// device < 0: the current device. nullptr on failure (*err says why).
|
||||
Qi21Dit* qi21_dit_open(const std::string& gguf_path, int device, std::string* err);
|
||||
|
||||
int qi21_dit_in_channels(const Qi21Dit* dit);
|
||||
int qi21_dit_out_channels(const Qi21Dit* dit);
|
||||
int qi21_dit_context_dim(const Qi21Dit* dit);
|
||||
|
||||
// latent: [in_channels][H][W] f32 (sd.cpp's DiT input, x), cond: [L][context_dim] f32, t: the timestep as sd.cpp
|
||||
// passes it; velocity: [out_channels][H][W] f32. "" on success.
|
||||
std::string qi21_dit_step(Qi21Dit* dit, const float* latent, int W, int H, const float* cond, int L, float t,
|
||||
float* velocity, Qi21DitStats* stats = nullptr);
|
||||
|
||||
std::string qi21_dit_open_report(const Qi21Dit* dit);
|
||||
|
||||
void qi21_dit_close(Qi21Dit* dit);
|
||||
|
||||
} // namespace strata::image
|
||||
@@ -0,0 +1,500 @@
|
||||
// src/image/dit/qi21_dit.cu - see include/strata/image/qi21_dit.hpp.
|
||||
//
|
||||
// One step, as the native runner (tools/image/sdcpp_native/qwen_image_2_1_native.hpp) with the D1+D2 GEMMs computes it:
|
||||
// prelude emb = sinusoid([t, 0], 256); te = silu(linear_2(silu(linear_1(emb)))); mod = modulation.1(te) (row 0 for
|
||||
// the image tokens, row 1 = t 0 for the text); scale = norm_out.linear(te row 0)
|
||||
// prefix (once per condition) x = out_layer(gelu(in_layer(RMSNorm(cond) (w + 1)))); 32 blocks over the text rows,
|
||||
// causal attention with f32 queries (attn_exact); each block's K / V (f16) kept in the prefix cache
|
||||
// image x = img_in(latent tokens); 32 blocks over the image rows, keys = [the block's cached text K / V; these
|
||||
// tokens' K / V], f16 queries (attn_fast; attn_exact where the card has no fast kernel)
|
||||
// block h = LN(x)(1 + m0); qkv = h W^T (one GEMM over q | k | v); per-head RMSNorm + RoPE; attention;
|
||||
// x += to_out(att) tanh(m1); h = LN(x)(1 + m2); gu = h Wgu^T; a = up silu(gate); x += out(a) tanh(m3)
|
||||
// head LN(x)(1 + scale) -> proj_out
|
||||
#include "strata/image/qi21_dit.hpp"
|
||||
|
||||
#include "qi21_kernels.hpp"
|
||||
#include "strata/image/dit_gemm.hpp"
|
||||
#include "strata/image/qi21_rope.hpp"
|
||||
#include "strata/image/te_dequant.hpp"
|
||||
|
||||
#define STRATA_GGUF_MAIN_DISABLED 1
|
||||
#include "strata/artifact/gguf_reader.hpp"
|
||||
|
||||
#if defined(__HIP__) || defined(__HIPCC__) || defined(__HIP_PLATFORM_AMD__)
|
||||
#include "strata/hip_compat/cuda_runtime.h"
|
||||
#else
|
||||
#include <cuda_runtime.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
namespace strata::image {
|
||||
namespace {
|
||||
|
||||
constexpr int HD = 128;
|
||||
constexpr float EPS = 1e-6f;
|
||||
const std::string PFX = "model.diffusion_model.";
|
||||
|
||||
#define DIT_CUDA(x) \
|
||||
do { \
|
||||
cudaError_t e_ = (x); \
|
||||
if (e_ != cudaSuccess) return std::string("qi21_dit: ") + #x + ": " + cudaGetErrorString(e_); \
|
||||
} while (0)
|
||||
#define DIT_TRY(x) \
|
||||
do { \
|
||||
std::string r_ = (x); \
|
||||
if (!r_.empty()) return r_; \
|
||||
} while (0)
|
||||
#define DIT_K(x) \
|
||||
do { \
|
||||
int r_ = (x); \
|
||||
if (r_ != 0) return std::string("qi21_dit: kernel ") + #x + " returned " + std::to_string(r_); \
|
||||
} while (0)
|
||||
|
||||
struct W2 { // a 2-D weight on the device: rows of K values, N rows, raw blocks of `type`
|
||||
uint32_t type = 0;
|
||||
size_t off = 0;
|
||||
int64_t K = 0, N = 0;
|
||||
};
|
||||
|
||||
struct Block {
|
||||
W2 qkv; // q | k | v rows one after the other (N = 3C) when fused, else q only
|
||||
W2 k, v; // used when not fused
|
||||
bool fused = false;
|
||||
W2 out, gate_up, down;
|
||||
size_t nq = 0, nk = 0; // float offsets of norm_q / norm_k in the norm buffer
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
struct Qi21Dit {
|
||||
std::unique_ptr<strata::GgufFile> file;
|
||||
int device = 0;
|
||||
int C = 0, F = 0, H = 0, in_ch = 0, out_ch = 0, ctx_dim = 0, t_dim = 0, n_layer = 0;
|
||||
bool fast_attn = false;
|
||||
std::vector<Block> blocks;
|
||||
W2 img_in, txt_in1, txt_in2, lin1, lin2, modw, norm_out, proj_out;
|
||||
size_t text_norm = 0;
|
||||
cudaStream_t stream = nullptr;
|
||||
cudaEvent_t ev[3] = {nullptr, nullptr, nullptr};
|
||||
uint8_t* d_w = nullptr;
|
||||
float* d_norm = nullptr;
|
||||
size_t weight_bytes = 0, norm_bytes = 0;
|
||||
double open_ms = 0;
|
||||
std::vector<std::string> unused;
|
||||
// work, sized for t_cap image tokens and l_cap text tokens
|
||||
int64_t t_cap = 0, l_cap = 0;
|
||||
float *x = nullptr, *h = nullptr, *att = nullptr, *gu = nullptr, *mlp = nullptr, *q16 = nullptr;
|
||||
uint16_t *kw = nullptr, *vw = nullptr, *pk = nullptr, *pv = nullptr;
|
||||
float *pe_img = nullptr, *pe_txt = nullptr, *latent = nullptr, *outp = nullptr, *ctx_in = nullptr;
|
||||
float *tin = nullptr, *emb = nullptr, *te1 = nullptr, *te2 = nullptr, *mod = nullptr, *scale = nullptr;
|
||||
size_t work_bytes = 0, peak_bytes = 0;
|
||||
std::vector<void*> work;
|
||||
// the prefix cache
|
||||
uint64_t prefix_key = 0;
|
||||
int64_t prefix_len = -1;
|
||||
};
|
||||
|
||||
namespace {
|
||||
|
||||
std::string find2(Qi21Dit* d, const std::string& name, int64_t K, int64_t N, W2& w, size_t& off, bool align,
|
||||
std::vector<std::pair<const strata::TensorInfo*, size_t>>& plan, std::set<std::string>& used) {
|
||||
const strata::TensorInfo* t = d->file->find(PFX + name);
|
||||
if (!t) return "qi21_dit: tensor " + name + " missing";
|
||||
if (t->shape.size() != 2 || (int64_t) t->shape[0] != K || (int64_t) t->shape[1] != N)
|
||||
return "qi21_dit: tensor " + name + " has an unexpected shape";
|
||||
const size_t rb = te_row_bytes(t->type, K);
|
||||
if (rb == 0 || !te_type_supported(t->type))
|
||||
return "qi21_dit: tensor " + name + " has type " + t->type_name() + ", which the DiT does not read";
|
||||
w = {t->type, off, K, N};
|
||||
plan.emplace_back(t, off);
|
||||
used.insert(PFX + name);
|
||||
off += rb * (size_t) N;
|
||||
if (align) off = (off + 255) / 256 * 256;
|
||||
return std::string();
|
||||
}
|
||||
|
||||
std::string find1(Qi21Dit* d, const std::string& name, int64_t n, size_t& at, std::vector<float>& host,
|
||||
std::set<std::string>& used) {
|
||||
const strata::TensorInfo* t = d->file->find(PFX + name);
|
||||
if (!t) return "qi21_dit: tensor " + name + " missing";
|
||||
if ((int64_t) t->elements() != n) return "qi21_dit: tensor " + name + " has an unexpected size";
|
||||
at = host.size();
|
||||
host.resize(at + (size_t) n);
|
||||
used.insert(PFX + name);
|
||||
return te_dequant_f32_host(t->type, d->file->tensor_data(*t), n, 1, host.data() + at);
|
||||
}
|
||||
|
||||
std::string shape_of(Qi21Dit* d, const std::string& name, int64_t& ne0, int64_t& ne1) {
|
||||
const strata::TensorInfo* t = d->file->find(PFX + name);
|
||||
if (!t || t->shape.size() != 2) return "qi21_dit: tensor " + name + " missing or not 2-D";
|
||||
ne0 = (int64_t) t->shape[0];
|
||||
ne1 = (int64_t) t->shape[1];
|
||||
return std::string();
|
||||
}
|
||||
|
||||
// host -> device through a pinned chunk pair, async on the stream
|
||||
std::string upload(Qi21Dit* d, uint8_t* dst, const uint8_t* src, size_t n, uint8_t* pinned[2], cudaEvent_t pin_ev[2],
|
||||
size_t chunk, int& next) {
|
||||
for (size_t done = 0; done < n;) {
|
||||
const int b = next;
|
||||
next ^= 1;
|
||||
DIT_CUDA(cudaEventSynchronize(pin_ev[b]));
|
||||
const size_t c = std::min(chunk, n - done);
|
||||
std::memcpy(pinned[b], src + done, c);
|
||||
DIT_CUDA(cudaMemcpyAsync(dst + done, pinned[b], c, cudaMemcpyHostToDevice, d->stream));
|
||||
DIT_CUDA(cudaEventRecord(pin_ev[b], d->stream));
|
||||
done += c;
|
||||
}
|
||||
return std::string();
|
||||
}
|
||||
|
||||
std::string open_impl(Qi21Dit* d, const std::string& path, int device) {
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
d->file = std::make_unique<strata::GgufFile>(path);
|
||||
std::set<std::string> used;
|
||||
int64_t a = 0, b = 0;
|
||||
DIT_TRY(shape_of(d, "img_in.weight", a, b));
|
||||
d->in_ch = (int) a;
|
||||
d->C = (int) b;
|
||||
DIT_TRY(shape_of(d, "proj_out.weight", a, b));
|
||||
d->out_ch = (int) b;
|
||||
DIT_TRY(shape_of(d, "txt_in.in_layer.weight", a, b));
|
||||
d->ctx_dim = (int) a;
|
||||
DIT_TRY(shape_of(d, "time_text_embed.timestep_embedder.linear_1.weight", a, b));
|
||||
d->t_dim = (int) a;
|
||||
DIT_TRY(shape_of(d, "transformer_blocks.0.img_mlp.gate_up.weight", a, b));
|
||||
d->F = (int) (b / 2);
|
||||
const int C = d->C, F = d->F;
|
||||
if (C % HD != 0 || (C / HD) % 8 != 0 || C > 8192) return "qi21_dit: unexpected model width";
|
||||
d->H = C / HD;
|
||||
while (d->file->find(PFX + "transformer_blocks." + std::to_string(d->n_layer) + ".attn.to_out.0.weight")) ++d->n_layer;
|
||||
if (d->n_layer == 0) return "qi21_dit: no transformer blocks";
|
||||
|
||||
std::vector<std::pair<const strata::TensorInfo*, size_t>> plan;
|
||||
std::vector<float> norms;
|
||||
size_t off = 0;
|
||||
d->blocks.resize(d->n_layer);
|
||||
for (int i = 0; i < d->n_layer; ++i) {
|
||||
Block& B = d->blocks[i];
|
||||
const std::string p = "transformer_blocks." + std::to_string(i) + ".";
|
||||
const strata::TensorInfo* tq = d->file->find(PFX + p + "attn.to_q.weight");
|
||||
const strata::TensorInfo* tk = d->file->find(PFX + p + "attn.to_k.weight");
|
||||
const strata::TensorInfo* tv = d->file->find(PFX + p + "attn.to_v.weight");
|
||||
B.fused = tq && tk && tv && tq->type == tk->type && tq->type == tv->type;
|
||||
DIT_TRY(find2(d, p + "attn.to_q.weight", C, C, B.qkv, off, !B.fused, plan, used));
|
||||
DIT_TRY(find2(d, p + "attn.to_k.weight", C, C, B.k, off, !B.fused, plan, used));
|
||||
DIT_TRY(find2(d, p + "attn.to_v.weight", C, C, B.v, off, true, plan, used));
|
||||
if (B.fused) B.qkv.N = 3 * C; // the three tensors' rows one after the other: one weight of 3C rows
|
||||
DIT_TRY(find2(d, p + "attn.to_out.0.weight", C, C, B.out, off, true, plan, used));
|
||||
DIT_TRY(find2(d, p + "img_mlp.gate_up.weight", C, 2 * F, B.gate_up, off, true, plan, used));
|
||||
DIT_TRY(find2(d, p + "img_mlp.out.weight", F, C, B.down, off, true, plan, used));
|
||||
DIT_TRY(find1(d, p + "attn.norm_q.weight", HD, B.nq, norms, used));
|
||||
DIT_TRY(find1(d, p + "attn.norm_k.weight", HD, B.nk, norms, used));
|
||||
}
|
||||
DIT_TRY(find2(d, "img_in.weight", d->in_ch, C, d->img_in, off, true, plan, used));
|
||||
DIT_TRY(find2(d, "txt_in.in_layer.weight", d->ctx_dim, C, d->txt_in1, off, true, plan, used));
|
||||
DIT_TRY(find2(d, "txt_in.out_layer.weight", C, C, d->txt_in2, off, true, plan, used));
|
||||
DIT_TRY(find2(d, "time_text_embed.timestep_embedder.linear_1.weight", d->t_dim, C, d->lin1, off, true, plan, used));
|
||||
DIT_TRY(find2(d, "time_text_embed.timestep_embedder.linear_2.weight", C, C, d->lin2, off, true, plan, used));
|
||||
DIT_TRY(find2(d, "modulation.1.weight", C, 4 * C, d->modw, off, true, plan, used));
|
||||
DIT_TRY(find2(d, "norm_out.linear.weight", C, C, d->norm_out, off, true, plan, used));
|
||||
DIT_TRY(find2(d, "proj_out.weight", C, d->out_ch, d->proj_out, off, true, plan, used));
|
||||
DIT_TRY(find1(d, "txt_in.text_norm.weight", d->ctx_dim, d->text_norm, norms, used));
|
||||
for (const auto& t : d->file->tensors())
|
||||
if (t.name.compare(0, PFX.size(), PFX) == 0 && !used.count(t.name)) d->unused.push_back(t.name);
|
||||
d->weight_bytes = off;
|
||||
d->norm_bytes = norms.size() * sizeof(float);
|
||||
|
||||
if (device >= 0) DIT_CUDA(cudaSetDevice(device));
|
||||
DIT_CUDA(cudaGetDevice(&d->device));
|
||||
d->fast_attn = qi21::has_fast_attn(d->device) != 0;
|
||||
DIT_CUDA(cudaStreamCreateWithFlags(&d->stream, cudaStreamNonBlocking));
|
||||
for (auto& e : d->ev) DIT_CUDA(cudaEventCreate(&e));
|
||||
DIT_CUDA(cudaMalloc((void**) &d->d_w, d->weight_bytes));
|
||||
DIT_CUDA(cudaMalloc((void**) &d->d_norm, d->norm_bytes));
|
||||
constexpr size_t CHUNK = 32u << 20;
|
||||
uint8_t* pinned[2] = {nullptr, nullptr};
|
||||
cudaEvent_t pin_ev[2] = {nullptr, nullptr};
|
||||
std::string err;
|
||||
for (int i = 0; i < 2 && err.empty(); ++i) {
|
||||
if (cudaMallocHost((void**) &pinned[i], CHUNK) != cudaSuccess) err = "qi21_dit: cudaMallocHost failed";
|
||||
else if (cudaEventCreateWithFlags(&pin_ev[i], cudaEventDisableTiming) != cudaSuccess) err = "qi21_dit: event";
|
||||
}
|
||||
int next = 0;
|
||||
for (const auto& [t, o] : plan) {
|
||||
if (!err.empty()) break;
|
||||
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],
|
||||
pinned, pin_ev, CHUNK, next);
|
||||
}
|
||||
if (err.empty())
|
||||
err = upload(d, reinterpret_cast<uint8_t*>(d->d_norm), reinterpret_cast<const uint8_t*>(norms.data()),
|
||||
d->norm_bytes, pinned, pin_ev, CHUNK, next);
|
||||
if (err.empty() && cudaStreamSynchronize(d->stream) != cudaSuccess) err = "qi21_dit: upload failed";
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
if (pinned[i]) cudaFreeHost(pinned[i]);
|
||||
if (pin_ev[i]) cudaEventDestroy(pin_ev[i]);
|
||||
}
|
||||
d->open_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
|
||||
return err;
|
||||
}
|
||||
|
||||
std::string alloc(Qi21Dit* d, int64_t T, int64_t L) {
|
||||
if (T <= d->t_cap && L <= d->l_cap) return std::string();
|
||||
for (void* p : d->work) cudaFree(p);
|
||||
d->work.clear();
|
||||
d->work_bytes = 0;
|
||||
d->t_cap = std::max(T, d->t_cap);
|
||||
d->l_cap = std::max(L, d->l_cap);
|
||||
d->prefix_len = -1; // the cache lived in the old buffers
|
||||
const int64_t R = std::max(d->t_cap, d->l_cap), Lc = std::max<int64_t>(d->l_cap, 1);
|
||||
const int64_t C = d->C, F = d->F, H = d->H;
|
||||
auto get = [&](auto*& p, size_t bytes) -> std::string {
|
||||
bytes = (bytes + 255) / 256 * 256;
|
||||
void* q = nullptr;
|
||||
DIT_CUDA(cudaMalloc(&q, bytes));
|
||||
d->work.push_back(q);
|
||||
d->work_bytes += bytes;
|
||||
p = static_cast<std::remove_reference_t<decltype(p)>>(q);
|
||||
return std::string();
|
||||
};
|
||||
const size_t f4 = sizeof(float), h2 = sizeof(uint16_t);
|
||||
DIT_TRY(get(d->x, R * C * f4));
|
||||
DIT_TRY(get(d->h, R * C * f4));
|
||||
DIT_TRY(get(d->att, R * C * f4));
|
||||
DIT_TRY(get(d->gu, R * std::max<int64_t>({2 * F, 3 * C, d->ctx_dim}) * f4));
|
||||
DIT_TRY(get(d->mlp, R * F * f4));
|
||||
DIT_TRY(get(d->q16, H * R * HD * f4));
|
||||
DIT_TRY(get(d->kw, H * (d->l_cap + d->t_cap) * HD * h2));
|
||||
DIT_TRY(get(d->vw, H * (d->l_cap + d->t_cap) * HD * h2));
|
||||
DIT_TRY(get(d->pk, (size_t) d->n_layer * H * Lc * HD * h2));
|
||||
DIT_TRY(get(d->pv, (size_t) d->n_layer * H * Lc * HD * h2));
|
||||
DIT_TRY(get(d->pe_img, d->t_cap * (HD / 2) * 4 * f4));
|
||||
DIT_TRY(get(d->pe_txt, Lc * (HD / 2) * 4 * f4));
|
||||
DIT_TRY(get(d->latent, d->t_cap * d->in_ch * f4));
|
||||
DIT_TRY(get(d->outp, d->t_cap * d->out_ch * f4));
|
||||
DIT_TRY(get(d->ctx_in, Lc * d->ctx_dim * f4));
|
||||
DIT_TRY(get(d->tin, 2 * f4));
|
||||
DIT_TRY(get(d->emb, 2 * d->t_dim * f4));
|
||||
DIT_TRY(get(d->te1, 2 * C * f4));
|
||||
DIT_TRY(get(d->te2, 2 * C * f4));
|
||||
DIT_TRY(get(d->mod, 2 * 4 * C * f4));
|
||||
DIT_TRY(get(d->scale, C * f4));
|
||||
return std::string();
|
||||
}
|
||||
|
||||
const uint8_t* wp(const Qi21Dit* d, const W2& w) { return d->d_w + w.off; }
|
||||
|
||||
// y[n][N] (stride ldy) = x[n][K] (stride ldx) . W^T
|
||||
std::string mm(Qi21Dit* d, const W2& w, const float* x, int64_t ldx, int64_t n, float* y, int64_t ldy) {
|
||||
return dit_gemm(d->stream, w.type, wp(d, w), w.K, w.N, x, ldx, n, y, ldy);
|
||||
}
|
||||
|
||||
// the 32 blocks over rows [0, n) of x; prefix: the text (mod row 1, causal, K / V into the prefix cache); otherwise the
|
||||
// image tokens (mod row 0) attending [cached text K / V of the block (L rows); their own].
|
||||
std::string blocks_pass(Qi21Dit* d, int64_t n, bool prefix, const float* pe, int64_t L) {
|
||||
void* s = d->stream;
|
||||
const int64_t C = d->C, F = d->F, H = d->H, D = HD;
|
||||
const float* m = d->mod + (prefix ? 4 * C : 0);
|
||||
const float *m0 = m, *m1 = m + C, *m2 = m + 2 * C, *m3 = m + 3 * C;
|
||||
const int64_t kvt = prefix ? n : L + n;
|
||||
const bool fast = !prefix && d->fast_attn;
|
||||
float* X = d->x;
|
||||
float* Hh = d->h;
|
||||
const size_t hb = sizeof(uint16_t);
|
||||
DIT_K(qi21::res_ln_mod(s, X, nullptr, nullptr, Hh, m0, (int) n, (int) C, EPS));
|
||||
for (int i = 0; i < d->n_layer; ++i) {
|
||||
const Block& B = d->blocks[i];
|
||||
const float *qs = d->gu, *ks = d->gu + C, *vs = d->gu + 2 * C;
|
||||
int64_t ld = 3 * C;
|
||||
if (B.fused) {
|
||||
DIT_TRY(mm(d, B.qkv, Hh, C, n, d->gu, 3 * C));
|
||||
} else {
|
||||
W2 q = B.qkv;
|
||||
q.N = C;
|
||||
DIT_TRY(mm(d, q, Hh, C, n, d->gu, 3 * C));
|
||||
DIT_TRY(mm(d, B.k, Hh, C, n, d->gu + C, 3 * C));
|
||||
DIT_TRY(mm(d, B.v, Hh, C, n, d->gu + 2 * C, 3 * C));
|
||||
}
|
||||
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,
|
||||
(int) n, d->kw, d->vw, (int) kvt, (int) (prefix ? 0 : L), (int) n, (int) H, EPS));
|
||||
const size_t pbytes = (size_t) L * D * hb; // one head's prefix rows
|
||||
uint16_t* pkl = d->pk + (size_t) i * H * std::max<int64_t>(d->l_cap, 1) * D;
|
||||
uint16_t* pvl = d->pv + (size_t) i * H * std::max<int64_t>(d->l_cap, 1) * D;
|
||||
if (prefix) {
|
||||
for (int64_t hh = 0; hh < H; ++hh) {
|
||||
DIT_CUDA(cudaMemcpyAsync(pkl + hh * n * D, d->kw + hh * kvt * D, n * D * hb, cudaMemcpyDeviceToDevice,
|
||||
d->stream));
|
||||
DIT_CUDA(cudaMemcpyAsync(pvl + hh * n * D, d->vw + hh * kvt * D, n * D * hb, cudaMemcpyDeviceToDevice,
|
||||
d->stream));
|
||||
}
|
||||
DIT_K(qi21::attn_exact(s, d->q16, (int) n, d->kw, d->vw, (int) kvt, d->att, (int) H, (int) n, (int) n, 1));
|
||||
} else {
|
||||
for (int64_t hh = 0; hh < H && L > 0; ++hh) {
|
||||
DIT_CUDA(cudaMemcpyAsync(d->kw + hh * kvt * D, pkl + hh * L * D, pbytes, cudaMemcpyDeviceToDevice,
|
||||
d->stream));
|
||||
DIT_CUDA(cudaMemcpyAsync(d->vw + hh * kvt * D, pvl + hh * L * D, pbytes, cudaMemcpyDeviceToDevice,
|
||||
d->stream));
|
||||
}
|
||||
if (fast)
|
||||
DIT_K(qi21::attn_fast(s, d->q16, (int) n, d->kw, d->vw, (int) kvt, d->att, (int) H, (int) n, (int) kvt));
|
||||
else
|
||||
DIT_K(qi21::attn_exact(s, d->q16, (int) n, d->kw, d->vw, (int) kvt, d->att, (int) H, (int) n, (int) kvt,
|
||||
0));
|
||||
}
|
||||
DIT_TRY(mm(d, B.out, d->att, C, n, Hh, C));
|
||||
DIT_K(qi21::res_ln_mod(s, X, Hh, m1, Hh, m2, (int) n, (int) C, EPS));
|
||||
DIT_TRY(mm(d, B.gate_up, Hh, C, n, d->gu, 2 * F));
|
||||
DIT_K(qi21::swiglu(s, d->gu, d->mlp, (int) n, (int) F));
|
||||
DIT_TRY(mm(d, B.down, d->mlp, F, n, Hh, C));
|
||||
const bool last = i + 1 == d->n_layer;
|
||||
DIT_K(qi21::res_ln_mod(s, X, Hh, m3, last ? nullptr : Hh, m0, (int) n, (int) C, EPS));
|
||||
}
|
||||
return std::string();
|
||||
}
|
||||
|
||||
std::string step_impl(Qi21Dit* d, const float* latent, int W, int Hd, const float* cond, int L, float t, float* vel,
|
||||
Qi21DitStats* st) {
|
||||
const int64_t T = (int64_t) W * Hd, C = d->C;
|
||||
DIT_CUDA(cudaSetDevice(d->device));
|
||||
DIT_TRY(alloc(d, T, L));
|
||||
void* s = d->stream;
|
||||
DIT_CUDA(cudaEventRecord(d->ev[0], d->stream));
|
||||
// rope tables (sd.cpp's layout and embedding, src/image/dit/qi21_rope.cpp: byte-identical to sd.cpp's)
|
||||
const std::vector<float> pe = qi21_rope_table(qi21_positions(L, Hd, W));
|
||||
const size_t per_tok = (HD / 2) * 4;
|
||||
if (pe.size() != (size_t) (L + T) * per_tok) return "qi21_dit: unexpected rope table size";
|
||||
DIT_CUDA(cudaMemcpyAsync(d->pe_img, pe.data() + (size_t) L * per_tok, T * per_tok * sizeof(float),
|
||||
cudaMemcpyHostToDevice, d->stream));
|
||||
// prelude
|
||||
const float tv[2] = {t, 0.f};
|
||||
DIT_CUDA(cudaMemcpyAsync(d->tin, tv, sizeof(tv), cudaMemcpyHostToDevice, d->stream));
|
||||
DIT_K(qi21::timestep_embedding(s, d->tin, d->emb, 2, d->t_dim, 10000.f));
|
||||
DIT_TRY(mm(d, d->lin1, d->emb, d->t_dim, 2, d->te1, C));
|
||||
DIT_K(qi21::silu(s, d->te1, 2 * C));
|
||||
DIT_TRY(mm(d, d->lin2, d->te1, C, 2, d->te2, C));
|
||||
DIT_K(qi21::silu(s, d->te2, 2 * C));
|
||||
DIT_TRY(mm(d, d->modw, d->te2, C, 2, d->mod, 4 * C));
|
||||
DIT_TRY(mm(d, d->norm_out, d->te2, C, 1, d->scale, C));
|
||||
// the text prefix, once per condition
|
||||
uint64_t key = 1469598103934665603ull;
|
||||
{
|
||||
const unsigned char* p = reinterpret_cast<const unsigned char*>(cond);
|
||||
const size_t nb = (size_t) L * d->ctx_dim * sizeof(float);
|
||||
for (size_t i = 0; i < nb; ++i) key = (key ^ p[i]) * 1099511628211ull;
|
||||
}
|
||||
const bool run_prefix = key != d->prefix_key || d->prefix_len != L;
|
||||
if (run_prefix) {
|
||||
DIT_CUDA(cudaMemcpyAsync(d->pe_txt, pe.data(), (size_t) L * per_tok * sizeof(float), cudaMemcpyHostToDevice,
|
||||
d->stream));
|
||||
DIT_CUDA(cudaMemcpyAsync(d->ctx_in, cond, (size_t) L * d->ctx_dim * sizeof(float), cudaMemcpyHostToDevice,
|
||||
d->stream));
|
||||
DIT_K(qi21::rms_norm_w1(s, d->ctx_in, d->d_norm + d->text_norm, d->gu, L, d->ctx_dim, EPS));
|
||||
DIT_TRY(mm(d, d->txt_in1, d->gu, d->ctx_dim, L, d->att, C));
|
||||
DIT_K(qi21::gelu_tanh(s, d->att, (int64_t) L * C));
|
||||
DIT_TRY(mm(d, d->txt_in2, d->att, C, L, d->x, C));
|
||||
DIT_TRY(blocks_pass(d, L, true, d->pe_txt, 0));
|
||||
d->prefix_key = key;
|
||||
d->prefix_len = L;
|
||||
}
|
||||
DIT_CUDA(cudaEventRecord(d->ev[1], d->stream));
|
||||
// the image tokens: patch 1, token h * W + w, channels
|
||||
{
|
||||
std::vector<float> tok((size_t) T * d->in_ch);
|
||||
for (int64_t c = 0; c < d->in_ch; ++c)
|
||||
for (int64_t i = 0; i < T; ++i) tok[(size_t) i * d->in_ch + c] = latent[(size_t) c * T + i];
|
||||
DIT_CUDA(cudaMemcpyAsync(d->latent, tok.data(), tok.size() * sizeof(float), cudaMemcpyHostToDevice, d->stream));
|
||||
DIT_TRY(mm(d, d->img_in, d->latent, d->in_ch, T, d->x, C));
|
||||
DIT_CUDA(cudaStreamSynchronize(d->stream)); // tok leaves scope
|
||||
}
|
||||
DIT_TRY(blocks_pass(d, T, false, d->pe_img, L));
|
||||
// head: LN(x) (1 + scale) -> proj_out
|
||||
DIT_K(qi21::res_ln_mod(s, d->x, nullptr, nullptr, d->h, d->scale, (int) T, (int) C, EPS));
|
||||
DIT_TRY(mm(d, d->proj_out, d->h, C, T, d->outp, d->out_ch));
|
||||
DIT_CUDA(cudaEventRecord(d->ev[2], d->stream));
|
||||
std::vector<float> o((size_t) T * d->out_ch);
|
||||
DIT_CUDA(cudaMemcpyAsync(o.data(), d->outp, o.size() * sizeof(float), cudaMemcpyDeviceToHost, d->stream));
|
||||
DIT_CUDA(cudaStreamSynchronize(d->stream));
|
||||
for (int64_t c = 0; c < d->out_ch; ++c)
|
||||
for (int64_t i = 0; i < T; ++i) vel[(size_t) c * T + i] = o[(size_t) i * d->out_ch + c];
|
||||
const size_t total = d->weight_bytes + d->norm_bytes + d->work_bytes + dit_gemm_buffer_bytes();
|
||||
d->peak_bytes = std::max(d->peak_bytes, total);
|
||||
if (st) {
|
||||
float ms = 0, pms = 0;
|
||||
cudaEventElapsedTime(&ms, d->ev[0], d->ev[2]);
|
||||
cudaEventElapsedTime(&pms, d->ev[0], d->ev[1]);
|
||||
st->step_ms = ms;
|
||||
st->prefix_ran = run_prefix;
|
||||
st->prefix_ms = run_prefix ? pms : 0;
|
||||
st->weight_bytes = d->weight_bytes + d->norm_bytes;
|
||||
st->work_bytes = d->work_bytes + dit_gemm_buffer_bytes();
|
||||
st->peak_bytes = d->peak_bytes;
|
||||
}
|
||||
return std::string();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Qi21Dit* qi21_dit_open(const std::string& gguf_path, int device, std::string* err) {
|
||||
auto* d = new Qi21Dit();
|
||||
std::string e;
|
||||
try {
|
||||
e = open_impl(d, gguf_path, device);
|
||||
} catch (const std::exception& x) {
|
||||
e = std::string("qi21_dit: ") + x.what();
|
||||
}
|
||||
if (!e.empty()) {
|
||||
if (err) *err = e;
|
||||
qi21_dit_close(d);
|
||||
return nullptr;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
int qi21_dit_in_channels(const Qi21Dit* d) { return d->in_ch; }
|
||||
int qi21_dit_out_channels(const Qi21Dit* d) { return d->out_ch; }
|
||||
int qi21_dit_context_dim(const Qi21Dit* d) { return d->ctx_dim; }
|
||||
|
||||
std::string qi21_dit_step(Qi21Dit* d, const float* latent, int W, int H, const float* cond, int L, float t, float* velocity,
|
||||
Qi21DitStats* stats) {
|
||||
if (!d || W <= 0 || H <= 0 || L <= 0) return "qi21_dit: bad arguments";
|
||||
return step_impl(d, latent, W, H, cond, L, t, velocity, stats);
|
||||
}
|
||||
|
||||
std::string qi21_dit_open_report(const Qi21Dit* d) {
|
||||
char b[512];
|
||||
int fused = 0;
|
||||
for (const auto& B : d->blocks) fused += B.fused;
|
||||
std::snprintf(b, sizeof b,
|
||||
"%d blocks, width %d, ffn %d, heads %d, in %d, out %d, context %d; weights %.3f GB + norms %.1f KB on "
|
||||
"device %d; q|k|v fused in %d blocks; attention %s; open %.0f ms; %zu tensors not used",
|
||||
d->n_layer, d->C, d->F, d->H, d->in_ch, d->out_ch, d->ctx_dim, d->weight_bytes / 1e9,
|
||||
d->norm_bytes / 1e3, d->device, fused, d->fast_attn ? "fast (mma / WMMA)" : "exact (f32)", d->open_ms,
|
||||
d->unused.size());
|
||||
std::string r = b;
|
||||
for (size_t i = 0; i < d->unused.size() && i < 8; ++i) r += (i ? ", " : ": ") + d->unused[i];
|
||||
return r;
|
||||
}
|
||||
|
||||
void qi21_dit_close(Qi21Dit* d) {
|
||||
if (!d) return;
|
||||
for (void* p : d->work) cudaFree(p);
|
||||
if (d->d_w) cudaFree(d->d_w);
|
||||
if (d->d_norm) cudaFree(d->d_norm);
|
||||
for (auto& e : d->ev)
|
||||
if (e) cudaEventDestroy(e);
|
||||
if (d->stream) cudaStreamDestroy(d->stream);
|
||||
dit_gemm_release();
|
||||
delete d;
|
||||
}
|
||||
|
||||
} // namespace strata::image
|
||||
@@ -0,0 +1,120 @@
|
||||
// src/image/dit/qi21_dit_step_main.cpp - test program strata-dit-step (not shipped): one Qwen-Image-2.1 DiT step in
|
||||
// Strata's own code (include/strata/image/qi21_dit.hpp) on the inputs stable-diffusion.cpp gave its DiT.
|
||||
//
|
||||
// strata-dit-step <dit.gguf> <out dir> <dump dir> [<dump dir> ...] [--repeat N] [--call K]
|
||||
//
|
||||
// Each dump dir holds the stage-hook dumps of one picture (tools/image/gate/stage_hooks.py): dit_x_<K> (the latent,
|
||||
// shape "W H C 1"), dit_t_<K> (the timestep) and cond (shape "context L"). Writes <out dir>/<dump parent name>/<dump name>/vel.bin, the
|
||||
// velocity as sd.cpp's vel_<K>.bin ([C][H][W] float32), and vel.shape. With --repeat N the step runs N times on the
|
||||
// same inputs (the first runs the text prefix, the rest reuse it, like sampling steps 2..8) and every run must give
|
||||
// the same bytes. Prints the open report, per run the step and prefix time, the memory peak of the DiT's own buffers
|
||||
// against the GGUF size, and DIT-STEP PASS / FAIL (FAIL = an error or runs that differ).
|
||||
#include "strata/image/qi21_dit.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
using namespace strata::image;
|
||||
|
||||
namespace {
|
||||
|
||||
bool read_f32(const fs::path& p, std::vector<float>& v) {
|
||||
std::ifstream f(p, std::ios::binary);
|
||||
if (!f) return false;
|
||||
std::vector<char> raw((std::istreambuf_iterator<char>(f)), {});
|
||||
v.resize(raw.size() / 4);
|
||||
std::memcpy(v.data(), raw.data(), v.size() * 4);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<long long> read_shape(const fs::path& p) {
|
||||
std::vector<long long> s;
|
||||
std::ifstream f(p);
|
||||
long long x;
|
||||
while (f >> x) s.push_back(x);
|
||||
return s;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc < 4) {
|
||||
std::fprintf(stderr, "usage: strata-dit-step <dit.gguf> <out dir> <dump dir> [...] [--repeat N] [--call K]\n");
|
||||
return 2;
|
||||
}
|
||||
int repeat = 1, call = 0;
|
||||
std::vector<fs::path> dumps;
|
||||
for (int i = 3; i < argc; ++i) {
|
||||
if (std::strcmp(argv[i], "--repeat") == 0 && i + 1 < argc) repeat = std::max(1, std::atoi(argv[++i]));
|
||||
else if (std::strcmp(argv[i], "--call") == 0 && i + 1 < argc) call = std::atoi(argv[++i]);
|
||||
else dumps.emplace_back(argv[i]);
|
||||
}
|
||||
const unsigned long long gguf_bytes = fs::file_size(argv[1]);
|
||||
std::string err;
|
||||
Qi21Dit* dit = qi21_dit_open(argv[1], -1, &err);
|
||||
if (!dit) {
|
||||
std::fprintf(stderr, "%s\n", err.c_str());
|
||||
std::printf("DIT-STEP FAIL\n");
|
||||
return 2;
|
||||
}
|
||||
std::printf("open: %s\n", qi21_dit_open_report(dit).c_str());
|
||||
int bad = 0;
|
||||
size_t peak = 0;
|
||||
for (const auto& d : dumps) {
|
||||
const std::string tag = d.parent_path().filename().string() + "/" + d.filename().string();
|
||||
const std::string xs = "dit_x_" + std::to_string(call), ts = "dit_t_" + std::to_string(call);
|
||||
std::vector<float> x, t, cond;
|
||||
const auto sx = read_shape(d / (xs + ".shape")), sc = read_shape(d / "cond.shape");
|
||||
if (!read_f32(d / (xs + ".bin"), x) || !read_f32(d / (ts + ".bin"), t) || !read_f32(d / "cond.bin", cond) ||
|
||||
sx.size() < 3 || sc.size() < 2 || t.empty()) {
|
||||
std::printf("%s: inputs missing\n", tag.c_str());
|
||||
++bad;
|
||||
continue;
|
||||
}
|
||||
const int W = (int) sx[0], H = (int) sx[1], C = (int) sx[2], ctx = (int) sc[0], L = (int) sc[1];
|
||||
if (C != qi21_dit_in_channels(dit) || ctx != qi21_dit_context_dim(dit) || x.size() != (size_t) W * H * C ||
|
||||
cond.size() != (size_t) ctx * L) {
|
||||
std::printf("%s: shapes do not match the model\n", tag.c_str());
|
||||
++bad;
|
||||
continue;
|
||||
}
|
||||
const int oc = qi21_dit_out_channels(dit);
|
||||
std::vector<float> vel((size_t) oc * W * H), first;
|
||||
for (int r = 0; r < repeat; ++r) {
|
||||
Qi21DitStats st;
|
||||
err = qi21_dit_step(dit, x.data(), W, H, cond.data(), L, t[0], vel.data(), &st);
|
||||
if (!err.empty()) {
|
||||
std::printf("%s: %s\n", tag.c_str(), err.c_str());
|
||||
++bad;
|
||||
break;
|
||||
}
|
||||
peak = std::max(peak, st.peak_bytes);
|
||||
std::printf("%s run %d: %dx%d latent, %d text tokens, t %.4f: step %.1f ms%s; weights %.3f GB, work %.3f GB, "
|
||||
"peak %.3f GB (GGUF %.3f GB)\n",
|
||||
tag.c_str(), r + 1, W, H, L, t[0], st.step_ms,
|
||||
st.prefix_ran ? (" (text prefix " + std::to_string((int) st.prefix_ms) + " ms of it)").c_str() : "",
|
||||
st.weight_bytes / 1e9, st.work_bytes / 1e9, st.peak_bytes / 1e9, gguf_bytes / 1e9);
|
||||
if (r == 0) {
|
||||
first = vel;
|
||||
} else if (std::memcmp(first.data(), vel.data(), vel.size() * 4) != 0) {
|
||||
std::printf("%s run %d: DIFFERS from run 1\n", tag.c_str(), r + 1);
|
||||
++bad;
|
||||
}
|
||||
}
|
||||
const fs::path od = fs::path(argv[2]) / d.parent_path().filename() / d.filename();
|
||||
fs::create_directories(od);
|
||||
std::ofstream(od / "vel.bin", std::ios::binary).write(reinterpret_cast<const char*>(first.data()), first.size() * 4);
|
||||
std::ofstream(od / "vel.shape") << W << " " << H << " " << oc << " 1\n";
|
||||
}
|
||||
std::printf("peak of the DiT's own device memory: %.3f GB (GGUF %.3f GB)\n", peak / 1e9, gguf_bytes / 1e9);
|
||||
qi21_dit_close(dit);
|
||||
std::printf("DIT-STEP %s\n", bad == 0 ? "PASS" : "FAIL");
|
||||
return bad == 0 ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
// src/image/dit/qi21_kernels.cu - see qi21_kernels.hpp. The kernels from tools/image/sdcpp_native/qi21-native.cu
|
||||
// (k_res_ln_mod, k_qkv_post_w, k_swiglu, k_attn_causal, k_attn_mma, k_attn_wmma) with the ggml headers taken out:
|
||||
// the bodies and launch shapes are unchanged, so a step computes what the native runner's kernels computed. New here:
|
||||
// the timestep sinusoid, SiLU, GELU and txt_in's RMSNorm, written as ggml's CUDA kernels compute them (same formulas,
|
||||
// float maths); their reductions are fixed-order, so a run gives the same bytes every time.
|
||||
#include "qi21_kernels.hpp"
|
||||
|
||||
#if defined(__HIP__) || defined(__HIPCC__) || defined(__HIP_PLATFORM_AMD__)
|
||||
#define QI_HIP 1
|
||||
#include "strata/hip_compat/cuda_runtime.h"
|
||||
#include "strata/hip_compat/cuda_fp16.h"
|
||||
#include "strata/hip_compat/intrinsics.hpp"
|
||||
#else
|
||||
#include <cuda_fp16.h>
|
||||
#include <cuda_runtime.h>
|
||||
#endif
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace strata::image::qi21 {
|
||||
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 = (int) 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]);
|
||||
}
|
||||
|
||||
template <typename QT>
|
||||
__device__ __forceinline__ void qi_store4(QT* dst, float a, float b, float c, float d);
|
||||
template <>
|
||||
__device__ __forceinline__ void qi_store4<float>(float* dst, float a, float b, float c, float d) {
|
||||
*reinterpret_cast<float4*>(dst) = make_float4(a, b, c, d);
|
||||
}
|
||||
template <>
|
||||
__device__ __forceinline__ void qi_store4<half>(half* dst, float a, float b, float c, float d) {
|
||||
half2 lo = __floats2half2_rn(a, b), hi2 = __floats2half2_rn(c, d);
|
||||
uint2 u;
|
||||
u.x = *reinterpret_cast<uint32_t*>(&lo);
|
||||
u.y = *reinterpret_cast<uint32_t*>(&hi2);
|
||||
*reinterpret_cast<uint2*>(dst) = u;
|
||||
}
|
||||
|
||||
// warp per head: grid (T, H/8), block 256; lane holds dims 4*lane..+3 (two RoPE pairs), no shared memory
|
||||
template <typename QT>
|
||||
__global__ void __launch_bounds__(256) k_qkv_post_w(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, int q_tstride, half* __restrict__ ko,
|
||||
half* __restrict__ vo, int kv_tstride, int kv_off, float eps) {
|
||||
const int t = blockIdx.x, lane = threadIdx.x & 31, hh = blockIdx.y * 8 + (threadIdx.x >> 5);
|
||||
const int d = lane * 4;
|
||||
const size_t src = (size_t) t * ld + hh * QI_D + d;
|
||||
const float4 p0 = *reinterpret_cast<const float4*>(pe + ((size_t) t * (QI_D / 2) + lane * 2) * 4);
|
||||
const float4 p1 = *reinterpret_cast<const float4*>(pe + ((size_t) t * (QI_D / 2) + lane * 2 + 1) * 4);
|
||||
for (int which = 0; which < 2; ++which) {
|
||||
const float4 x = *reinterpret_cast<const float4*>((which == 0 ? q : k) + src);
|
||||
float ss = x.x * x.x + x.y * x.y + x.z * x.z + x.w * x.w;
|
||||
for (int off = 16; off > 0; off >>= 1) ss += __shfl_xor_sync(0xffffffff, ss, off, 32);
|
||||
const float inv = rsqrtf(ss / QI_D + eps);
|
||||
const float4 w = *reinterpret_cast<const float4*>((which == 0 ? wq : wk) + d);
|
||||
const float y0 = x.x * inv * w.x, y1 = x.y * inv * w.y, y2 = x.z * inv * w.z, y3 = x.w * inv * w.w;
|
||||
const float r0 = p0.x * y0 + p0.y * y1, r1 = p0.z * y0 + p0.w * y1;
|
||||
const float r2 = p1.x * y2 + p1.y * y3, r3 = p1.z * y2 + p1.w * y3;
|
||||
if (which == 0)
|
||||
qi_store4<QT>(qo + ((size_t) hh * q_tstride + t) * QI_D + d, r0, r1, r2, r3);
|
||||
else
|
||||
qi_store4<half>(ko + ((size_t) hh * kv_tstride + kv_off + t) * QI_D + d, r0, r1, r2, r3);
|
||||
}
|
||||
const float4 vv = *reinterpret_cast<const float4*>(v + src);
|
||||
qi_store4<half>(vo + ((size_t) hh * kv_tstride + kv_off + t) * QI_D + d, vv.x, vv.y, vv.z, vv.w);
|
||||
}
|
||||
|
||||
__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. 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]);
|
||||
}
|
||||
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(QI_HIP)
|
||||
// WMMA fragments: gfx11 (RDNA3) lanes hold 16 k-values of their row/column (lanes 16..31 duplicate 0..15) and C row
|
||||
// 2i + (lane >> 4); gfx12 (RDNA4) lanes hold 8 k-values at offset 8 * (lane >> 4) and C row 8 * (lane >> 4) + i.
|
||||
#if defined(__gfx1200__) || defined(__gfx1201__)
|
||||
#define QI_RDNA4 1
|
||||
#define QI_KL 8
|
||||
#define QI_KOFF(hi) ((hi) * 8)
|
||||
#define QI_ROW(i, hi) ((hi) * 8 + (i))
|
||||
#define QI_WMMA __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12
|
||||
#elif defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || \
|
||||
defined(__gfx1150__) || defined(__gfx1151__) || defined(__gfx1152__)
|
||||
#define QI_RDNA3 1
|
||||
#endif
|
||||
#if !defined(QI_KL)
|
||||
#define QI_KL 16
|
||||
#define QI_KOFF(hi) 0
|
||||
#define QI_ROW(i, hi) (2 * (i) + (hi))
|
||||
#define QI_WMMA __builtin_amdgcn_wmma_f32_16x16x16_f16_w32
|
||||
#endif
|
||||
typedef _Float16 qi_h16 __attribute__((ext_vector_type(QI_KL)));
|
||||
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, int hi) {
|
||||
#if QI_KL == 8
|
||||
return __builtin_bit_cast(qi_h16, *reinterpret_cast<const uint4*>(p + QI_KOFF(hi)));
|
||||
#else
|
||||
(void) hi;
|
||||
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);
|
||||
#endif
|
||||
}
|
||||
|
||||
__global__ void __launch_bounds__(FA_NW * 32) k_attn_wmma(const _Float16* __restrict__ Q, 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(QI_RDNA3) || defined(QI_RDNA4)
|
||||
__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];
|
||||
{
|
||||
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, hi);
|
||||
}
|
||||
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) s[t] = QI_WMMA(qa[c], qi_ld16(&sK[t * 16 + l16][c * 16], hi), 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][QI_ROW(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], hi);
|
||||
for (int c = 0; c < QI_D / 16; ++c) o[c] = QI_WMMA(pa, qi_ld16(&sVt[c * 16 + l16][kc * 16], hi), o[c]);
|
||||
}
|
||||
}
|
||||
for (int c = 0; c < QI_D / 16; ++c)
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const int row = q0 + QI_ROW(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
|
||||
}
|
||||
#else // NVIDIA
|
||||
// sm_80+: mma.sync m16n8k16 f16 -> f32 flash attention. 8 warps x 16 queries per block, 64-key tiles of K and V
|
||||
// (row-major) double-buffered with cp.async, ldmatrix (.trans for V) fragments, fp32 online softmax, P in fp16.
|
||||
constexpr int MF_NW = 8, MF_BQ = MF_NW * 16, MF_BKV = 64, MF_LD = QI_D + 8;
|
||||
constexpr size_t MF_SMEM = (size_t) 4 * MF_BKV * MF_LD * sizeof(half);
|
||||
|
||||
__device__ __forceinline__ void qi_mma16816(float* c, const uint32_t* a, const uint32_t* b) {
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
|
||||
asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n"
|
||||
: "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
|
||||
: "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
|
||||
#else
|
||||
(void) c; (void) a; (void) b;
|
||||
__trap();
|
||||
#endif
|
||||
}
|
||||
__device__ __forceinline__ uint32_t qi_pack2(float x, float y) {
|
||||
half2 h = __floats2half2_rn(x, y);
|
||||
return *reinterpret_cast<uint32_t*>(&h);
|
||||
}
|
||||
__device__ __forceinline__ void qi_ldsm_x4(uint32_t* r, const half* p, bool trans) {
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
|
||||
const uint32_t a = (uint32_t) __cvta_generic_to_shared(p);
|
||||
if (trans)
|
||||
asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0,%1,%2,%3}, [%4];\n"
|
||||
: "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a));
|
||||
else
|
||||
asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n"
|
||||
: "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a));
|
||||
#else
|
||||
(void) r; (void) p; (void) trans;
|
||||
#endif
|
||||
}
|
||||
__device__ __forceinline__ void qi_cp16(half* dst, const half* src, bool ok) {
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
|
||||
const uint32_t a = (uint32_t) __cvta_generic_to_shared(dst);
|
||||
const int n = ok ? 16 : 0;
|
||||
asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\n" :: "r"(a), "l"(src), "r"(n));
|
||||
#else
|
||||
(void) dst; (void) src; (void) ok;
|
||||
#endif
|
||||
}
|
||||
|
||||
__global__ void __launch_bounds__(MF_NW * 32) k_attn_mma(const half* __restrict__ Q, int q_tstride,
|
||||
const half* __restrict__ K, const half* __restrict__ V,
|
||||
int kv_tstride, float* __restrict__ O, int H, int nq, int nkv,
|
||||
float scale_log2) {
|
||||
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
|
||||
extern __shared__ __align__(16) half qi_smem[];
|
||||
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
|
||||
const int r = lane >> 2, c2 = (lane & 3) * 2, lr = lane & 7, lq = lane >> 3;
|
||||
const int head = blockIdx.y, q0 = blockIdx.x * MF_BQ + warp * 16;
|
||||
const half* Qh = Q + (size_t) head * q_tstride * QI_D;
|
||||
const half* Kh = K + (size_t) head * kv_tstride * QI_D;
|
||||
const half* Vh = V + (size_t) head * kv_tstride * QI_D;
|
||||
auto tile = [&](int st, int kv) { return qi_smem + ((st * 2 + kv) * MF_BKV) * MF_LD; };
|
||||
auto load = [&](int st, int k0) {
|
||||
for (int e = tid * 8; e < MF_BKV * QI_D; e += MF_NW * 32 * 8) {
|
||||
const int rr = e / QI_D, cc = e % QI_D, key = k0 + rr;
|
||||
const bool ok = key < nkv;
|
||||
const size_t off = (size_t) (ok ? key : 0) * QI_D + cc;
|
||||
qi_cp16(tile(st, 0) + rr * MF_LD + cc, Kh + off, ok);
|
||||
qi_cp16(tile(st, 1) + rr * MF_LD + cc, Vh + off, ok);
|
||||
}
|
||||
asm volatile("cp.async.commit_group;\n");
|
||||
};
|
||||
uint32_t qa[QI_D / 16][4];
|
||||
{
|
||||
const int r0 = min(q0 + r, nq - 1), r1 = min(q0 + r + 8, nq - 1);
|
||||
for (int kc = 0; kc < QI_D / 16; ++kc) {
|
||||
qa[kc][0] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r0 * QI_D + kc * 16 + c2);
|
||||
qa[kc][1] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r1 * QI_D + kc * 16 + c2);
|
||||
qa[kc][2] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r0 * QI_D + kc * 16 + c2 + 8);
|
||||
qa[kc][3] = *reinterpret_cast<const uint32_t*>(Qh + (size_t) r1 * QI_D + kc * 16 + c2 + 8);
|
||||
}
|
||||
}
|
||||
float o[QI_D / 8][4];
|
||||
for (int n = 0; n < QI_D / 8; ++n) o[n][0] = o[n][1] = o[n][2] = o[n][3] = 0.f;
|
||||
float m0 = -INFINITY, m1 = -INFINITY, l0 = 0.f, l1 = 0.f;
|
||||
const int ntiles = (nkv + MF_BKV - 1) / MF_BKV;
|
||||
load(0, 0);
|
||||
for (int it = 0; it < ntiles; ++it) {
|
||||
const int st = it & 1, k0 = it * MF_BKV;
|
||||
if (it + 1 < ntiles) {
|
||||
load(st ^ 1, k0 + MF_BKV);
|
||||
asm volatile("cp.async.wait_group 1;\n");
|
||||
} else {
|
||||
asm volatile("cp.async.wait_group 0;\n");
|
||||
}
|
||||
__syncthreads();
|
||||
const half* sK = tile(st, 0);
|
||||
const half* sV = tile(st, 1);
|
||||
float s[MF_BKV / 8][4];
|
||||
for (int t = 0; t < MF_BKV / 8; ++t) {
|
||||
s[t][0] = s[t][1] = s[t][2] = s[t][3] = 0.f;
|
||||
for (int kc = 0; kc < QI_D / 16; kc += 2) {
|
||||
uint32_t b[4];
|
||||
qi_ldsm_x4(b, sK + (t * 8 + lr) * MF_LD + kc * 16 + lq * 8, false);
|
||||
qi_mma16816(s[t], qa[kc], b);
|
||||
qi_mma16816(s[t], qa[kc + 1], b + 2);
|
||||
}
|
||||
}
|
||||
float mx0 = -INFINITY, mx1 = -INFINITY;
|
||||
for (int t = 0; t < MF_BKV / 8; ++t)
|
||||
for (int j = 0; j < 2; ++j) {
|
||||
const bool ok = k0 + t * 8 + c2 + j < nkv;
|
||||
s[t][j] = ok ? s[t][j] * scale_log2 : -INFINITY;
|
||||
s[t][2 + j] = ok ? s[t][2 + j] * scale_log2 : -INFINITY;
|
||||
mx0 = fmaxf(mx0, s[t][j]);
|
||||
mx1 = fmaxf(mx1, s[t][2 + j]);
|
||||
}
|
||||
for (int off = 1; off < 4; off <<= 1) {
|
||||
mx0 = fmaxf(mx0, __shfl_xor_sync(0xffffffff, mx0, off));
|
||||
mx1 = fmaxf(mx1, __shfl_xor_sync(0xffffffff, mx1, off));
|
||||
}
|
||||
const float mn0 = fmaxf(m0, mx0), mn1 = fmaxf(m1, mx1);
|
||||
const float a0 = exp2f(m0 - mn0), a1 = exp2f(m1 - mn1);
|
||||
float sum0 = 0.f, sum1 = 0.f;
|
||||
for (int t = 0; t < MF_BKV / 8; ++t)
|
||||
for (int j = 0; j < 2; ++j) {
|
||||
s[t][j] = exp2f(s[t][j] - mn0);
|
||||
s[t][2 + j] = exp2f(s[t][2 + j] - mn1);
|
||||
sum0 += s[t][j];
|
||||
sum1 += s[t][2 + j];
|
||||
}
|
||||
for (int off = 1; off < 4; off <<= 1) {
|
||||
sum0 += __shfl_xor_sync(0xffffffff, sum0, off);
|
||||
sum1 += __shfl_xor_sync(0xffffffff, sum1, off);
|
||||
}
|
||||
l0 = l0 * a0 + sum0;
|
||||
l1 = l1 * a1 + sum1;
|
||||
m0 = mn0;
|
||||
m1 = mn1;
|
||||
for (int n = 0; n < QI_D / 8; ++n) {
|
||||
o[n][0] *= a0; o[n][1] *= a0; o[n][2] *= a1; o[n][3] *= a1;
|
||||
}
|
||||
for (int kc = 0; kc < MF_BKV / 16; ++kc) {
|
||||
uint32_t pa[4];
|
||||
pa[0] = qi_pack2(s[2 * kc][0], s[2 * kc][1]);
|
||||
pa[1] = qi_pack2(s[2 * kc][2], s[2 * kc][3]);
|
||||
pa[2] = qi_pack2(s[2 * kc + 1][0], s[2 * kc + 1][1]);
|
||||
pa[3] = qi_pack2(s[2 * kc + 1][2], s[2 * kc + 1][3]);
|
||||
for (int n = 0; n < QI_D / 8; n += 2) {
|
||||
uint32_t b[4];
|
||||
qi_ldsm_x4(b, sV + (kc * 16 + (lq & 1) * 8 + lr) * MF_LD + n * 8 + (lq >> 1) * 8, true);
|
||||
qi_mma16816(o[n], pa, b);
|
||||
qi_mma16816(o[n + 1], pa, b + 2);
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
const int row0 = q0 + r, row1 = q0 + r + 8;
|
||||
for (int n = 0; n < QI_D / 8; ++n) {
|
||||
if (row0 < nq)
|
||||
*reinterpret_cast<float2*>(O + (size_t) row0 * H * QI_D + head * QI_D + n * 8 + c2) =
|
||||
make_float2(o[n][0] / l0, o[n][1] / l0);
|
||||
if (row1 < nq)
|
||||
*reinterpret_cast<float2*>(O + (size_t) row1 * H * QI_D + head * QI_D + n * 8 + c2) =
|
||||
make_float2(o[n][2] / l1, o[n][3] / l1);
|
||||
}
|
||||
#else
|
||||
__trap();
|
||||
#endif
|
||||
}
|
||||
#endif // QI_HIP
|
||||
|
||||
// ---- the steps ggml did for the native runner (ggml-cuda's formulas, float maths)
|
||||
__global__ void k_timestep(const float* __restrict__ t, float* __restrict__ emb, int dim, float max_period) {
|
||||
const int i = blockIdx.y, j = blockIdx.x * blockDim.x + threadIdx.x, half_dim = dim / 2;
|
||||
if (j >= half_dim) return;
|
||||
const float freq = expf(-logf(max_period) * j / half_dim);
|
||||
const float arg = t[i] * freq;
|
||||
emb[(size_t) i * dim + j] = cosf(arg);
|
||||
emb[(size_t) i * dim + j + half_dim] = sinf(arg);
|
||||
}
|
||||
|
||||
__global__ void k_silu(float* __restrict__ x, int64_t n) {
|
||||
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i < n) x[i] = x[i] / (1.f + expf(-x[i]));
|
||||
}
|
||||
|
||||
__global__ void k_gelu(float* __restrict__ x, int64_t n) {
|
||||
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i >= n) return;
|
||||
const float GELU_COEF_A = 0.044715f, SQRT_2_OVER_PI = 0.79788456080286535587989211986876f;
|
||||
const float v = x[i];
|
||||
x[i] = 0.5f * v * (1.f + tanhf(SQRT_2_OVER_PI * v * (1.f + GELU_COEF_A * v * v)));
|
||||
}
|
||||
|
||||
__global__ void __launch_bounds__(256) k_rms_w1(const float* __restrict__ x, const float* __restrict__ w,
|
||||
float* __restrict__ out, int C, float eps) {
|
||||
__shared__ float red[32];
|
||||
const size_t row = blockIdx.x;
|
||||
float s = 0.f;
|
||||
for (int c = threadIdx.x; c < C; c += blockDim.x) s += x[row * C + c] * x[row * C + c];
|
||||
const float inv = rsqrtf(qi_block_sum(s, red) / C + eps);
|
||||
for (int c = threadIdx.x; c < C; c += blockDim.x) out[row * C + c] = x[row * C + c] * inv * (w[c] + 1.f);
|
||||
}
|
||||
|
||||
inline cudaStream_t qs(void* s) { return static_cast<cudaStream_t>(s); }
|
||||
inline int launched() { return cudaGetLastError() == cudaSuccess ? 0 : 2; }
|
||||
inline unsigned blocks(int64_t n) { return (unsigned) ((n + 255) / 256); }
|
||||
|
||||
} // namespace
|
||||
|
||||
int 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 || T <= 0) return T <= 0 ? 0 : 1;
|
||||
if (h != nullptr && out != nullptr)
|
||||
k_res_ln_mod<true, true><<<T, 256, 0, qs(stream)>>>(x, h, g, out, m, C, eps);
|
||||
else if (h != nullptr)
|
||||
k_res_ln_mod<true, false><<<T, 256, 0, qs(stream)>>>(x, h, g, out, m, C, eps);
|
||||
else
|
||||
k_res_ln_mod<false, true><<<T, 256, 0, qs(stream)>>>(x, h, g, out, m, C, eps);
|
||||
return launched();
|
||||
}
|
||||
|
||||
int 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, int q_f16, int q_tstride, void* ko, void* vo, int kv_tstride, int kv_off, int T,
|
||||
int H, float eps) {
|
||||
if (H % 8 != 0 || ld % 4 != 0) return 1;
|
||||
const dim3 gw(T, H / 8);
|
||||
if (q_f16)
|
||||
k_qkv_post_w<half><<<gw, 256, 0, qs(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<half*>(qo), q_tstride,
|
||||
static_cast<half*>(ko), static_cast<half*>(vo), kv_tstride, kv_off,
|
||||
eps);
|
||||
else
|
||||
k_qkv_post_w<float><<<gw, 256, 0, qs(stream)>>>(q, k, v, ld, wq, wk, pe, static_cast<float*>(qo), q_tstride,
|
||||
static_cast<half*>(ko), static_cast<half*>(vo), kv_tstride, kv_off,
|
||||
eps);
|
||||
return launched();
|
||||
}
|
||||
|
||||
int swiglu(void* stream, const float* gu, float* out, int T, int F) {
|
||||
const int64_t n = (int64_t) T * F;
|
||||
k_swiglu<<<blocks(n), 256, 0, qs(stream)>>>(gu, out, F, n);
|
||||
return launched();
|
||||
}
|
||||
|
||||
int attn_exact(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, qs(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 launched();
|
||||
}
|
||||
|
||||
int has_fast_attn(int device) {
|
||||
cudaDeviceProp prop{};
|
||||
if (cudaGetDeviceProperties(&prop, device) != cudaSuccess) return 0;
|
||||
#if defined(QI_HIP)
|
||||
const char* arch = prop.gcnArchName;
|
||||
for (const char* p : {"gfx1100", "gfx1101", "gfx1102", "gfx1103", "gfx1150", "gfx1151", "gfx1152"})
|
||||
if (std::strncmp(arch, p, 7) == 0) return 1;
|
||||
const char* g12 = std::getenv("STRATA_QI_GFX12_ATTN");
|
||||
const bool rdna4 = std::strncmp(arch, "gfx1200", 7) == 0 || std::strncmp(arch, "gfx1201", 7) == 0;
|
||||
return rdna4 && g12 != nullptr && g12[0] == '1' ? 1 : 0;
|
||||
#else
|
||||
return prop.major >= 8 ? 1 : 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
int attn_fast(void* stream, const void* q, int q_tstride, const void* k, const void* v, int kv_tstride, float* out, int H,
|
||||
int nq, int nkv) {
|
||||
const float sl = (float) (1.0 / std::sqrt((double) QI_D) * 1.4426950408889634);
|
||||
#if defined(QI_HIP)
|
||||
k_attn_wmma<<<dim3((nq + FA_BQ - 1) / FA_BQ, H), FA_NW * 32, 0, qs(stream)>>>(
|
||||
static_cast<const _Float16*>(q), q_tstride, static_cast<const _Float16*>(k), static_cast<const _Float16*>(v),
|
||||
kv_tstride, out, H, nq, nkv, sl);
|
||||
#else
|
||||
static bool attr = false;
|
||||
if (!attr) {
|
||||
if (cudaFuncSetAttribute(k_attn_mma, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) MF_SMEM) != cudaSuccess)
|
||||
return 2;
|
||||
attr = true;
|
||||
}
|
||||
k_attn_mma<<<dim3((nq + MF_BQ - 1) / MF_BQ, H), MF_NW * 32, MF_SMEM, qs(stream)>>>(
|
||||
static_cast<const half*>(q), q_tstride, static_cast<const half*>(k), static_cast<const half*>(v), kv_tstride, out,
|
||||
H, nq, nkv, sl);
|
||||
#endif
|
||||
return launched();
|
||||
}
|
||||
|
||||
int timestep_embedding(void* stream, const float* t, float* emb, int n, int dim, float max_period) {
|
||||
if (dim % 2 != 0) return 1;
|
||||
k_timestep<<<dim3((dim / 2 + 255) / 256, n), 256, 0, qs(stream)>>>(t, emb, dim, max_period);
|
||||
return launched();
|
||||
}
|
||||
|
||||
int silu(void* stream, float* x, int64_t n) {
|
||||
k_silu<<<blocks(n), 256, 0, qs(stream)>>>(x, n);
|
||||
return launched();
|
||||
}
|
||||
|
||||
int gelu_tanh(void* stream, float* x, int64_t n) {
|
||||
k_gelu<<<blocks(n), 256, 0, qs(stream)>>>(x, n);
|
||||
return launched();
|
||||
}
|
||||
|
||||
int rms_norm_w1(void* stream, const float* x, const float* w, float* out, int T, int C, float eps) {
|
||||
if (T <= 0) return 0;
|
||||
k_rms_w1<<<T, 256, 0, qs(stream)>>>(x, w, out, C, eps);
|
||||
return launched();
|
||||
}
|
||||
|
||||
} // namespace strata::image::qi21
|
||||
@@ -0,0 +1,50 @@
|
||||
// src/image/dit/qi21_kernels.hpp - the Qwen-Image-2.1 DiT's element-wise and attention kernels (src/image/dit/
|
||||
// qi21_kernels.cu), launched on a caller's stream. Moved from the sd.cpp patch tools/image/sdcpp_native/qi21-native.cu
|
||||
// (same kernels, same launch shapes; that patch keeps its own copy for the test builds until the sd-cli hook changes),
|
||||
// plus the steps ggml still did for the native runner: the timestep sinusoid, SiLU, GELU (tanh form), the zero-centred
|
||||
// RMSNorm of txt_in. Every launcher returns 0, or 1 for an unsupported shape, 2 for a launch error.
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace strata::image::qi21 {
|
||||
|
||||
// x += h * tanh(g) (when h), then out = LayerNorm(x) * (1 + m) (when out); no affine, eps. T rows of C (C <= 8192).
|
||||
int res_ln_mod(void* stream, float* x, const float* h, const float* g, float* out, const float* m, int T, int C, float eps);
|
||||
|
||||
// per head of T tokens: q, k RMSNorm * wq | wk, RoPE from the per-token table pe ([T][64][4]), q -> qo head-major
|
||||
// [H][q_tstride][128] (f16 when q_f16, else f32), k, v -> f16 head-major [H][kv_tstride][128] at row kv_off.
|
||||
// q, k, v rows have stride ld floats. H % 8 == 0, ld % 4 == 0.
|
||||
int 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, int q_f16, int q_tstride, void* ko, void* vo, int kv_tstride, int kv_off, int T,
|
||||
int H, float eps);
|
||||
|
||||
// out[T][F] = up * silu(gate), gu = [T][gate F | up F]
|
||||
int swiglu(void* stream, const float* gu, float* out, int T, int F);
|
||||
|
||||
// fp32 attention, q f32 head-major, k / v f16 head-major, out token-major [Lq][H*128]; causal: query i sees keys
|
||||
// 0..i (the text prefix); otherwise all Lk keys (the exact reference path). Lk * 4 bytes of shared memory <= 48 KiB.
|
||||
int attn_exact(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);
|
||||
|
||||
// 1 when this device runs attn_fast (NVIDIA sm_80+: mma.sync; HIP gfx11: WMMA; gfx12 with STRATA_QI_GFX12_ATTN=1)
|
||||
int has_fast_attn(int device);
|
||||
|
||||
// flash attention for the image tokens: q f16 head-major, k / v f16 head-major, out f32 token-major
|
||||
int attn_fast(void* stream, const void* q, int q_tstride, const void* k, const void* v, int kv_tstride, float* out, int H,
|
||||
int nq, int nkv);
|
||||
|
||||
// emb[n][dim] = [cos(t * f_j) | sin(t * f_j)], f_j = exp(-ln(max_period) * j / (dim / 2)) (ggml_timestep_embedding)
|
||||
int timestep_embedding(void* stream, const float* t, float* emb, int n, int dim, float max_period);
|
||||
|
||||
// x = x / (1 + exp(-x)) in place
|
||||
int silu(void* stream, float* x, int64_t n);
|
||||
|
||||
// x = 0.5 x (1 + tanh(sqrt(2 / pi) x (1 + 0.044715 x^2))) in place (ggml's GELU)
|
||||
int gelu_tanh(void* stream, float* x, int64_t n);
|
||||
|
||||
// out[r] = x[r] / sqrt(mean(x[r]^2) + eps) * (w + 1), T rows of C (txt_in's zero-centred RMSNorm)
|
||||
int rms_norm_w1(void* stream, const float* x, const float* w, float* out, int T, int C, float eps);
|
||||
|
||||
} // namespace strata::image::qi21
|
||||
@@ -0,0 +1,89 @@
|
||||
"""tools/image/gate/dit_step_check.py - TEST-ONLY (OWN-5B D4): strata-dit-step's velocities against the reference.
|
||||
|
||||
For each case: velocity rel L2 to the f32 reference (dit_ref.py) for ours (strata-dit-step), the emulation with
|
||||
float32 sums (dit_ref mode f16acc32, the stage rule's comparison since 11-11) and with exact sums (f16op), the D1+D2
|
||||
test build (sd.cpp's native runner with our GEMMs), stock sd.cpp and its native runner; and ours against the D1+D2
|
||||
build directly. Then the stage rule over the cases given: (i) mean ours <= 1.25 x mean emulation, (ii) no case above
|
||||
1.5 x its emulation value, (iii) every case closer than stock and native - against both emulations.
|
||||
|
||||
python -I -B dit_step_check.py --root R --ours O [--cases "512 p0,512 p5"]
|
||||
R = the Spark own5b folder (pics/, d0ref/ with d0ref/acc32 from dit_acc32_cases.py); O = strata-dit-step's out dir.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
if str(_HERE) not in sys.path:
|
||||
sys.path.insert(0, str(_HERE))
|
||||
from te_ref import compare # noqa: E402
|
||||
|
||||
|
||||
def vel(path) -> np.ndarray:
|
||||
"""a velocity file ([C][H][W] float32, sd.cpp's vel_<k>.bin layout) as [H*W][C] rows"""
|
||||
return np.fromfile(path, dtype="<f4").reshape(64, -1).T
|
||||
|
||||
|
||||
def case_paths(root: Path, name: str) -> dict:
|
||||
size, p = name.split()
|
||||
p = int(p[1:])
|
||||
dn = f"dump_p{p}_s42"
|
||||
if size == "1024":
|
||||
return {"dump": root / "pics/d0_stock_1024" / dn, "ref": root / "d0ref/r1024" / dn,
|
||||
"acc32": root / "d0ref/acc32/1024_p0_acc32.npy", "stock": root / "pics/d0_stock_1024" / dn / "vel_0.bin",
|
||||
"native": root / "pics/d0_native_1024" / dn / "vel_0.bin",
|
||||
"d1d2": root / "pics/z_ours_1024" / dn / "vel_0.bin"}
|
||||
lo = "d0" if p < 4 else "z"
|
||||
return {"dump": root / f"pics/{lo}_stock_512" / dn, "ref": root / "d0ref" / dn,
|
||||
"acc32": root / f"d0ref/acc32/512_p{p}_acc32.npy", "stock": root / f"pics/{lo}_stock_512" / dn / "vel_0.bin",
|
||||
"native": root / f"pics/{lo}_native_512" / dn / "vel_0.bin",
|
||||
"d1d2": root / ("pics/d2_g15" if p < 4 else "pics/z_ours_512") / dn / "vel_0.bin"}
|
||||
|
||||
|
||||
def rule(rows: list, k: int) -> str:
|
||||
O = np.mean([r["ours"] for r in rows])
|
||||
E = np.mean([r[k] for r in rows])
|
||||
worst = max(rows, key=lambda r: r["ours"] / r[k])
|
||||
ii = all(r["ours"] <= 1.5 * r[k] for r in rows)
|
||||
iii = all(r["ours"] < r["stock"] and r["ours"] < r["native"] for r in rows)
|
||||
return (f"(i) mean {O:.5f} / {E:.5f} = {O / E:.3f} ({'PASS' if O <= 1.25 * E else 'FAIL'}); (ii) largest "
|
||||
f"{worst['ours'] / worst[k]:.3f} at {worst['name']} ({'PASS' if ii else 'FAIL'}); (iii) "
|
||||
f"{'PASS' if iii else 'FAIL'}")
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--root", required=True)
|
||||
ap.add_argument("--ours", required=True)
|
||||
ap.add_argument("--cases", default="512 p0,512 p5")
|
||||
a = ap.parse_args(argv)
|
||||
root, ours_dir = Path(a.root), Path(a.ours)
|
||||
rows = []
|
||||
for name in [c.strip() for c in a.cases.split(",") if c.strip()]:
|
||||
P = case_paths(root, name)
|
||||
f32 = np.load(str(P["ref"]) + "_f32.npy").reshape(64, -1).T
|
||||
o = vel(ours_dir / P["dump"].parent.name / P["dump"].name / "vel.bin")
|
||||
r = {"name": name, "ours": compare(o, f32)["rel_l2"],
|
||||
"f16acc32": compare(np.load(P["acc32"]).reshape(64, -1).T, f32)["rel_l2"],
|
||||
"f16op": compare(np.load(str(P["ref"]) + "_f16op.npy").reshape(64, -1).T, f32)["rel_l2"],
|
||||
"d1d2": compare(vel(P["d1d2"]), f32)["rel_l2"], "stock": compare(vel(P["stock"]), f32)["rel_l2"],
|
||||
"native": compare(vel(P["native"]), f32)["rel_l2"], "ours_vs_d1d2": compare(o, vel(P["d1d2"]))["rel_l2"]}
|
||||
rows.append(r)
|
||||
print("| case | ours (strata-dit-step) | f32-sum emulation | ratio | exact-sum emulation | ratio | D1+D2 test build "
|
||||
"| stock | native | ours vs D1+D2 build |")
|
||||
print("|---|---|---|---|---|---|---|---|---|---|")
|
||||
for r in rows:
|
||||
print(f"| {r['name']} | {r['ours']:.5f} | {r['f16acc32']:.5f} | {r['ours'] / r['f16acc32']:.3f} | "
|
||||
f"{r['f16op']:.5f} | {r['ours'] / r['f16op']:.3f} | {r['d1d2']:.5f} | {r['stock']:.5f} | "
|
||||
f"{r['native']:.5f} | {r['ours_vs_d1d2']:.5f} |")
|
||||
print("RULE vs the float32-sum emulation: " + rule(rows, "f16acc32"))
|
||||
print("RULE vs the exact-sum emulation: " + rule(rows, "f16op"))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,61 @@
|
||||
"""tools/image/gate/test_dit_step_check.py - TEST-ONLY: dit_step_check.py on a fake folder (no model, no GPU).
|
||||
|
||||
python -m pytest tools/image/gate/test_dit_step_check.py"""
|
||||
import contextlib
|
||||
import io
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import dit_step_check as K # noqa: E402
|
||||
|
||||
|
||||
def put(path: Path, a: np.ndarray, npy: bool = False) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if npy:
|
||||
np.save(path, a)
|
||||
else:
|
||||
a.astype("<f4").tofile(path)
|
||||
|
||||
|
||||
class StepCheck(unittest.TestCase):
|
||||
def test_table_and_rule(self):
|
||||
rng = np.random.default_rng(3)
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root, ours = Path(td) / "own5b", Path(td) / "ours"
|
||||
for p, scale in ((0, 1.0), (5, 3.0)):
|
||||
P = K.case_paths(root, f"512 p{p}")
|
||||
ref = rng.standard_normal((64, 4, 4)).astype(np.float32)
|
||||
noise = lambda s: ref + s * rng.standard_normal(ref.shape).astype(np.float32) # noqa: E731
|
||||
put(Path(str(P["ref"]) + "_f32.npy"), ref, True)
|
||||
put(Path(str(P["ref"]) + "_f16op.npy"), noise(1e-3), True)
|
||||
put(P["acc32"], noise(1e-3 * scale), True)
|
||||
put(P["stock"], noise(1e-2))
|
||||
put(P["native"], noise(1e-2))
|
||||
put(P["d1d2"], noise(1e-3))
|
||||
put(ours / P["dump"].parent.name / P["dump"].name / "vel.bin", noise(1e-3 * scale))
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
K.main(["--root", str(root), "--ours", str(ours)])
|
||||
text = out.getvalue()
|
||||
self.assertIn("| 512 p0 |", text)
|
||||
self.assertIn("| 512 p5 |", text)
|
||||
f32_rule = next(line for line in text.splitlines() if line.startswith("RULE vs the float32"))
|
||||
exact_rule = next(line for line in text.splitlines() if line.startswith("RULE vs the exact"))
|
||||
self.assertIn("(iii) PASS", f32_rule) # 1e-3 vs 1e-2: ours closer than stock and native
|
||||
self.assertIn("(ii) largest", f32_rule)
|
||||
self.assertIn("FAIL", exact_rule) # p5 ours ~3x the exact-sum emulation
|
||||
|
||||
def test_case_paths(self):
|
||||
P = K.case_paths(Path("/r"), "1024 p0")
|
||||
self.assertEqual(P["acc32"].name, "1024_p0_acc32.npy")
|
||||
self.assertEqual(K.case_paths(Path("/r"), "512 p6")["d1d2"].parent.parent.name, "z_ours_512")
|
||||
self.assertEqual(K.case_paths(Path("/r"), "512 p2")["d1d2"].parent.parent.name, "d2_g15")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user