image: DiT kernels write the GEMM inputs as f16 directly (D4, second piece)

The kernels whose output only feeds a GEMM - LayerNorm + modulate (also the head's),
SwiGLU and both attention kernels - now store f16 instead of f32, and the GEMMs read those
rows in place (dit_gemm_x16); dit_gemm's separate f32 -> f16 conversion pass is gone from
the step. Each kernel computes in f32 as before and rounds at the store, to nearest even:
the same bits the conversion pass made (f16_from_f32; the attention's epilogue uses the
hardware pair conversion, the same bits for every finite value, because f16_from_f32's
integer code there doubled the kernel's time). dit_gemm reads an F16 weight in place
without the decode. The text-input MLP and the prelude keep the f32 path.

Gate (GB10, dgxspark-20261111-0552-384c): the velocities of the nine stage cases (512
prompts 0-7, 1024 prompt 0) are byte-identical to 1705c8b9f's.
Step time, median of 5 steps after the text prefix run, two rounds in the same job
(1705c8b9f -> this):
  512 p0:  374.8 -> 359.3 ms, 381.6 -> 365.2 ms
  1024 p0: 1326.3 -> 1208.7 ms, 1322.3 -> 1241.9 ms
Memory peak of the DiT's own buffers: 8.120 -> 8.070 GB at 512, 8.905 -> 8.704 GB at 1024
(Q8_0 GGUF 7.641 GB): the f32 attention / SwiGLU buffers and the GEMM's f16 activation
buffer are no longer needed.
nsys at 1024 (dgxspark-20261111-0551-c25d, the first try with the software rounding in the
attention): rows_to_f16 335 ms -> 0, k_res_ln_mod 377 -> 329 ms, k_swiglu 308 -> 253 ms
over 4 steps; the attention 520 -> 1054 ms then, fixed here.
CPU tests: p1006-20261111-0549-c852, 51 passed (test_sdcpp_dit: the sd.cpp patch copies
dit_gemm.cu; its old entry point keeps its behaviour).
Not used by any build or by sd-cli. HIP written, not compiled.
This commit is contained in:
Niko1221 committed 2026-11-11 05:55:30 +01:00
1 parent 1705c8b9f0
commit bb5f308b9b
6 files changed
+183 -65

No files matched your search

+7
View File
@@ -13,9 +13,16 @@ namespace strata::image {
// y[n][N] (f32, row stride ldy floats) = x[n][K] (f32 rows, stride ldx floats) . W[N][K]^T, W = `type` blocks at w
// (N rows of K values, GGUF layout), on `stream` (cudaStream_t / hipStream_t). Asynchronous; "" on success.
// The decoded weight and the f16 activations live in buffers kept between calls (dit_gemm_release frees them).
// A weight of type F16 (TE_F16) is read in place, without the decode into the buffer.
std::string dit_gemm(void* stream, uint32_t type, const void* w, int64_t K, int64_t N, const float* x, int64_t ldx,
int64_t n, float* y, int64_t ldy);
// the same with the activations already f16 (x16: n rows of K f16 values, row stride ldx elements), as the kernels
// that feed a GEMM can write them; no conversion pass. Same GEMM, so the same bytes as dit_gemm on the f32 rows
// those f16 values were rounded from.
std::string dit_gemm_x16(void* stream, uint32_t type, const void* w, int64_t K, int64_t N, const uint16_t* x16,
int64_t ldx, int64_t n, float* y, int64_t ldy);
// device bytes the buffers hold now
size_t dit_gemm_buffer_bytes();
void dit_gemm_release();
+38 -12
View File
@@ -53,8 +53,11 @@ std::string grow(uint16_t*& p, size_t& cap, size_t elems) {
} // namespace
std::string dit_gemm(void* stream, uint32_t type, const void* w, int64_t K, int64_t N, const float* x, int64_t ldx,
int64_t n, float* y, int64_t ldy) {
namespace {
// x (f32 rows, converted here) or x16 (f16 rows, used in place)
std::string gemm_impl(void* stream, uint32_t type, const void* w, int64_t K, int64_t N, const float* x,
const uint16_t* x16, int64_t ldx, int64_t n, float* y, int64_t ldy) {
if (n <= 0) return std::string();
State& s = st();
std::lock_guard<std::mutex> lock(s.mu);
@@ -66,25 +69,48 @@ std::string dit_gemm(void* stream, uint32_t type, const void* w, int64_t K, int6
if (cublasCreate(&s.blas) != CUBLAS_STATUS_SUCCESS) return "dit_gemm: cannot create the BLAS handle";
s.device = dev;
}
std::string err = grow(s.w16, s.w_cap, (size_t) N * (size_t) K);
if (err.empty()) err = grow(s.x16, s.x_cap, (size_t) n * (size_t) K);
std::string err;
if (type != TE_F16) err = grow(s.w16, s.w_cap, (size_t) N * (size_t) K);
if (err.empty() && x16 == nullptr) err = grow(s.x16, s.x_cap, (size_t) n * (size_t) K);
if (!err.empty()) return err;
cudaStream_t cs = static_cast<cudaStream_t>(stream);
err = te_dequant_f16(type, w, K, N, s.w16, stream);
if (!err.empty()) return "dit_gemm: " + err;
const int64_t total = n * K;
const int64_t blocks = (total + 255) / 256;
rows_to_f16<<<(unsigned) (blocks < 65535 * 8 ? blocks : 65535 * 8), 256, 0, cs>>>(x, ldx, K, n, s.x16);
if (cudaGetLastError() != cudaSuccess) return "dit_gemm: the f16 conversion kernel failed";
const uint16_t* wa = static_cast<const uint16_t*>(w);
if (type != TE_F16) {
err = te_dequant_f16(type, w, K, N, s.w16, stream);
if (!err.empty()) return "dit_gemm: " + err;
wa = s.w16;
}
const uint16_t* xa = x16;
int64_t lda = ldx;
if (x16 == nullptr) {
const int64_t total = n * K;
const int64_t blocks = (total + 255) / 256;
rows_to_f16<<<(unsigned) (blocks < 65535 * 8 ? blocks : 65535 * 8), 256, 0, cs>>>(x, ldx, K, n, s.x16);
if (cudaGetLastError() != cudaSuccess) return "dit_gemm: the f16 conversion kernel failed";
xa = s.x16;
lda = K;
}
if (cublasSetStream(s.blas, cs) != CUBLAS_STATUS_SUCCESS) return "dit_gemm: cublasSetStream failed";
const float one = 1.f, zero = 0.f;
const auto r = cublasGemmEx(s.blas, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) n, (int) K, &one, s.w16, CUDA_R_16F,
(int) K, s.x16, CUDA_R_16F, (int) K, &zero, y, CUDA_R_32F, (int) ldy, CUBLAS_COMPUTE_32F,
const auto r = cublasGemmEx(s.blas, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, (int) n, (int) K, &one, wa, CUDA_R_16F,
(int) K, xa, CUDA_R_16F, (int) lda, &zero, y, CUDA_R_32F, (int) ldy, CUBLAS_COMPUTE_32F,
CUBLAS_GEMM_DEFAULT);
if (r != CUBLAS_STATUS_SUCCESS) return "dit_gemm: GemmEx status " + std::to_string((int) r);
return std::string();
}
} // namespace
std::string dit_gemm(void* stream, uint32_t type, const void* w, int64_t K, int64_t N, const float* x, int64_t ldx,
int64_t n, float* y, int64_t ldy) {
return gemm_impl(stream, type, w, K, N, x, nullptr, ldx, n, y, ldy);
}
std::string dit_gemm_x16(void* stream, uint32_t type, const void* w, int64_t K, int64_t N, const uint16_t* x16,
int64_t ldx, int64_t n, float* y, int64_t ldy) {
return gemm_impl(stream, type, w, K, N, nullptr, x16, ldx, n, y, ldy);
}
size_t dit_gemm_buffer_bytes() {
State& s = st();
std::lock_guard<std::mutex> lock(s.mu);
+29 -22
View File
@@ -93,7 +93,8 @@ struct Qi21Dit {
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;
float *x = nullptr, *h = nullptr, *gu = nullptr, *q16 = nullptr;
uint16_t *h16 = nullptr, *a16 = nullptr, *m16 = nullptr; // GEMM inputs, written f16 by the kernels before them
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;
@@ -270,9 +271,10 @@ std::string alloc(Qi21Dit* d, int64_t T, int64_t L) {
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->h16, R * C * h2));
DIT_TRY(get(d->a16, R * C * h2));
DIT_TRY(get(d->m16, R * F * h2));
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));
@@ -299,6 +301,11 @@ std::string mm(Qi21Dit* d, const W2& w, const float* x, int64_t ldx, int64_t n,
return dit_gemm(d->stream, w.type, wp(d, w), w.K, w.N, x, ldx, n, y, ldy);
}
// the same with f16 rows (row stride ldx elements) written by the kernel before the GEMM
std::string mm16(Qi21Dit* d, const W2& w, const uint16_t* x16, int64_t ldx, int64_t n, float* y, int64_t ldy) {
return dit_gemm_x16(d->stream, w.type, wp(d, w), w.K, w.N, x16, 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) {
@@ -311,19 +318,19 @@ std::string blocks_pass(Qi21Dit* d, int64_t n, bool prefix, const float* pe, int
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));
DIT_K(qi21::res_ln_mod_f16(s, X, nullptr, nullptr, d->h16, 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));
DIT_TRY(mm16(d, B.qkv, d->h16, 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_TRY(mm16(d, q, d->h16, C, n, d->gu, 3 * C));
DIT_TRY(mm16(d, B.k, d->h16, C, n, d->gu + C, 3 * C));
DIT_TRY(mm16(d, B.v, d->h16, 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));
@@ -337,7 +344,7 @@ std::string blocks_pass(Qi21Dit* d, int64_t n, bool prefix, const float* pe, int
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));
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));
} 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,
@@ -346,18 +353,18 @@ std::string blocks_pass(Qi21Dit* d, int64_t n, bool prefix, const float* pe, int
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));
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));
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,
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,
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));
DIT_TRY(mm16(d, B.out, d->a16, C, n, Hh, C));
DIT_K(qi21::res_ln_mod_f16(s, X, Hh, m1, d->h16, m2, (int) n, (int) C, EPS));
DIT_TRY(mm16(d, B.gate_up, d->h16, C, n, d->gu, 2 * F));
DIT_K(qi21::swiglu_f16(s, d->gu, d->m16, (int) n, (int) F));
DIT_TRY(mm16(d, B.down, d->m16, 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));
DIT_K(qi21::res_ln_mod_f16(s, X, Hh, m3, last ? nullptr : d->h16, m0, (int) n, (int) C, EPS));
}
return std::string();
}
@@ -399,9 +406,9 @@ std::string step_impl(Qi21Dit* d, const float* latent, int W, int Hd, const floa
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(mm(d, d->txt_in1, d->gu, d->ctx_dim, L, d->h, C));
DIT_K(qi21::gelu_tanh(s, d->h, (int64_t) L * C));
DIT_TRY(mm(d, d->txt_in2, d->h, C, L, d->x, C));
DIT_TRY(blocks_pass(d, L, true, d->pe_txt, 0));
d->prefix_key = key;
d->prefix_len = L;
@@ -418,8 +425,8 @@ std::string step_impl(Qi21Dit* d, const float* latent, int W, int Hd, const floa
}
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_K(qi21::res_ln_mod_f16(s, d->x, nullptr, nullptr, d->h16, d->scale, (int) T, (int) C, EPS));
DIT_TRY(mm16(d, d->proj_out, d->h16, 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));
+7
View File
@@ -87,6 +87,7 @@ int main(int argc, char** argv) {
}
const int oc = qi21_dit_out_channels(dit);
std::vector<float> vel((size_t) oc * W * H), first;
std::vector<double> later; // step times of runs 2.. (the text prefix reused, as in sampling steps 2..8)
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);
@@ -96,6 +97,7 @@ int main(int argc, char** argv) {
break;
}
peak = std::max(peak, st.peak_bytes);
if (r > 0) later.push_back(st.step_ms);
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,
@@ -108,6 +110,11 @@ int main(int argc, char** argv) {
++bad;
}
}
if (!later.empty()) {
std::sort(later.begin(), later.end());
std::printf("%s: median step of runs 2..%d: %.1f ms (min %.1f, max %.1f)\n", tag.c_str(), repeat,
later[later.size() / 2], later.front(), later.back());
}
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);
+92 -31
View File
@@ -15,6 +15,8 @@
#include <cuda_runtime.h>
#endif
#include "strata/kernels/f16_bits.hpp"
#include <cmath>
#include <cstdint>
#include <cstdlib>
@@ -25,6 +27,11 @@ namespace {
constexpr int QI_D = 128;
// an output element: float as computed, or f16 bits rounded from that float by f16_from_f32 (round to nearest even),
// the rounding dit_gemm's conversion pass applies, so an f16 store gives the bytes the conversion gave
__device__ __forceinline__ void qi_put(float* p, size_t i, float v) { p[i] = v; }
__device__ __forceinline__ void qi_put(uint16_t* p, size_t i, float v) { p[i] = strata::kernels::f16_from_f32(v); }
__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);
@@ -42,9 +49,9 @@ __device__ __forceinline__ float qi_block_sum(float v, float* red) {
return red[0];
}
template <bool RES, bool LN>
template <bool RES, bool LN, typename OT>
__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__ g, OT* __restrict__ out,
const float* __restrict__ m, int C, float eps) {
__shared__ float red[32];
const size_t row = blockIdx.x;
@@ -67,7 +74,7 @@ __global__ void __launch_bounds__(256) k_res_ln_mod(float* __restrict__ x, const
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]);
for (int c = threadIdx.x; c < C; c += blockDim.x) qi_put(out, row * C + c, (v[n++] - mean) * inv * (1.f + m[c]));
}
template <typename QT>
@@ -115,18 +122,20 @@ __global__ void __launch_bounds__(256) k_qkv_post_w(const float* __restrict__ q,
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) {
template <typename OT>
__global__ void k_swiglu(const float* __restrict__ gu, OT* __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)));
qi_put(out, (size_t) i, u * (g / (1.f + expf(-g))));
}
// grid (Lq, H), block 128, dynamic smem Lk floats. causal: query i sees keys 0..i.
template <typename OT>
__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 kv_tstride, OT* __restrict__ out, int H, int Lk,
int causal, float scale) {
extern __shared__ float s[];
__shared__ float red[32];
@@ -158,7 +167,7 @@ __global__ void __launch_bounds__(QI_D) k_attn_causal(const float* __restrict__
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;
qi_put(out, (size_t) i * H * QI_D + hh * QI_D + d, acc / sum);
}
#if defined(QI_HIP)
@@ -195,9 +204,10 @@ __device__ __forceinline__ qi_h16 qi_ld16(const _Float16* p, int hi) {
#endif
}
template <typename OT>
__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,
int kv_tstride, OT* __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];
@@ -279,7 +289,7 @@ __global__ void __launch_bounds__(FA_NW * 32) k_attn_wmma(const _Float16* __rest
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];
if (row < nq) qi_put(O, (size_t) row * H * QI_D + head * QI_D + c * 16 + l16, o[c][i] / l[i]);
}
#else
__builtin_trap();
@@ -328,9 +338,20 @@ __device__ __forceinline__ void qi_cp16(half* dst, const half* src, bool ok) {
#endif
}
__device__ __forceinline__ void qi_put2(float* p, size_t i, float a, float b) {
*reinterpret_cast<float2*>(p + i) = make_float2(a, b);
}
// the hardware's round-to-nearest-even pair conversion (the same bits as f16_from_f32 for every finite value and
// infinity) and one 4-byte store: f16_from_f32's integer code here doubled the kernel's time (spills in the epilogue)
__device__ __forceinline__ void qi_put2(uint16_t* p, size_t i, float a, float b) {
half2 h = __floats2half2_rn(a, b);
*reinterpret_cast<uint32_t*>(p + i) = *reinterpret_cast<uint32_t*>(&h);
}
template <typename OT>
__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,
int kv_tstride, OT* __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[];
@@ -438,12 +459,8 @@ __global__ void __launch_bounds__(MF_NW * 32) k_attn_mma(const half* __restrict_
}
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);
if (row0 < nq) qi_put2(O, (size_t) row0 * H * QI_D + head * QI_D + n * 8 + c2, o[n][0] / l0, o[n][1] / l0);
if (row1 < nq) qi_put2(O, (size_t) row1 * H * QI_D + head * QI_D + n * 8 + c2, o[n][2] / l1, o[n][3] / l1);
}
#else
__trap();
@@ -490,16 +507,28 @@ 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) {
namespace {
template <typename OT>
int res_ln_mod_t(void* stream, float* x, const float* h, const float* g, OT* 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);
k_res_ln_mod<true, true, OT><<<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);
k_res_ln_mod<true, false, OT><<<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);
k_res_ln_mod<false, true, OT><<<T, 256, 0, qs(stream)>>>(x, h, g, out, m, C, eps);
return launched();
}
} // 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) {
return res_ln_mod_t<float>(stream, x, h, g, out, m, T, C, eps);
}
int res_ln_mod_f16(void* stream, float* x, const float* h, const float* g, uint16_t* out, const float* m, int T, int C,
float eps) {
return res_ln_mod_t<uint16_t>(stream, x, h, g, out, m, T, C, eps);
}
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,
@@ -519,19 +548,38 @@ int qkv_post(void* stream, const float* q, const float* k, const float* v, int l
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);
k_swiglu<float><<<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) {
int swiglu_f16(void* stream, const float* gu, uint16_t* out, int T, int F) {
const int64_t n = (int64_t) T * F;
k_swiglu<uint16_t><<<blocks(n), 256, 0, qs(stream)>>>(gu, out, F, n);
return launched();
}
namespace {
template <typename OT>
int attn_exact_t(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride, OT* 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));
k_attn_causal<OT><<<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();
}
} // namespace
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) {
return attn_exact_t<float>(stream, q, q_tstride, k, v, kv_tstride, out, H, Lq, Lk, causal);
}
int attn_exact_f16(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride,
uint16_t* out, int H, int Lq, int Lk, int causal) {
return attn_exact_t<uint16_t>(stream, q, q_tstride, k, v, kv_tstride, out, H, Lq, Lk, causal);
}
int has_fast_attn(int device) {
cudaDeviceProp prop{};
@@ -548,26 +596,39 @@ int has_fast_attn(int device) {
#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) {
namespace {
template <typename OT>
int attn_fast_t(void* stream, const void* q, int q_tstride, const void* k, const void* v, int kv_tstride, OT* 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)>>>(
k_attn_wmma<OT><<<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)
if (cudaFuncSetAttribute(k_attn_mma<OT>, 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)>>>(
k_attn_mma<OT><<<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();
}
} // namespace
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) {
return attn_fast_t<float>(stream, q, q_tstride, k, v, kv_tstride, out, H, nq, nkv);
}
int attn_fast_f16(void* stream, const void* q, int q_tstride, const void* k, const void* v, int kv_tstride, uint16_t* out,
int H, int nq, int nkv) {
return attn_fast_t<uint16_t>(stream, q, q_tstride, k, v, kv_tstride, out, H, nq, nkv);
}
int timestep_embedding(void* stream, const float* t, float* emb, int n, int dim, float max_period) {
if (dim % 2 != 0) return 1;
+10
View File
@@ -35,6 +35,16 @@ int has_fast_attn(int device);
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);
// the same with the output as f16 bits (f16_from_f32 of the float the f32 version stores: the bytes dit_gemm's
// conversion pass made of that float), for the kernels whose output only feeds a GEMM
int res_ln_mod_f16(void* stream, float* x, const float* h, const float* g, uint16_t* out, const float* m, int T, int C,
float eps);
int swiglu_f16(void* stream, const float* gu, uint16_t* out, int T, int F);
int attn_exact_f16(void* stream, const float* q, int q_tstride, const void* k, const void* v, int kv_tstride,
uint16_t* out, int H, int Lq, int Lk, int causal);
int attn_fast_f16(void* stream, const void* q, int q_tstride, const void* k, const void* v, int kv_tstride, uint16_t* 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);