radiance 1.10.0

LoRA for image and video generators:
- civitai and Hugging Face adapter files as published: kohya, ComfyUI and diffusers/PEFT key names;
  LoRA, LoCon, LoHa, LoKr and full-weight diffs; DoRA, OFT and Tucker are refused by name
- stacked per request with a strength each, through the `loras` field or <lora:name:strength> tags
  in the prompt; --lora-dir serves every file in a directory, GET /v1/loras lists them, and
  --max-loras / --max-lora-rank size the slots on the card (generators default to rank 64)
- Krea 2, Qwen-Image 2.1, FLUX.3 [klein], MiniMax H3, LTX-2.5, Anima and SDXL

New models:
- Anima (base, aesthetic and turbo): Cosmos-Predict2 DiT with the Qwen3-0.6B text encoder and the
  Qwen-Image VAE, on one card
- Stable Diffusion XL and its single-file finetunes (Illustrious, NoobAI including V-Pred, Pony),
  read as civitai ships them, with the Euler, Euler a and DPM++ 2M samplers

Recipes:
- q38-27b-mxfp4-df2: any bf16 Qwen3.8-27B or finetune at MXFP4 with the DFlash2 drafter
- Krea 2 finetunes from civitai: scripts/krea2_native.py reads Krea's own key names, and
  krea-2-fp8-unscaled keeps a plain-fp8 file's codes exactly

Changes: --max-num-batched-tokens defaults to 2048 (was 8192). Plugin ABI 25: out-of-tree plugins
must be rebuilt.
This commit is contained in:
Deadcode committed 2026-10-20 21:05:16 +02:00
1 parent 685ec5bd85
commit 4246a1dd04
124 files changed
+14326 -387

No files matched your search

+354
View File
@@ -17,6 +17,7 @@
#include "r4d_q8.h"
#include "rad_philox.h"
#include <algorithm>
#include <cmath>
#include <initializer_list>
#include <cstdlib>
@@ -380,6 +381,118 @@ __global__ __launch_bounds__(kT) void flow_euler_kernel(
st[so] = f32_to_bf16(xn);
}
// ---------------------------------------------------------------------------- kd_input, kd_step
// The k-diffusion sampler over a discrete-time denoiser (libref's ref_kd_input / ref_kd_step): the
// lanes hold x = x0 + sigma eps in f32, a thread one element of one entry, every entry's constants
// computed by each of its threads (a handful of f32 operations beside the element's own).
constexpr int kKdEuler = 0, kKdAncestral = 1, kKdDpm2m = 2;
struct KdConst {
float s, sn, w, cskip, cout, sup, sdown, ratio, em, c1, c2;
bool second;
};
__device__ __forceinline__ KdConst kd_const(float s, float sn, float sp, float w, int sampler,
bool first) {
KdConst k{};
k.s = s;
k.sn = sn;
k.w = w;
const float s2p = s * s + 1.0f;
k.cskip = 1.0f / s2p;
k.cout = s / sqrtf(s2p);
if (sampler == kKdAncestral) {
const float s2 = s * s, sn2 = sn * sn;
const float up2 = sn2 * (s2 - sn2) / s2;
float sup = sqrtf(up2);
if (!(sup < sn)) sup = sn;
const float dn2 = sn2 - sup * sup;
k.sup = sup;
k.sdown = sqrtf(dn2 > 0.0f ? dn2 : 0.0f);
} else if (sampler == kKdDpm2m && sn > 0.0f) {
const float t = -logf(s), tn = -logf(sn);
const float h = tn - t;
k.ratio = sn / s;
k.em = expm1f(-h);
if (!first) {
const float r = (t - (-logf(sp))) / h;
k.c2 = 1.0f / (2.0f * r);
k.c1 = 1.0f + k.c2;
k.second = true;
}
}
return k;
}
__device__ __forceinline__ float kd_den(const KdConst& k, bool v_pred, float x, float o) {
return v_pred ? x * k.cskip - o * k.cout : x - k.s * o;
}
__global__ __launch_bounds__(kT) void kd_input_kernel(
const float* __restrict__ sg, const int* __restrict__ pair, const int* __restrict__ lane,
const int* __restrict__ flags, const uint32_t* __restrict__ seed, const int* __restrict__ cu,
float* __restrict__ st, uint16_t* __restrict__ y, int n, int stride, int st_ld, int y_ld) {
const int e = blockIdx.y;
const int pr = pair[e];
if (pr == -2) return;
const int b0 = cu[e];
const int64_t len = cu[e + 1] - b0;
const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x;
if (i >= len * n) return;
const int64_t k = i / n, c = i % n;
const float s = sg[e];
float* xp = st + ((size_t)lane[e] * stride + k) * st_ld + c;
if (flags[e] & 1) *xp = rad_philox_normal(seed_of(seed, e), (uint64_t)i) * sqrtf(1.0f + s * s);
const uint16_t v = f32_to_bf16(*xp * (1.0f / sqrtf(s * s + 1.0f)));
y[(size_t)(b0 + k) * y_ld + c] = v;
if (pr >= 0) y[(size_t)(cu[pr] + k) * y_ld + c] = v;
}
__global__ __launch_bounds__(kT) void kd_step_kernel(
const uint16_t* __restrict__ out, const float* __restrict__ sg, const float* __restrict__ sgn,
const float* __restrict__ sgp, const float* __restrict__ cfg, const int* __restrict__ pair,
const int* __restrict__ lane, const int* __restrict__ flags, const uint32_t* __restrict__ seed,
const int* __restrict__ sampler, const int* __restrict__ step, const int* __restrict__ cu,
float* __restrict__ st, float* __restrict__ hist, float* __restrict__ pv, int n, int stride,
int o_ld, int st_ld, int h_ld, int pv_ld, int v_pred) {
const int e = blockIdx.y;
const int pr = pair[e];
if (pr == -2) return;
const int b0 = cu[e];
const int64_t len = cu[e + 1] - b0;
const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x;
if (i >= len * n) return;
const int64_t k = i / n, c = i % n;
const int f = flags[e], sm = sampler[e];
const KdConst K = kd_const(sg[e], sgn[e], sgp[e], cfg[e], sm, (f & 1) != 0);
const size_t row = (size_t)lane[e] * stride + k;
const float x = st[row * st_ld + c];
float D = kd_den(K, v_pred != 0, x, bf2f(out[(size_t)(b0 + k) * o_ld + c]));
if (pr >= 0) {
const float Du = kd_den(K, v_pred != 0, x, bf2f(out[(size_t)(cu[pr] + k) * o_ld + c]));
D = Du + K.w * (D - Du);
}
if ((f & 4) && pv) pv[row * pv_ld + c] = D;
float xn;
if (sm == kKdEuler) {
xn = x + (K.sn - K.s) * ((x - D) / K.s);
} else if (sm == kKdAncestral) {
xn = x + ((x - D) / K.s) * (K.sdown - K.s);
if (K.sn > 0.0f)
xn += rad_philox_normal_s(seed_of(seed, e), (uint64_t)(uint32_t)(1 + step[e]),
(uint64_t)i) * K.sup;
} else if (sm != kKdDpm2m) {
return;
} else if (K.sn == 0.0f) {
xn = D;
} else {
const float Dd = K.second ? K.c1 * D - K.c2 * hist[row * h_ld + c] : D;
xn = K.ratio * x - K.em * Dd;
}
st[row * st_ld + c] = xn;
hist[row * h_ld + c] = D;
}
// ---------------------------------------------------------------------------- per-channel ops
// The two lists ride in the kernel arguments, whose segment the backend caps at 768 bytes; two
// lists of 64 channels (a latent's) take 512.
@@ -504,6 +617,20 @@ __global__ __launch_bounds__(kT) void to_rgba8_kernel(const uint16_t* __restrict
y[i] = (uint8_t)rintf(u * 255.0f);
}
// ---------------------------------------------------------------------------- gelu_quick
// CLIP's quick_gelu, libref's three roundings: a workgroup a row, a thread an element.
template <typename T>
__global__ __launch_bounds__(kT) void gelu_quick_kernel(const T* __restrict__ x, T* __restrict__ y,
int n, int x_ld, int y_ld) {
const int r = blockIdx.x;
for (int c = threadIdx.x; c < n; c += kT) {
const float v = ca_ld(x, (size_t)r * x_ld + c);
const float a = ca_rd(y, 1.702f * v);
const float s = ca_rd(y, 1.0f / (1.0f + expf(-a)));
ca_st(y, (int64_t)r * y_ld + c, v * s);
}
}
__global__ __launch_bounds__(kT) void gelu_tanh_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int n, int x_ld, int y_ld) {
const int r = blockIdx.x;
@@ -698,6 +825,91 @@ __global__ __launch_bounds__(kT) void conv_direct_kernel(
y[(size_t)oy * y_ld + (size_t)ox * cout + co] = f32_to_bf16(acc + bf2f(bias[co]));
}
// ---------------------------------------------------------------------------- im2col_nhwc
// conv2d_nhwc's receptive fields as rows: y[oy Wo + ox][(ci k + i) k + j] = the input at tap
// (i, j) of output pixel (oy, ox), channel ci. A block is a run of IC_TW output pixels of one
// output row and IC_CC input channels: it stages the k input rows those pixels read (through the
// upsample and the zero padding) in LDS channel-major, [cl][i][xw], 16 bytes of NHWC channels a
// load, then writes each pixel's cc k k columns -- one contiguous run of its y row -- VW elements a
// thread, so both the reads and the writes are coalesced. KS is k at compile time (3 and 1), 0 for
// any other. Values are copied bit for bit.
constexpr int IC_TW = 32;
constexpr int IC_CC = 64;
template <int KS, int VW>
__global__ __launch_bounds__(kT) void im2col_nhwc_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo,
int k_rt, int stride, int up, int pt, int pl, int64_t x_ld, int64_t y_ld, int vec) {
extern __shared__ uint16_t ic_lds[];
const int k = KS ? KS : k_rt, kk = k * k;
const int ox0 = blockIdx.x * IC_TW, oy = blockIdx.y, c0 = blockIdx.z * IC_CC;
const int cc = min(IC_CC, cin - c0), nq = min(IC_TW, Wo - ox0);
const int W = (IC_TW - 1) * stride + k;
const int iy0 = oy * stride - pt, ix0 = ox0 * stride - pl;
const int sites = k * W;
const int tid = threadIdx.x;
if (vec) {
const int groups = cc >> 3;
for (int u = tid; u < sites * groups; u += kT) {
const int g = u % groups, site = u / groups;
const int i = site / W, xw = site - i * W;
const int iy = iy0 + i, ix = ix0 + xw;
uint4 v = make_uint4(0, 0, 0, 0);
if (iy >= 0 && iy < Hv && ix >= 0 && ix < Wv)
v = *(const uint4*)(x + (size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin + c0 +
g * 8);
const uint32_t w4[4] = { v.x, v.y, v.z, v.w };
#pragma unroll
for (int e = 0; e < 8; ++e)
ic_lds[((g * 8 + e) * k + i) * W + xw] =
(uint16_t)(e & 1 ? w4[e >> 1] >> 16 : w4[e >> 1] & 0xffffu);
}
} else {
for (int u = tid; u < sites * cc; u += kT) {
const int cl = u % cc, site = u / cc;
const int i = site / W, xw = site - i * W;
const int iy = iy0 + i, ix = ix0 + xw;
uint16_t v = 0;
if (iy >= 0 && iy < Hv && ix >= 0 && ix < Wv)
v = x[(size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin + c0 + cl];
ic_lds[(cl * k + i) * W + xw] = v;
}
}
__syncthreads();
/* The block's pixels' runs as one list of VW-element pieces, so every thread stores whatever
* the run length; a thread's (pixel, piece) advances by the block each pass, without a
* division. */
const int span = cc * kk, pieces = span / VW;
uint16_t* yb = y + (size_t)((int64_t)oy * Wo + ox0) * y_ld + (size_t)c0 * kk;
int q = tid / pieces, pc = tid - q * pieces;
for (; q < nq;) {
const int t = pc * VW;
uint16_t* yr = yb + (size_t)q * y_ld;
const int xq = q * stride;
uint16_t v[VW];
#pragma unroll
for (int e = 0; e < VW; ++e) {
const int te = t + e;
const int cl = te / kk, r = te - cl * kk, i = r / k, j = r - i * k;
v[e] = ic_lds[(cl * k + i) * W + xq + j];
}
if constexpr (VW == 8)
*(uint4*)(yr + t) = make_uint4((uint32_t)v[0] | ((uint32_t)v[1] << 16),
(uint32_t)v[2] | ((uint32_t)v[3] << 16),
(uint32_t)v[4] | ((uint32_t)v[5] << 16),
(uint32_t)v[6] | ((uint32_t)v[7] << 16));
else if constexpr (VW == 4)
*(uint2*)(yr + t) = make_uint2((uint32_t)v[0] | ((uint32_t)v[1] << 16),
(uint32_t)v[2] | ((uint32_t)v[3] << 16));
else if constexpr (VW == 2)
*(uint32_t*)(yr + t) = (uint32_t)v[0] | ((uint32_t)v[1] << 16);
else
yr[t] = v[0];
pc += kT;
while (pc >= pieces) { pc -= pieces; ++q; }
}
}
inline int st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); }
inline unsigned blocks_for(int64_t n) { return (unsigned)((n + kT - 1) / kT); }
@@ -1073,6 +1285,72 @@ extern "C" int r4d_rad_flow_euler(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_kd_input(const RadArgs* a, RadStream s) {
const RadTensor *sg = r4d_opt(a, 0), *pair = r4d_opt(a, 1), *lane = r4d_opt(a, 2);
const RadTensor *fl = r4d_opt(a, 3), *seed = r4d_opt(a, 4), *cu = r4d_opt(a, 5);
const RadTensor *st = r4d_opt(a, 6), *y = r4d_opt(a, 7);
if (!sg || !pair || !lane || !fl || !seed || !cu || !st || !y) return R4D_NO(RAD_E_INVAL);
if (st->dtype != RAD_F32 || !is_bf16(y) || sg->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0);
long long rs = 0, ry = 0;
const long long sl = r4d_rows_pitch(st, n, &rs), yl = r4d_rows_pitch(y, n, &ry);
if (sl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE);
const long long n_seq = r4d_numel(cu) - 1;
if (n <= 0 || stride <= 0 || n_seq <= 0 || rs < stride) return R4D_NO(RAD_E_SHAPE);
/* One scalar of each kind an entry, two seed words. A lane's rows, a pair's entry and a
* repaint flag (device data) are not checked. */
for (const RadTensor* e : { sg, pair, lane, fl })
if (r4d_numel(e) < n_seq) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(seed) < 2 * n_seq) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(kd_input_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0,
(hipStream_t)s, (const float*)sg->data, (const int*)pair->data,
(const int*)lane->data, (const int*)fl->data, (const uint32_t*)seed->data,
(const int*)cu->data, (float*)st->data, (uint16_t*)y->data, (int)n,
(int)stride, (int)sl, (int)yl);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_kd_step(const RadArgs* a, RadStream s) {
const RadTensor *o = r4d_opt(a, 0), *sg = r4d_opt(a, 1), *sgn = r4d_opt(a, 2);
const RadTensor *sgp = r4d_opt(a, 3), *cfg = r4d_opt(a, 4), *pair = r4d_opt(a, 5);
const RadTensor *lane = r4d_opt(a, 6), *fl = r4d_opt(a, 7), *seed = r4d_opt(a, 8);
const RadTensor *smp = r4d_opt(a, 9), *stp = r4d_opt(a, 10), *cu = r4d_opt(a, 11);
const RadTensor *st = r4d_opt(a, 12), *hs = r4d_opt(a, 13), *pv = r4d_opt(a, 14);
if (!o || !sg || !sgn || !sgp || !cfg || !pair || !lane || !fl || !seed || !smp || !stp || !cu ||
!st || !hs)
return R4D_NO(RAD_E_INVAL);
if (!is_bf16(o) || st->dtype != RAD_F32 || hs->dtype != RAD_F32 ||
(pv && pv->dtype != RAD_F32))
return R4D_NO(RAD_E_DTYPE);
const char* pred = r4d_gets(a, "pred");
const int v_pred = pred && !std::strcmp(pred, "v");
if (!v_pred && (!pred || std::strcmp(pred, "eps"))) return R4D_NO(RAD_E_INVAL);
const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0);
long long ro = 0, rs = 0, rh = 0, rp = 0;
const long long ol = r4d_rows_pitch(o, n, &ro), sl = r4d_rows_pitch(st, n, &rs);
const long long hl = r4d_rows_pitch(hs, n, &rh), pl = pv ? r4d_rows_pitch(pv, n, &rp) : 0;
if (ol < 0 || sl < 0 || hl < 0 || pl < 0) return R4D_NO(RAD_E_STRIDE);
const long long n_seq = r4d_numel(cu) - 1;
if (n <= 0 || stride <= 0 || n_seq <= 0 || rs < stride || rh < rs || (pv && rp < rs))
return R4D_NO(RAD_E_SHAPE);
/* One scalar of each kind an entry, two seed words. A lane's rows, a pair's entry, the
* sampler ids and the flags (device data) are not checked here: the kernel leaves the lane of
* an entry whose sampler it does not know, and writes no preview without the operand, where
* libref refuses both. */
for (const RadTensor* e : { sg, sgn, sgp, cfg, pair, lane, fl, smp, stp })
if (r4d_numel(e) < n_seq) return R4D_NO(RAD_E_SHAPE);
if (r4d_numel(seed) < 2 * n_seq) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(kd_step_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT), 0,
(hipStream_t)s, (const uint16_t*)o->data, (const float*)sg->data,
(const float*)sgn->data, (const float*)sgp->data, (const float*)cfg->data,
(const int*)pair->data, (const int*)lane->data, (const int*)fl->data,
(const uint32_t*)seed->data, (const int*)smp->data, (const int*)stp->data,
(const int*)cu->data, (float*)st->data, (float*)hs->data,
pv ? (float*)pv->data : nullptr, (int)n, (int)stride, (int)ol, (int)sl,
(int)hl, (int)pl, v_pred);
return st_of(hipGetLastError());
}
/* Both rows: x and y bf16 (chan_affine_bf16) or both f32 (chan_affine_f32). `round` 0 keeps the
* lists and the arithmetic in f32. */
extern "C" int r4d_rad_chan_affine(const RadArgs* a, RadStream s) {
@@ -1175,6 +1453,61 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_im2col_nhwc(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE);
const long long cin = r4d_geti_or(a, "cin", 0), k = r4d_geti_or(a, "k", 0);
const long long stride = r4d_geti_or(a, "stride", 1), up = r4d_geti_or(a, "up", 1);
const char* pad = r4d_gets(a, "pad");
const bool down = pad && !std::strcmp(pad, "down");
const bool causal = pad && !std::strcmp(pad, "causal");
if (pad && !down && !causal && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL);
if (cin <= 0 || k <= 0 || k > 7 || stride <= 0 || stride > 2 || up <= 0 || up > 2)
return R4D_NO(RAD_E_SHAPE);
long long Hin = 0, Win = 0;
if (!image_of(x, cin, &Hin, &Win, true)) return R4D_NO(RAD_E_SHAPE);
const long long Hv = Hin * up, Wv = Win * up;
const long long pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2;
const long long pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
const long long Ho = (Hv + pt + pb - k) / stride + 1, Wo = (Wv + pl + pr - k) / stride + 1;
const long long KK = cin * k * k;
long long rows = 0;
const long long y_ld = r4d_rows_pitch(y, KK, &rows);
if (y_ld < 0 || y->stride[y->rank - 1] != 1) return R4D_NO(RAD_E_STRIDE);
if (Ho <= 0 || Wo <= 0 || rows != Ho * Wo || Ho > 65535 || Ho * Wo * y_ld >= (1ll << 40))
return R4D_NO(RAD_E_SHAPE);
/* 16-byte channel loads where every chunk's channels start on one; the widest store every
* chunk's run, the row pitch and the base allow. */
const long long tail = cin % IC_CC ? cin % IC_CC : IC_CC;
const int vec = cin % 8 == 0 && x->stride[0] % 8 == 0 && !((uintptr_t)x->data & 15);
auto fits = [&](long long vw) {
return (std::min((long long)IC_CC, cin) * k * k) % vw == 0 && (tail * k * k) % vw == 0 &&
y_ld % vw == 0 && !((uintptr_t)y->data & (2 * vw - 1));
};
const int VW = fits(8) ? 8 : fits(4) ? 4 : fits(2) ? 2 : 1;
const long long W = (IC_TW - 1) * stride + k;
const size_t lds = (size_t)(std::min((long long)IC_CC, cin) * k * W) * sizeof(uint16_t);
const dim3 grid((unsigned)((Wo + IC_TW - 1) / IC_TW), (unsigned)Ho,
(unsigned)((cin + IC_CC - 1) / IC_CC));
#define R4D_IC(KS, V) \
hipLaunchKernelGGL((im2col_nhwc_kernel<KS, V>), grid, dim3(kT), lds, (hipStream_t)s, \
(const uint16_t*)x->data, (uint16_t*)y->data, (int)Hv, (int)Wv, (int)cin, \
(int)Wo, (int)k, (int)stride, (int)up, (int)pt, (int)pl, \
(int64_t)x->stride[0], (int64_t)y_ld, vec)
#define R4D_IC_K(V) \
if (k == 3) R4D_IC(3, V); \
else if (k == 1) R4D_IC(1, V); \
else R4D_IC(0, V)
if (VW == 8) { R4D_IC_K(8); }
else if (VW == 4) { R4D_IC_K(4); }
else if (VW == 2) { R4D_IC_K(2); }
else { R4D_IC_K(1); }
#undef R4D_IC_K
#undef R4D_IC
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_l2norm_chan(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *g = r4d_opt(a, 1), *y = r4d_opt(a, 2);
if (!x || !g || !y) return R4D_NO(RAD_E_INVAL);
@@ -1246,6 +1579,27 @@ extern "C" int r4d_rad_to_rgba8(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_gelu_quick(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
const bool f32 = x->dtype == RAD_F32;
if ((!is_bf16(x) && !f32) || y->dtype != x->dtype) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
long long rx = 0, ry = 0;
const long long xl = r4d_rows_pitch(x, n, &rx), yl = r4d_rows_pitch(y, n, &ry);
if (n <= 0 || xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE);
if (ry <= 0 || rx < ry) return R4D_NO(RAD_E_SHAPE);
if (f32)
hipLaunchKernelGGL(gelu_quick_kernel<float>, dim3((unsigned)ry), dim3(kT), 0,
(hipStream_t)s, (const float*)x->data, (float*)y->data, (int)n, (int)xl,
(int)yl);
else
hipLaunchKernelGGL(gelu_quick_kernel<uint16_t>, dim3((unsigned)ry), dim3(kT), 0,
(hipStream_t)s, (const uint16_t*)x->data, (uint16_t*)y->data, (int)n,
(int)xl, (int)yl);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_gelu_tanh(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
+153
View File
@@ -252,6 +252,11 @@ enum {
kExThreads = 256,
kZMax = 16, /* the passes of one tile spread over at most this many blocks */
kZGrid = 256, /* ... and only while the grid is smaller than this */
kMmMT = 128, /* expand_mm: rows a tile, 32 a wave */
kMmNT = 256, /* expand_mm: columns a tile, 128 a wave */
kMmJC = 32, /* expand_mm: j a staged step */
kMmWaves = 8, /* 4 (rows) x 2 (columns) over the tile */
kMmThreads = kMmWaves * 32,
};
struct ShrinkTArgs {
@@ -590,6 +595,119 @@ __global__ __launch_bounds__(kExThreads) void lora_expand_tiled_kernel(ExpandTAr
}
}
/* lora_expand_mm: the same delta on the WMMA, t rounded to bf16, for the passes whose rows are
* many and mostly of one slot (an image or video generator's). One block a (256 columns, 128 rows),
* eight waves, wave w the 32 rows at 32 (w >> 1) and the 128 columns at 128 (w & 1): 2 x 8 WMMA
* tiles. Each 32-wide j step stages t's [128 rows][32 j] (rounded to bf16) and B[s]'s [256 columns]
* [32 j] in LDS, read by every wave; B's fragment is the WMMA's A operand (16 n x 16 j) and t's its
* B (16 j x 16 m), so lane l's eight outputs are row l % 16 of its m tile at columns 8 (l / 16) ..
* +7 -- eight neighbours in y. Rows of a slot not in the pass are staged as zeros and not stored. */
template <int YDT, bool V>
__global__ __launch_bounds__(kMmThreads) void lora_expand_mm_kernel(ExpandTArgs T) {
__shared__ uint16_t ts[kMmMT][kMmJC + 8]; /* +8: rows land on different banks */
__shared__ uint16_t bs[kMmNT][kMmJC + 8];
__shared__ int mm_slot[kMmMT], mm_list[kMmMT];
__shared__ int mm_n;
const ExpandArgs& A = T.b;
const int tid = (int)threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, half = lane >> 4;
const long long nb = (long long)blockIdx.x * kMmNT;
const int mb = (int)blockIdx.y * kMmMT;
const int wm = 32 * (wave >> 1), wn = 128 * (wave & 1);
for (int i = tid; i < kMmMT; i += kMmThreads) {
int s = -1;
if (mb + i < T.M) {
s = A.slot[(long long)(mb + i) * A.slot_st];
if (s < 0 || s >= A.S) s = -1;
}
mm_slot[i] = s;
}
__syncthreads();
if (tid == 0) mm_n = distinct_slots(mm_slot, mm_list, kMmMT);
__syncthreads();
const int npass = mm_n;
for (int p = 0; p < npass; ++p) {
const int s = mm_list[p];
const uint16_t* bp = A.lb + (long long)s * A.lb_s0;
lr_v8f acc[2][8];
for (int b = 0; b < 2; ++b)
for (int a = 0; a < 8; ++a) acc[b][a] = (lr_v8f)(0.0f);
for (int j0 = 0; j0 < A.R; j0 += kMmJC) {
__syncthreads(); /* the last step's readers are done */
/* t: 128 rows x 32 j, one row's 32 a pair of lanes */
for (int i = tid; i < kMmMT * 2; i += kMmThreads) {
const int r = i >> 1, h = (i & 1) * 16;
const bool on = mm_slot[r] == s;
const long long row = (long long)(mb + r) * A.t_rs;
for (int e = 0; e < 16; ++e) {
const int j = j0 + h + e;
ts[r][h + e] = on && j < A.R ? f2bf(A.t[row + (long long)j * A.t_cs]) : (uint16_t)0;
}
}
/* B[s]: 256 columns x 32 j, one column's 32 a pair of lanes */
for (int i = tid; i < kMmNT * 2; i += kMmThreads) {
const int c = i >> 1, h = (i & 1) * 16;
const long long n = nb + c;
lr_v8s f[2];
ld_pool16<V>(bp + (n < A.N ? n : 0) * A.lb_s1, j0 + h, A.R, A.lb_s2, n < A.N, f);
for (int e = 0; e < 16; ++e) bs[c][h + e] = (uint16_t)f[e >> 3][e & 7];
}
__syncthreads();
lr_v8s tf[2][2];
for (int b = 0; b < 2; ++b)
for (int q = 0; q < 2; ++q)
for (int e = 0; e < 8; ++e)
tf[b][q][e] = (short)ts[wm + 16 * b + col][16 * half + 8 * q + e];
for (int a = 0; a < 8; ++a) {
lr_v8s bf[2];
for (int q = 0; q < 2; ++q)
for (int e = 0; e < 8; ++e)
bf[q][e] = (short)bs[wn + 16 * a + col][16 * half + 8 * q + e];
for (int b = 0; b < 2; ++b) {
acc[b][a] = wmma_bf16(bf[0], tf[b][0], acc[b][a]);
acc[b][a] = wmma_bf16(bf[1], tf[b][1], acc[b][a]);
}
}
}
for (int b = 0; b < 2; ++b) {
const int ml = wm + 16 * b + col;
if (mm_slot[ml] != s) continue;
const long long m = mb + ml;
for (int a = 0; a < 8; ++a) {
const long long n0 = nb + wn + 16 * a + 8 * half;
const long long o = m * A.y_rs + n0 * A.y_cs;
const float* scp = A.sc + (long long)s * A.sc_rs;
if (YDT == kBF16 && A.y_cs == 1 && n0 + 8 <= A.N && (((uintptr_t)A.y + 2 * o) & 15) == 0) {
lr_v8s* yp = (lr_v8s*)((uint16_t*)A.y + o);
lr_v8s yv = *yp;
for (int e = 0; e < 8; ++e)
yv[e] = (short)f2bf(bf2f((uint16_t)yv[e]) + scp[(n0 + e) * A.sc_cs] * acc[b][a][e]);
*yp = yv;
continue;
}
for (int e = 0; e < 8; ++e) {
const long long n = n0 + e;
if (n >= A.N) continue;
const float d = scp[n * A.sc_cs] * acc[b][a][e];
const long long oe = m * A.y_rs + n * A.y_cs;
if (YDT == kBF16) {
uint16_t* y = (uint16_t*)A.y + oe;
*y = f2bf(bf2f(*y) + d);
} else if (YDT == kF16) {
uint16_t* y = (uint16_t*)A.y + oe;
*y = f32_to_f16(f16_to_f32(*y) + d);
} else {
float* y = (float*)A.y + oe;
*y = *y + d;
}
}
}
}
}
}
/* ---------------------------------------------------------------- operand reading (host) */
/* `t` read as [rows, cols]: the trailing axes that span `cols` must be one dense run, the leading
@@ -885,6 +1003,13 @@ static void launch_expand_tiled(const ExpandTArgs& P, dim3 grid, RadStream strea
(hipStream_t)stream, P);
}
template <int YDT, bool V>
static void launch_expand_mm(const ExpandTArgs& P, dim3 grid, RadStream stream) {
(void)stream;
R4D_KLAUNCH(R4D_KNAME(lora_expand_mm_kernel<YDT, V>), grid, dim3(kMmThreads),
(hipStream_t)stream, P);
}
} /* namespace r4d_lora */
extern "C" {
@@ -1003,4 +1128,32 @@ int r4d_rad_lora_expand_tiled(const RadArgs* a, RadStream stream) {
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
/* lora_expand_mm: one block a (256 columns, 128 rows); expand_operands reads the same operands. */
int r4d_rad_lora_expand_mm(const RadArgs* a, RadStream stream) {
using namespace r4d_lora;
ExpandArgs P{};
int ydt = 0;
int64_t M = 0;
const int rc = expand_operands(a, &P, &ydt, &M);
if (rc != RAD_OK || M <= 0) return rc;
const int64_t rt = (M + kMmMT - 1) / kMmMT, nt = (P.N + kMmNT - 1) / kMmNT;
if (rt > 65535 || nt > 0x7fffffff) return RAD_E_SHAPE;
ExpandTArgs T{};
T.b = P;
T.M = (int)M;
T.Z = 1;
const bool v = P.lb_s2 == 1 && (uintptr_t)P.lb % 16 == 0 && P.lb_s1 % 8 == 0 &&
P.lb_s0 % 8 == 0;
const dim3 grid((unsigned)nt, (unsigned)rt, 1u);
switch (ydt) {
case kBF16: v ? launch_expand_mm<kBF16, true>(T, grid, stream)
: launch_expand_mm<kBF16, false>(T, grid, stream); break;
case kF16: v ? launch_expand_mm<kF16, true>(T, grid, stream)
: launch_expand_mm<kF16, false>(T, grid, stream); break;
default: v ? launch_expand_mm<kF32, true>(T, grid, stream)
: launch_expand_mm<kF32, false>(T, grid, stream); break;
}
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
} /* extern "C" */
+5
View File
@@ -156,6 +156,7 @@ int r4d_rad_lora_expand (const RadArgs*, RadStream);
int r4d_rad_lora_shrink_wmma (const RadArgs*, RadStream);
int64_t r4d_rad_lora_shrink_wmma_scratch(const RadArgs*);
int r4d_rad_lora_expand_tiled (const RadArgs*, RadStream);
int r4d_rad_lora_expand_mm (const RadArgs*, RadStream);
int r4d_rad_attn_vit (const RadArgs*, RadStream);
int r4d_rad_attn_dense (const RadArgs*, RadStream);
int r4d_rad_seg_sinusoid (const RadArgs*, RadStream);
@@ -179,13 +180,17 @@ int r4d_rad_lane_gather (const RadArgs*, RadStream);
int r4d_rad_lane_store (const RadArgs*, RadStream);
int r4d_rad_randn_lanes (const RadArgs*, RadStream);
int r4d_rad_flow_euler (const RadArgs*, RadStream);
int r4d_rad_kd_input (const RadArgs*, RadStream);
int r4d_rad_kd_step (const RadArgs*, RadStream);
int r4d_rad_chan_affine (const RadArgs*, RadStream);
int r4d_rad_conv2d_nhwc (const RadArgs*, RadStream);
int r4d_rad_im2col_nhwc (const RadArgs*, RadStream);
int r4d_rad_l2norm_chan (const RadArgs*, RadStream);
int r4d_rad_d2s_add (const RadArgs*, RadStream);
int r4d_rad_s2d_avg_add (const RadArgs*, RadStream);
int r4d_rad_to_rgba8 (const RadArgs*, RadStream);
int r4d_rad_gelu_tanh (const RadArgs*, RadStream);
int r4d_rad_gelu_quick (const RadArgs*, RadStream);
int r4d_rad_scatter_add_rows (const RadArgs*, RadStream);
/* r4d_audio.hip */
int r4d_rad_conv1d (const RadArgs*, RadStream);
+88 -7
View File
@@ -2318,6 +2318,21 @@ static const RadOperandSpec oFlowEuler[] = {
{ "inp_lat", RAD_OPD_IN, 1 }, { "inp_mask", RAD_OPD_IN, 1 }, { "state", RAD_OPD_INOUT, 0 },
{ "preview", RAD_OPD_INOUT, 1 },
};
/* The k-diffusion sampler's input and step: `pred` "eps" or "v", the lanes f32. */
static const RadParamSpec pKdStep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("pred"),
P_STR("dtype") };
static const RadOperandSpec oKdInput[] = {
{ "sigma", RAD_OPD_IN, 0 }, { "pair", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 },
{ "flags", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
{ "state", RAD_OPD_INOUT, 0 }, { "y", RAD_OPD_OUT, 0 },
};
static const RadOperandSpec oKdStep[] = {
{ "out", RAD_OPD_IN, 0 }, { "sigma", RAD_OPD_IN, 0 }, { "sigma_next", RAD_OPD_IN, 0 },
{ "sigma_prev", RAD_OPD_IN, 0 }, { "cfg", RAD_OPD_IN, 0 }, { "pair", RAD_OPD_IN, 0 },
{ "lane", RAD_OPD_IN, 0 }, { "flags", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 },
{ "sampler", RAD_OPD_IN, 0 }, { "step", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
{ "state", RAD_OPD_INOUT, 0 }, { "hist", RAD_OPD_INOUT, 0 }, { "preview", RAD_OPD_INOUT, 1 },
};
/* `round` 0 keeps the lists and the arithmetic in f32 (default 1, bf16 lists and roundings). */
static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"),
P_STR("mode"), P_STR("dtype"), P_INTO("round") };
@@ -2329,6 +2344,8 @@ static const RadOperandSpec oConvNhwc[] = {
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pIm2col[] = { P_INT("M"), P_INT("cin"), P_INT("k"), P_INT("stride"),
P_STR("pad"), P_INT("up"), P_STR("dtype") };
static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
static const RadOperandSpec oL2Norm[] = {
{ "x", RAD_OPD_IN, 0 }, { "gamma", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 },
@@ -3231,6 +3248,11 @@ static const RadOpSchema kSchemas[] = {
"y[m, n] = y[m, n] + scale[s, n] * sum_j t[m, j] * lora_b[s, n, j] for each row m "
"whose s = slot[m] is in [0, S), f32 accumulate, one rounding to y's dtype. A base "
"row's `y` is neither read nor written."),
SCHEMA("lora_expand_mm", pLoraExpand, oLoraExpand,
"lora_expand with t rounded to bf16 and the sum over j in any order: y[m, n] = y[m, n] "
"+ scale[s, n] * sum_j bf16(t[m, j]) * lora_b[s, n, j], f32 accumulate, one rounding "
"to y's dtype; a base row's `y` is neither read nor written. A row's bytes may depend "
"on M."),
SCHEMA("ln_mod", pLnMod, oLnMod,
"y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a layer norm with no gain or bias, then the "
"row's sequence's modulation row of `s`."),
@@ -3258,17 +3280,30 @@ static const RadOpSchema kSchemas[] = {
"an image's first step: its lane's rows become its seed's normal stream."),
SCHEMA("flow_euler", pLane, oFlowEuler,
"one Euler step of a flow-matching sampler per entry that moves a lane."),
SCHEMA("kd_input", pLane, oKdInput,
"a k-diffusion sampler's model input per entry that moves a lane: a first step's noise "
"times sqrt(1 + sigma^2) into the lane, then rd(x / sqrt(sigma^2 + 1)) at its rows and "
"its pair's."),
SCHEMA("kd_step", pKdStep, oKdStep,
"one k-diffusion sampler step per entry that moves a lane: the guided clean estimate "
"from an eps or v output, then Euler, Euler ancestral or DPM++ 2M; the lanes f32."),
SCHEMA("chan_affine", pChanAffine, oGenUnary,
"a per-channel affine from two parameter lists of n values; `round` 0 keeps the lists "
"and the arithmetic in f32, rounded once into y."),
SCHEMA("conv2d_nhwc", pConvNhwc, oConvNhwc,
"an image convolution, channels innermost, the sizes read off the operands."),
SCHEMA("im2col_nhwc", pIm2col, oGenUnary,
"conv2d_nhwc's receptive fields as rows: y [Ho * Wo, cin * k * k], column "
"(ci * k + i) * k + j of row oy * Wo + ox the input conv2d_nhwc multiplies weight[o, ci, "
"i, j] by, 0 in the padding."),
SCHEMA("l2norm_chan", pL2Norm, oL2Norm,
"unit-L2 per row, times sqrt(n), times gamma, then `act`: an image decoder's norm."),
SCHEMA("d2s_add", pSpaceDepth, oSpaceDepth, "an upsampling shortcut added in."),
SCHEMA("s2d_avg_add", pSpaceDepth, oSpaceDepth, "a downsampling shortcut added in."),
SCHEMA("to_rgba8", pGenMn, oGenUnary, "decoded pixels in [-1, 1] to bytes."),
SCHEMA("gelu_tanh", pGenMn, oGenUnary, "the tanh approximation of gelu."),
SCHEMA("gelu_quick", pGenMn, oGenUnary,
"CLIP's quick_gelu: a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s)."),
SCHEMA("scatter_add_rows", pGenMn, oScatterAdd, "x[idx[i]] += v[i]; a negative index adds nothing."),
SCHEMA("attn_prefix_self", pAttnPS, oAttnPS,
"attention over a paged prefix and the step's own rows, causal over the own rows or not. "
@@ -4784,14 +4819,14 @@ static const RadConstraint cPatchUnfold[] = { C_IN("dtype", "f32"), C_LE("C", 64
static const RadConstraint cGenAnyFloat[] = { C_IN("dtype", "bf16 f32") };
static const RadConstraint cSnakeAa[] = { C_IN("dtype", "f32"), C_LE("k", 32) };
/* ---- a video latent upscaler (r4d_upscaler.hip). The convolution decodes 3 x 3 x 3 taps as
* constants and reads 16-byte chunks of a voxel row; the group norm puts a thread on an 8-channel
* chunk inside one group, a row's chunks a power of two dividing the 256-thread block (the shim
* checks that and n / groups % 8), and merges at most 256 groups; the temporal convolution keeps
* constants and reads 16-byte chunks of a voxel row; the group norm puts a thread on chunks of 8, 4
* or 2 channels inside one group, a row's chunks spread over at most the 256-thread block (the
* shim checks an even group width), and merges at most 256 groups; the temporal convolution keeps
* its 5-frame window in registers; the fold's lists are kernel arguments, 64 floats at most. */
static const RadConstraint cConv3d[] = { C_IN("dtype", "bf16"), C_EQ("k", 3), C_EQ("kt", 3),
C_DIV("cin", 8) };
static const RadConstraint cGroupNorm[] = { C_IN("dtype", "bf16 f32"), C_DIV("n", 8),
C_LE("n", 2048), C_LE("groups", 256) };
C_LE("n", 8192), C_LE("groups", 256) };
static const RadConstraint cTconvDw[] = { C_IN("dtype", "bf16"), C_EQ("k", 5), C_DIV("n", 8) };
static const RadConstraint cResizeBil[] = { C_IN("dtype", "bf16 f32"), C_DIV("n", 8) };
static const RadConstraint cPatchFold[] = { C_IN("dtype", "bf16 f32"), C_LE("C", 64) };
@@ -4799,6 +4834,8 @@ static const RadConstraint cLnModQ[] = { C_IN("dtype", "bf16"), C_DIV("n", 128),
C_EQ("group", 128) };
/* The lane copies move 32-bit words, so any row of whole words: bf16 latents and an f32 mask. */
static const RadConstraint cGenLanes[] = { C_IN("dtype", "bf16 f32") };
/* gelu_quick: x and y of one dtype, any width and pitch. */
static const RadConstraint cGeluQuick[] = { C_IN("dtype", "bf16 f32") };
/* The two lists are kernel arguments, 64 floats each at most (r4d_gen.hip). */
static const RadConstraint cGenAffine[] = { C_IN("dtype", "bf16"), C_LE("n", 64) };
static const RadConstraint cGenAffineF32[] = { C_IN("dtype", "f32"), C_LE("n", 64) };
@@ -7868,6 +7905,17 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
RAD_DOMAIN_DEVICE, R4D_PRIO_LORA_TILED,
ROW(cLoraExpand), NOTUNE,
nullptr, nullptr, r4d_rad_lora_expand_tiled },
/* The generators' expand (lora_expand_mm): the same delta on the WMMA, for passes of many rows of
* one adapter, where the exact row's scalar sum is most of the adapter's cost. */
{ "lora_expand_mm_wmma", "lora_expand_mm", "gemm",
"y += scale * (bf16(t) B[slot]^T) per row, base rows neither read nor written: WMMA bf16 over "
"64-row x 64-column tiles, four waves of 2 x 2 16 x 16 tiles, one pass a distinct slot of a tile",
"any M and N, 1 <= R <= 65536, 1 <= S <= 2^20; row and column strides of t and y honoured, "
"16-byte pool loads where B's rows are aligned",
"f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y",
RAD_DOMAIN_DEVICE, R4D_PRIO_LORA_TILED,
ROW(cLoraExpand), NOTUNE,
nullptr, nullptr, r4d_rad_lora_expand_mm },
{ "attn_prefix_self_h128_bf16", "attn_prefix_self", "attn",
"attention over a paged prefix and the pass's own rows, causal over the own rows or not",
"head_dim 128, 1/2/4/8 query heads a KV head, a flat grid over the sequences' query blocks; "
@@ -8062,6 +8110,22 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_flow_euler },
{ "kd_input_bf16", "kd_input", "elem",
"a k-diffusion sampler's model input: a first step's noise into the f32 lane, c_in x out",
"any M, row pitches honoured; a thread an element of an entry",
"f32 lanes, bf16 y",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_kd_input },
{ "kd_step_bf16", "kd_step", "elem",
"a k-diffusion sampler step with guidance and preview: Euler, Euler ancestral or DPM++ 2M",
"any M, row pitches honoured; a thread an element of an entry",
"bf16 model output, f32 lanes, history and preview, f32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_kd_step },
{ "chan_affine_bf16", "chan_affine", "elem",
"a per-channel affine from parameter lists; `round` 0 keeps the lists and arithmetic f32",
"any M, row pitches honoured",
@@ -8118,6 +8182,14 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cGenRows8), NOTUNE,
nullptr, nullptr, r4d_rad_gelu_tanh },
{ "gelu_quick_bf16", "gelu_quick", "elem",
"CLIP's quick_gelu, libref's three roundings",
"any M and n, row pitches honoured",
"bf16 or f32 in and out (one dtype), f32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGeluQuick), NOTUNE,
nullptr, nullptr, r4d_rad_gelu_quick },
{ "scatter_add_rows_bf16", "scatter_add_rows", "elem",
"x[idx[i]] += v[i]",
"any M, row pitches honoured",
@@ -8135,6 +8207,15 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, nullptr, r4d_rad_conv2d_nhwc, nullptr, r4d_rad_layout_conv_tap, r4d_rad_relayout_conv_tap,
nullptr, r4d_rad_unrelayout_conv_tap },
{ "im2col_nhwc_bf16", "im2col_nhwc", "elem",
"a convolution's receptive fields as GEMM rows in the weight's (cin, kh, kw) order: 32 output "
"pixels by 64 channels a block, the input rows staged in LDS, coalesced loads and stores",
"k <= 7, stride and up 1 or 2; x rows at their own pitch; y exactly Ho * Wo rows at its pitch",
"bf16 in and out, copied bit for bit",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_im2col_nhwc },
/* -------------------------------------------------------------------------- audio generation */
{ "conv1d_bf16", "conv1d", "conv",
"a 1-D convolution over sequences as an implicit GEMM over (tap, cin), the weight tap-major",
@@ -8392,9 +8473,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
{ "group_norm", "group_norm", "norm",
"GroupNorm over all rows in three launches: per-part (count, mean, M2), their merge to mean and "
"rstd, then the affine, modulation and SiLU a thread an 8-channel chunk",
"n % 8 == 0 with n / 8 a power of two up to 256, n / groups % 8 == 0, groups <= 256, M n / "
"groups < 2^24; row pitches honoured, y may alias x",
"rstd, then the affine, modulation and SiLU a thread an 8-, 4- or 2-channel chunk",
"n % 8 == 0 up to 8192, an even n / groups, groups <= 256, M n / groups < 2^31; row pitches "
"honoured, y may alias x",
"bf16 or f32 rows, bf16 or f32 gain, bias and modulation, f32 statistics",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGroupNorm), NOTUNE,
+339 -5
View File
@@ -8004,6 +8004,60 @@ void conv2d_cases(const Plugin& pl) {
}
}
/* im2col_nhwc against a host unfold, bit for bit: SDXL's widths (a tail of channels past the
* 64-channel chunks, the upsample, both stride-2 paddings), an input whose channels are not a
* multiple of eight (the element loads), a 1x1 and a 5x5 (k at run time), x at a row pitch, and an
* odd output width (the narrowest stores). The y rows past the unfold must stay as they were. */
void im2col_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "im2col_nhwc_bf16");
if (!r) { ok("im2col_nhwc_bf16", false, "row absent"); return; }
struct Case { const char* pad; int64_t cin, k, stride, up, H, W, xpad; };
for (const Case c : { Case{ "same", 320, 3, 1, 1, 40, 37, 0 }, Case{ "same", 200, 3, 1, 2, 9, 13, 0 },
Case{ "same", 640, 3, 2, 1, 22, 17, 0 }, Case{ "down", 64, 3, 2, 1, 10, 14, 0 },
Case{ "same", 4, 3, 1, 1, 33, 35, 0 }, Case{ "same", 6, 3, 1, 1, 7, 9, 2 },
Case{ "same", 96, 1, 1, 1, 11, 7, 8 }, Case{ "same", 72, 5, 1, 1, 12, 15, 0 },
Case{ "causal", 24, 3, 1, 1, 8, 5, 0 } }) {
const bool down = !std::strcmp(c.pad, "down"), causal = !std::strcmp(c.pad, "causal");
const int64_t Hv = c.H * c.up, Wv = c.W * c.up;
const int64_t pt = down ? 0 : causal ? c.k - 1 : c.k / 2, pb = down ? 1 : causal ? 0 : c.k / 2;
const int64_t pl0 = down ? 0 : c.k / 2, pr = down ? 1 : c.k / 2;
const int64_t Ho = (Hv + pt + pb - c.k) / c.stride + 1, Wo = (Wv + pl0 + pr - c.k) / c.stride + 1;
const int64_t KK = c.cin * c.k * c.k, ld = c.W * c.cin + c.xpad;
const std::string nm = fmt("im2col_nhwc_bf16 %s, %lld channels, k %lld, stride %lld, up %lld, "
"%lldx%lld", c.pad, (long long)c.cin, (long long)c.k,
(long long)c.stride, (long long)c.up, (long long)c.H,
(long long)c.W);
std::vector<float> x = randv((size_t)(c.H * ld), 1.0f);
void* dx = up_bf16(x);
std::vector<float> pre((size_t)((Ho * Wo + 1) * KK), -7.5f);
void* dy = up_bf16(pre);
RadTensor tx = T(dx, RAD_BF16, { c.H, c.W * c.cin });
tx.stride[0] = ld;
const int rc = launch(r, { tx, T(dy, RAD_BF16, { Ho * Wo, KK }) },
{ PI("M", Ho * Wo), PI("cin", c.cin), PI("k", c.k),
PI("stride", c.stride), PS("pad", c.pad), PI("up", c.up),
PS("dtype", "bf16") });
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
const std::vector<float> got = down_bf16(dy, pre.size());
int64_t bad = 0;
for (int64_t oy = 0; oy < Ho; ++oy)
for (int64_t ox = 0; ox < Wo; ++ox)
for (int64_t ci = 0; ci < c.cin; ++ci)
for (int64_t i = 0; i < c.k; ++i)
for (int64_t j = 0; j < c.k; ++j) {
const int64_t iy = oy * c.stride + i - pt, ix = ox * c.stride + j - pl0;
const float v = iy < 0 || iy >= Hv || ix < 0 || ix >= Wv
? 0.0f
: x[(size_t)((iy / c.up) * ld + (ix / c.up) * c.cin + ci)];
const int64_t at = (oy * Wo + ox) * KK + (ci * c.k + i) * c.k + j;
bad += got[(size_t)at] != v;
}
for (int64_t e = Ho * Wo * KK; e < (Ho * Wo + 1) * KK; ++e)
bad += got[(size_t)e] != -7.5f;
ok(nm.c_str(), bad == 0, fmt("%lld elements differ", (long long)bad));
}
}
} /* namespace ltx */
/* ---- a video latent upscaler's ops, at MiniMax-H3's shapes ---------------------------------------
@@ -8287,6 +8341,7 @@ void group_norm_cases(const Plugin& pl) {
bool silu, inplace;
float offset; /* added to every value: a mean far from zero */
int64_t pad;
float eps = 1e-5f;
};
for (const G& g : {
/* The target size modulated with SiLU (a block's second norm), then plain with SiLU
@@ -8306,6 +8361,17 @@ void group_norm_cases(const Plugin& pl) {
G{ "2 channels a group", 48 * 8 * 8, 64, 32, false, false, false, 0, true, false, 0.0f, 0 },
G{ "2 channels a group, f32 rows", 777, 64, 32, true, true, true, 2, false, false, 5.0f, 8 },
G{ "4 channels a group, f32", 777, 128, 32, true, true, true, 2, false, false, 20.0f, 8 },
/* SDXL's UNet: 10 to 80 channels a group, a row's chunks not a power of two (160),
* or more than the block (480 and 320 chunks, three and two to a thread); a
* resnet's norm with SiLU at eps 1e-5, a transformer's without at 1e-6. */
G{ "SDXL 320", 128 * 128, 320, 32, false, false, false, 0, true, false, 0.0f, 0 },
G{ "SDXL 640, eps 1e-6", 64 * 64, 640, 32, false, false, false, 0, false, false, 3.0f, 8, 1e-6f },
G{ "SDXL 960 in place", 128 * 128, 960, 32, false, false, false, 0, true, true, 0.0f, 0 },
G{ "SDXL 1280, eps 1e-6", 32 * 32, 1280, 32, false, false, false, 0, false, false, 0.0f, 0, 1e-6f },
G{ "SDXL 1920", 64 * 64, 1920, 32, false, false, false, 0, true, false, -2.0f, 16 },
G{ "SDXL 2560", 32 * 32 + 7, 2560, 32, false, false, true, 2, true, false, 0.0f, 8 },
/* A group of more than 2^24 values: the counts past f32's integers. */
G{ "2^24 values a group", 600 * 1024, 64, 2, false, false, false, 0, true, false, 1.0f, 0 },
}) {
const int64_t M = g.M, n = g.n, ld = n + g.pad, rows = M + 2;
const std::string nm = fmt("group_norm %s: %lld x %lld in %lld groups", g.what,
@@ -8343,12 +8409,12 @@ void group_norm_cases(const Plugin& pl) {
T(db, g.wf ? RAD_F32 : RAD_BF16, { n }), tm,
T(ds, RAD_F32, { g.groups * (2 + 3 * 1024) }), pitched(dy, ydt, M, n, ld) };
const std::vector<RadParam> ps = { PI("M", M), PI("n", n), PI("groups", g.groups),
PF("eps", 1e-5), PS("act", g.silu ? "silu" : "none"),
PF("eps", g.eps), PS("act", g.silu ? "silu" : "none"),
PS("dtype", g.xf ? "f32" : "bf16") };
const int rc = launch(r, ts, ps);
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
std::vector<float> want, mean, rstd;
gn_ref(x, M, n, g.groups, w, b, g.mod ? &mod : nullptr, g.silu, 1e-5f, !g.yf, &want,
gn_ref(x, M, n, g.groups, w, b, g.mod ? &mod : nullptr, g.silu, g.eps, !g.yf, &want,
&mean, &rstd);
const size_t yel = (size_t)(rows * ld);
const std::vector<float> yall = g.yf ? down_f32(dy, yel) : down_bf16(dy, yel);
@@ -8395,10 +8461,10 @@ void group_norm_cases(const Plugin& pl) {
}
RadTensor nomod = T(nullptr, RAD_BF16, { 1 });
absent(nomod);
ok("group_norm refuses 12 channels a group",
ok("group_norm refuses 3 channels a group",
launch(r, { TA(RAD_BF16, { 4, 96 }), TA(RAD_BF16, { 96 }), TA(RAD_BF16, { 96 }), nomod,
TA(RAD_F32, { 8 * 3074 }), TA(RAD_BF16, { 4, 96 }) },
{ PI("M", 4), PI("n", 96), PI("groups", 8), PF("eps", 1e-5), PS("act", "none"),
TA(RAD_F32, { 32 * 3074 }), TA(RAD_BF16, { 4, 96 }) },
{ PI("M", 4), PI("n", 96), PI("groups", 32), PF("eps", 1e-5), PS("act", "none"),
PS("dtype", "bf16") }) == RAD_E_SHAPE);
}
@@ -9474,6 +9540,165 @@ void attn_long_case(const Plugin& pl, const char* name, int64_t hd, int64_t nh,
check(nm + " numerics", got, want, 2e-2);
}
/* ---- SDXL's: CLIP-L's activation and the k-diffusion sampler, against a host port of libref's
* arithmetic (libref/ref_gen.cpp). */
void gelu_quick_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "gelu_quick_bf16");
if (!r) { ok("gelu_quick_bf16", false, "row absent"); return; }
const int64_t M = 77, n = 3072, ld = 3080;
std::vector<float> x = randv((size_t)(M * ld), 4.0f);
void* dx = up_bf16(x);
void* dy = dalloc((size_t)(M * n) * 2);
RadTensor tx = T(dx, RAD_BF16, { M, n });
tx.stride[0] = ld;
const int rc = launch(r, { tx, T(dy, RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PS("dtype", "bf16") });
if (rc != RAD_OK) { ok("gelu_quick_bf16", false, "rc " + std::to_string(rc)); return; }
std::vector<float> want((size_t)(M * n));
for (int64_t m = 0; m < M; ++m)
for (int64_t c = 0; c < n; ++c) {
const float v = x[(size_t)(m * ld + c)];
const float a = bfr(1.702f * v), s = bfr(1.0f / (1.0f + std::exp(-a)));
want[(size_t)(m * n + c)] = bfr(v * s);
}
check("gelu_quick_bf16 over pitched rows", down_bf16(dy, want.size()), want, 4e-3);
}
/* The host port of kd_step's per-element arithmetic for one entry. */
struct KdHost {
float s, sn, w, cskip, cout, sup = 0, sdown = 0, ratio = 0, em = 0, c1 = 0, c2 = 0;
bool second = false;
KdHost(float s_, float sn_, float sp, float w_, int sampler, bool first)
: s(s_), sn(sn_), w(w_) {
const float s2p = s * s + 1.0f;
cskip = 1.0f / s2p;
cout = s / std::sqrt(s2p);
if (sampler == 1) {
const float s2 = s * s, sn2 = sn * sn;
float u = std::sqrt(sn2 * (s2 - sn2) / s2);
if (!(u < sn)) u = sn;
sup = u;
const float d2 = sn2 - u * u;
sdown = std::sqrt(d2 > 0.0f ? d2 : 0.0f);
} else if (sampler == 2 && sn > 0.0f) {
const float t = -std::log(s), h = -std::log(sn) - t;
ratio = sn / s;
em = std::expm1(-h);
if (!first) {
const float rr = (t + std::log(sp)) / h;
c2 = 1.0f / (2.0f * rr);
c1 = 1.0f + c2;
second = true;
}
}
}
float den(bool v, float x, float o) const { return v ? x * cskip - o * cout : x - s * o; }
float next(int sampler, float x, float D, float hist, float nz) const {
if (sampler == 0) return x + (sn - s) * ((x - D) / s);
if (sampler == 1) return x + ((x - D) / s) * (sdown - s) + (sn > 0.0f ? nz * sup : 0.0f);
if (sn == 0.0f) return D;
return ratio * x - em * (second ? c1 * D - c2 * hist : D);
}
};
/* Five entries over lanes of 300 rows by 4 channels, an image of 280 latent rows each: entry 0 a
* first step guided against entry 1 (parked), entries 2-4 unguided at later steps. kd_input fills
* entry 0's lane and writes both entries' rows; kd_step takes every sampler at each prediction. */
void kd_cases(const Plugin& pl) {
const RadKernelInfo* ri = find(pl, "kd_input_bf16");
const RadKernelInfo* rs = find(pl, "kd_step_bf16");
if (!ri || !rs) { ok("kd_input_bf16 / kd_step_bf16", false, "row absent"); return; }
const int64_t n = 4, stride = 300, len = 280, S = 5, R = S * len, LR = S * stride;
const std::vector<int32_t> pair = { 1, -2, -1, -1, -1 }, lane = { 3, 0, 1, 4, 2 };
std::vector<int32_t> cu(S + 1);
for (int64_t e = 0; e <= S; ++e) cu[(size_t)e] = (int32_t)(e * len);
const std::vector<uint32_t> seeds = { 0x9e3779b9u, 7u, 0, 0, 5u, 1u, 77u, 0, 0xdeadbeefu, 3u };
std::vector<int32_t> sdw(seeds.begin(), seeds.end());
const std::vector<float> sg = { 14.6f, 14.6f, 3.5f, 1.25f, 0.4f };
const std::vector<float> sgn = { 11.0f, 11.0f, 2.0f, 0.7f, 0.0f };
const std::vector<float> sgp = { 0.0f, 0.0f, 5.0f, 2.0f, 0.9f };
const std::vector<float> cfg = { 6.0f, 1.0f, 1.0f, 1.0f, 1.0f };
const std::vector<int32_t> step = { 0, 0, 7, 4, 20 };
std::vector<float> st0 = randv((size_t)(LR * n), 2.0f);
/* ---- kd_input */
void* dst = up_f32(st0);
void* dy = dalloc((size_t)(R * n) * 2);
const std::vector<int32_t> fl_in = { 1, 0, 0, 0, 0 };
int rc = launch(ri, { T(up_f32(sg), RAD_F32, { S }), TI32({ S }, pair), TI32({ S }, lane),
TI32({ S }, fl_in), T(up_i32(sdw), RAD_U32, { 2 * S }),
TI32({ S + 1 }, cu), T(dst, RAD_F32, { LR, n }),
T(dy, RAD_BF16, { R, n }) },
{ PI("M", R), PI("n", n), PI("stride", stride), PS("dtype", "bf16") });
if (rc != RAD_OK) { ok("kd_input_bf16", false, "rc " + std::to_string(rc)); return; }
std::vector<float> st1 = st0, ywant((size_t)(R * n), 0.0f);
for (int64_t e = 0; e < S; ++e) {
if (pair[(size_t)e] == -2) continue;
const float s = sg[(size_t)e];
const uint64_t sd = (uint64_t)seeds[(size_t)(2 * e)] | ((uint64_t)seeds[(size_t)(2 * e + 1)] << 32);
for (int64_t k = 0; k < len; ++k)
for (int64_t c = 0; c < n; ++c) {
float& x = st1[(size_t)(((int64_t)lane[(size_t)e] * stride + k) * n + c)];
if (fl_in[(size_t)e] & 1)
x = rad_philox_normal(sd, (uint64_t)(k * n + c)) * std::sqrt(1.0f + s * s);
const float v = x * (1.0f / std::sqrt(s * s + 1.0f));
ywant[(size_t)((cu[(size_t)e] + k) * n + c)] = v;
if (pair[(size_t)e] >= 0) ywant[(size_t)((cu[(size_t)pair[(size_t)e]] + k) * n + c)] = v;
}
}
check_f32("kd_input_bf16 lanes", down_f32(dst, st1.size()), st1, 1e-6);
check("kd_input_bf16 model input", down_bf16(dy, ywant.size()), ywant, 4e-3);
/* ---- kd_step, each sampler for every entry, both predictions */
for (const bool v_pred : { false, true })
for (int smp = 0; smp < 3; ++smp) {
std::vector<float> out = randv((size_t)(R * n), 1.5f), hs = randv((size_t)(LR * n), 1.0f);
void* ds = up_f32(st1);
void* dh = up_f32(hs);
void* dp = dalloc((size_t)(LR * n) * 4);
const std::vector<int32_t> fl = { 5, 0, 0, 1, 0 };
const std::vector<int32_t> sm(S, smp);
const int rc2 = launch(rs, { T(up_bf16(out), RAD_BF16, { R, n }),
T(up_f32(sg), RAD_F32, { S }), T(up_f32(sgn), RAD_F32, { S }),
T(up_f32(sgp), RAD_F32, { S }), T(up_f32(cfg), RAD_F32, { S }),
TI32({ S }, pair), TI32({ S }, lane), TI32({ S }, fl),
T(up_i32(sdw), RAD_U32, { 2 * S }), TI32({ S }, sm),
TI32({ S }, step), TI32({ S + 1 }, cu),
T(ds, RAD_F32, { LR, n }), T(dh, RAD_F32, { LR, n }),
T(dp, RAD_F32, { LR, n }) },
{ PI("M", R), PI("n", n), PI("stride", stride),
PS("pred", v_pred ? "v" : "eps"), PS("dtype", "bf16") });
const std::string nm = fmt("kd_step_bf16 sampler %d %s", smp, v_pred ? "v" : "eps");
if (rc2 != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc2)); return; }
std::vector<float> sw = st1, hw = hs, pw((size_t)(LR * n), 0.0f);
for (int64_t e = 0; e < S; ++e) {
const int32_t pr = pair[(size_t)e];
if (pr == -2) continue;
const KdHost K(sg[(size_t)e], sgn[(size_t)e], sgp[(size_t)e], cfg[(size_t)e], smp,
(fl[(size_t)e] & 1) != 0);
const uint64_t sd = (uint64_t)seeds[(size_t)(2 * e)] | ((uint64_t)seeds[(size_t)(2 * e + 1)] << 32);
for (int64_t k = 0; k < len; ++k)
for (int64_t c = 0; c < n; ++c) {
const size_t li = (size_t)(((int64_t)lane[(size_t)e] * stride + k) * n + c);
const float x = sw[li];
float D = K.den(v_pred, x, out[(size_t)((cu[(size_t)e] + k) * n + c)]);
if (pr >= 0) {
const float Du = K.den(v_pred, x, out[(size_t)((cu[(size_t)pr] + k) * n + c)]);
D = Du + K.w * (D - Du);
}
if (fl[(size_t)e] & 4) pw[li] = D;
const float nz = rad_philox_normal_s(sd, (uint64_t)(uint32_t)(1 + step[(size_t)e]),
(uint64_t)(k * n + c));
sw[li] = K.next(smp, x, D, hw[li], nz);
hw[li] = D;
}
}
check_f32(nm + " lanes", down_f32(ds, sw.size()), sw, 1e-5);
check_f32(nm + " history", down_f32(dh, hw.size()), hw, 1e-5);
if (smp == 0) check_f32(nm + " preview", down_f32(dp, pw.size()), pw, 1e-5);
}
}
} /* namespace vg */
/* ---- video sparse attention: vsa_select and attn_vsa against a host port of their contract
@@ -16227,6 +16452,96 @@ static void attn_perf(const Plugin& pl, int64_t M, int64_t H, int iters) {
dfree_all();
}
/* SDXL's UNet convolutions at 1024 x 1024 (a 128 x 128 latent): the implicit GEMM against the
* unfold and a GEMM over the checkpoint's own weight, which runtime LoRA can attach to. */
static void conv_perf(const Plugin& pl, int iters) {
if (iters <= 0) iters = 20;
const RadKernelInfo* rc = find(pl, "conv2d_nhwc_bf16");
const RadKernelInfo* ri = find(pl, "im2col_nhwc_bf16");
const RadKernelInfo* rg = find(pl, "gemm_bf16_nt_bias_tiled");
if (!rc || !ri || !rg) { std::printf("conv timing: a row is absent\n"); return; }
auto rand_fill = [](void* d, size_t bytes) {
const size_t chunk = std::min<size_t>(bytes, (size_t)16 << 20);
std::vector<uint16_t> h(chunk / 2);
for (size_t i = 0; i < h.size(); ++i) h[i] = st_rand_bf16((uint32_t)i);
for (size_t off = 0; off < bytes; off += chunk)
st_memcpy((uint8_t*)d + off, h.data(), std::min(chunk, bytes - off), hipMemcpyHostToDevice);
};
auto time_row = [&](const RadKernelInfo* r, std::vector<RadTensor> ts, std::vector<RadParam> ps)
-> double {
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
a.world_size = 1;
const int code = r->launch(&a, nullptr);
if (code != RAD_OK) return (double)code;
if (st_stream_sync(nullptr) != hipSuccess) return -1000.0;
return st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr);
};
struct C { int64_t side, cin, cout, stride, up; };
static const C kC[] = {
{ 128, 320, 320, 1, 1 }, { 128, 960, 320, 1, 1 }, { 128, 640, 320, 1, 1 },
{ 64, 640, 640, 1, 2 }, { 128, 320, 320, 2, 1 },
{ 64, 320, 640, 1, 1 }, { 64, 640, 640, 1, 1 }, { 64, 1920, 640, 1, 1 },
{ 64, 1280, 640, 1, 1 }, { 64, 960, 640, 1, 1 }, { 32, 1280, 1280, 1, 2 },
{ 64, 640, 640, 2, 1 },
{ 32, 640, 1280, 1, 1 }, { 32, 1280, 1280, 1, 1 }, { 32, 2560, 1280, 1, 1 },
{ 32, 1920, 1280, 1, 1 },
};
std::printf("SDXL's 3x3 convolutions at 1024 x 1024, %d launches each: conv2d_nhwc_bf16 "
"against im2col_nhwc_bf16 + gemm_bf16_nt_bias_tiled\n", iters);
std::printf(" %-28s %10s %10s %10s %10s %7s\n", "input -> output, channels", "conv us",
"im2col us", "gemm us", "sum us", "ratio");
double tc = 0, ti = 0, tg = 0;
for (const C& c : kC) {
const int64_t Hin = c.side, Hv = Hin * c.up, Ho = (Hv + 2 - 3) / c.stride + 1, k = 3;
const int64_t P = Ho * Ho, K = c.cin * k * k;
void* dx = dalloc((size_t)(Hin * Hin * c.cin) * 2);
void* dw = dalloc((size_t)(c.cout * K) * 2);
void* db = dalloc((size_t)c.cout * 2);
void* dc = dalloc((size_t)(P * K) * 2);
void* dy = dalloc((size_t)(P * c.cout) * 2);
if (!dx || !dw || !db || !dc || !dy) { std::printf(" hipMalloc failed\n"); dfree_all(); continue; }
rand_fill(dx, (size_t)(Hin * Hin * c.cin) * 2);
rand_fill(dw, (size_t)(c.cout * K) * 2);
rand_fill(db, (size_t)c.cout * 2);
const std::vector<RadParam> pc = { PI("M", P), PI("cin", c.cin), PI("cout", c.cout),
PI("k", k), PI("stride", c.stride), PS("pad", "same"),
PI("up", c.up), PS("dtype", "bf16") };
const double uc = time_row(rc, { T(dx, RAD_BF16, { Hin, Hin * c.cin }),
T(dw, RAD_BF16, { c.cout, c.cin, k, k }),
T(db, RAD_BF16, { c.cout }), T(dy, RAD_BF16, { Ho, Ho * c.cout }) },
pc);
const std::vector<RadParam> pi = { PI("M", P), PI("cin", c.cin), PI("k", k),
PI("stride", c.stride), PS("pad", "same"), PI("up", c.up),
PS("dtype", "bf16") };
const double ui = time_row(ri, { T(dx, RAD_BF16, { Hin, Hin * c.cin }),
T(dc, RAD_BF16, { P, K }) }, pi);
RadTensor tres = T(nullptr, RAD_BF16, { 1 });
absent(tres);
const double ug = time_row(rg, { T(dc, RAD_BF16, { P, K }), T(dw, RAD_BF16, { c.cout, K }),
T(db, RAD_BF16, { c.cout }), tres,
T(dy, RAD_BF16, { P, c.cout }) },
{ PI("M", P), PI("N", c.cout), PI("K", K), PS("dtype", "bf16") });
const std::string nm = fmt("%lldx%lld%s -> %lldx%lld, %lld -> %lld", (long long)Hin,
(long long)Hin, c.up == 2 ? " up2" : "", (long long)Ho,
(long long)Ho, (long long)c.cin, (long long)c.cout);
if (uc < 0 || ui < 0 || ug < 0) {
std::printf(" %-28s rc %d / %d / %d\n", nm.c_str(), (int)uc, (int)ui, (int)ug);
} else {
std::printf(" %-28s %10.1f %10.1f %10.1f %10.1f %7.2f\n", nm.c_str(), uc, ui, ug,
ui + ug, (ui + ug) / uc);
tc += uc;
ti += ui;
tg += ug;
}
dfree_all();
}
std::printf(" %-28s %10.1f %10.1f %10.1f %10.1f %7.2f\n", "total", tc, ti, tg, ti + tg,
(ti + tg) / tc);
}
static void video_perf(const Plugin& pl, int iters, const char* only) {
if (iters <= 0) iters = 10;
/* One section by name, or every one. */
@@ -24719,6 +25034,7 @@ static void device_phase(const Plugin& pl) {
if (sel("stft_logmel")) ltx::stft_cases(pl);
if (sel("bwe_up")) ltx::bwe_cases(pl);
if (sel("conv2d_nhwc_bf16")) ltx::conv2d_cases(pl);
if (sel("im2col_nhwc_bf16")) ltx::im2col_cases(pl);
if (sel("int_affine")) ltx::int_affine_cases(pl);
if (sel("vsa_select_h128_bf16")) vsa::select_cases(pl);
if (sel("attn_vsa_h128_bf16")) vsa::attn_cases(pl);
@@ -24738,6 +25054,8 @@ static void device_phase(const Plugin& pl) {
if (sel("layernorm_bf16")) vg::norm_f32_rows_cases(pl, true);
if (sel("timestep_embed_f32")) vg::timestep_f32_case(pl);
if (sel("randn_lanes_f32")) vg::randn_f32_case(pl);
if (sel("gelu_quick_bf16")) vg::gelu_quick_cases(pl);
if (sel("kd_input_bf16") || sel("kd_step_bf16")) vg::kd_cases(pl);
if (sel("interleave2_bf16")) vg::interleave2_f32_case(pl);
if (sel("chan_affine_f32")) vg::chan_affine_cases(pl, "chan_affine_f32");
if (sel("chan_affine_bf16")) vg::chan_affine_cases(pl, "chan_affine_bf16");
@@ -25518,6 +25836,8 @@ static void usage(void) {
" decoder's tiles), upscaler (a latent upscaler's 3D convolutions\n"
" beside the bf16 GEMM at the same M, N and K, then its norm and\n"
" elementwise ops); every section without one.\n"
" --perfconv [iters]: SDXL's 3x3 convolutions at 1024 x 1024, conv2d_nhwc against\n"
" im2col_nhwc and the biased GEMM over the unfolded rows.\n"
" --perfvsa [iters] [local]: vsa_select and attn_vsa at 1344 x 768 (38010\n"
" rows, 28 heads), sparsity 0.8 and 0, beside attn_dense over the same\n"
" rows. `local` gives q and k features of the row's grid position, so a\n"
@@ -25591,6 +25911,7 @@ int main(int argc, char** argv) {
long long m16_m = 0, m16_e = 256, m16_k = 10, m16_d = 0;
int m16_it = 20;
int video_it = 0;
int conv_it = 0;
long long attn_m = 0, attn_h = 0;
int attn_it = 5;
int vsa_it = 0;
@@ -25778,6 +26099,9 @@ int main(int argc, char** argv) {
video_it = 10;
if (i + 1 < argc && argv[i + 1][0] != '-') video_it = (int)std::strtol(argv[++i], nullptr, 0);
if (i + 1 < argc && argv[i + 1][0] != '-') video_sec = argv[++i];
} else if (!std::strcmp(argv[i], "--perfconv")) {
conv_it = 20;
if (i + 1 < argc && argv[i + 1][0] != '-') conv_it = (int)std::strtol(argv[++i], nullptr, 0);
} else if (!std::strcmp(argv[i], "--perfvsa")) {
vsa_it = 5;
if (i + 1 < argc && argv[i + 1][0] != '-' && std::strcmp(argv[i + 1], "local"))
@@ -25813,6 +26137,16 @@ int main(int argc, char** argv) {
attn_perf(pl, attn_m, attn_h, attn_it);
#else
skip("attention timing", "built without HIP");
#endif
return 0;
}
if (conv_it) {
if (!load(&pl, path)) return 1;
#ifdef RAD_HAVE_HIP
conv_perf(pl, conv_it);
dfree_all();
#else
skip("convolution timing", "built without HIP");
#endif
return 0;
}
+55 -52
View File
@@ -412,12 +412,15 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
// give the same bytes:
//
// 1. parts: block p takes rows [p rpp, (p + 1) rpp) and writes each group's (count, mean, M2)
// of them to the scratch. A thread keeps one 8-channel chunk of one group over every
// `slots`-th row, summing deviations from its first value (the shift keeps the f32 sums of
// squares from cancelling against a large mean); the block merges its threads' triples per
// group in thread order (Chan's parallel update).
// of them to the scratch. A row is `tpr` threads, each owning `cpt` consecutive CW-channel
// chunks of one group, and the block holds `slots` = 256 / tpr rows at a time (the threads
// past slots * tpr idle). A thread keeps its chunks over every `slots`-th row, summing
// deviations from its first value (the shift keeps the f32 sums of squares from cancelling
// against a large mean); the block merges its threads' triples per group in thread order
// (Chan's parallel update).
// 2. final: block g merges group g's parts, 256 strided runs then a fixed tree, and writes
// stats[2g] = mean and stats[2g + 1] = rstd = 1 / sqrt(M2 / count + eps).
// stats[2g] = mean and stats[2g + 1] = rstd = 1 / sqrt(M2 / count + eps), the count the
// group's exact M n / groups.
// 3. apply: a thread an 8-channel chunk, v = (x - mean) rstd w + b, the modulation and SiLU in
// f32, one rounding.
//
@@ -436,31 +439,33 @@ __device__ __forceinline__ void chan_merge(float& n, float& mean, float& m2, flo
n = nab;
}
/* `cpr_log`: log2 of the chunks a row (n / CW, a power of two dividing the block); `gs8` the
* chunks a group. A chunk is CW channels: 8, or 4 for groups of 4 channels. */
/* A chunk is CW channels (8, 4 or 2: the widest dividing a group). `tpr` threads a row, each over
* `cpt` chunks; `tpg` threads a group (its chunks / cpt). */
template <typename TX, int CW>
__global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
float* __restrict__ stats, int M, int groups,
int cpr_log, int gs8, int ldx, int rpp) {
int tpr, int cpt, int tpg, int ldx, int rpp) {
__shared__ float sh[3][kT];
const int tid = threadIdx.x;
const int cpr = 1 << cpr_log, slots = kT >> cpr_log;
const int c = tid & (cpr - 1), slot = tid >> cpr_log;
const int slots = kT / tpr;
const int c = tid % tpr, slot = tid / tpr;
const int p = blockIdx.x;
const int r0 = p * rpp, r1 = min(M, r0 + rpp);
float cnt = 0.0f, s1 = 0.0f, s2 = 0.0f, shift = 0.0f;
for (int r = r0 + slot; r < r1; r += slots) {
float v[CW];
ldc<CW>(x + (size_t)r * ldx + c * CW, v);
if (cnt == 0.0f) shift = v[0];
if (slot < slots)
for (int r = r0 + slot; r < r1; r += slots)
for (int q = 0; q < cpt; ++q) {
float v[CW];
ldc<CW>(x + (size_t)r * ldx + (c * cpt + q) * CW, v);
if (cnt == 0.0f) shift = v[0];
#pragma unroll
for (int j = 0; j < CW; ++j) {
const float d = v[j] - shift;
s1 += d;
s2 += d * d;
}
cnt += (float)CW;
}
for (int j = 0; j < CW; ++j) {
const float d = v[j] - shift;
s1 += d;
s2 += d * d;
}
cnt += (float)CW;
}
float mean = 0.0f, m2 = 0.0f;
if (cnt > 0.0f) {
const float q = s1 / cnt;
@@ -474,8 +479,8 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
for (int g = tid; g < groups; g += kT) {
float N = 0.0f, Mn = 0.0f, Q = 0.0f;
for (int s = 0; s < slots; ++s)
for (int k = 0; k < gs8; ++k) {
const int t = (s << cpr_log) + g * gs8 + k;
for (int k = 0; k < tpg; ++k) {
const int t = s * tpr + g * tpg + k;
chan_merge(N, Mn, Q, sh[0][t], sh[1][t], sh[2][t]);
}
float* o = stats + 2 * groups + ((size_t)g * kGnParts + p) * 3;
@@ -486,7 +491,7 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
}
__global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats, int groups,
int parts, float eps) {
int parts, float count, float eps) {
__shared__ float sh[3][kT];
const int g = blockIdx.x, tid = threadIdx.x;
const float* P = stats + 2 * groups + (size_t)g * kGnParts * 3;
@@ -507,24 +512,24 @@ __global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats,
__syncthreads();
}
if (tid == 0) {
const float var = sh[2][0] / sh[0][0];
const float var = sh[2][0] / count;
stats[2 * g] = sh[1][0];
stats[2 * g + 1] = 1.0f / sqrtf(var + eps);
}
}
/* `wf`, `bf`: the gain's and bias's dtype is f32; `modk` 0 no modulation, 1 a bf16 row, 2 an f32
* one. x and y may be the same memory: a thread reads its chunk before it writes it. */
* one. A thread is chunk `i % cpr` of row `i / cpr`, `gs8` chunks a group. x and y may be the same
* memory: a thread reads its chunk before it writes it. */
template <typename TX, typename TY, int CW>
__global__ __launch_bounds__(kT) void gn_apply_kernel(
const TX* x, TY* y, const void* __restrict__ w, const void* __restrict__ b,
const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr_log,
const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr,
int gs8, int ldx, int ldy, int wf, int bf, int modk, int silu) {
const int slots = kT >> cpr_log;
const int tid = threadIdx.x;
const int r = blockIdx.x * slots + (tid >> cpr_log);
const long long i = (long long)blockIdx.x * kT + threadIdx.x;
const int r = (int)(i / cpr);
if (r >= M) return;
const int ck = tid & ((1 << cpr_log) - 1), c = ck * CW;
const int ck = (int)(i - (long long)r * cpr), c = ck * CW;
const int g = ck / gs8;
const float mean = stats[2 * g], rstd = stats[2 * g + 1];
float v[CW], wv[CW], bv[CW];
@@ -741,12 +746,6 @@ int parse_f32_list(const char* s, float* out, int max) {
return n;
}
inline int log2_exact(long long v) {
int l = 0;
while ((1ll << l) < v) ++l;
return (1ll << l) == v ? l : -1;
}
} // namespace
// ============================================================== the plugin ABI entry points
@@ -833,14 +832,18 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
if (!std::strcmp(act, "silu")) silu = 1;
else if (std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL);
}
/* A thread a chunk of CW channels inside one group (8; 4 for groups of 4 channels, the
* FLUX.2 VAE's 128 channels in 32 groups; 2 for groups of 2), a row's chunks a power of two
* dividing the 256-thread block. */
/* A chunk is CW channels inside one group: 8, 4 or 2, the widest dividing the group (the
* FLUX.2 VAE's 128 channels in 32 groups take 4, SDXL's 320 in 32 take 2). A row's chunks are
* split over at most 256 threads, each taking `cpt` consecutive chunks of one group, `cpt`
* the smallest divisor of the group's chunks that fits the row in the block. */
if (groups <= 0 || groups > kT || n <= 0 || n % groups || (n / groups) % 2)
return R4D_NO(RAD_E_SHAPE);
const int CW = (n / groups) % 8 == 0 ? 8 : (n / groups) % 4 == 0 ? 4 : 2;
const int cpr_log = log2_exact(n / CW);
if (cpr_log < 0 || n / CW > kT) return R4D_NO(RAD_E_SHAPE);
const long long cg = n / groups;
const int CW = cg % 8 == 0 ? 8 : cg % 4 == 0 ? 4 : 2;
const int cpr = (int)(n / CW), gs8 = (int)(cg / CW);
int cpt = 1;
while (cpr / cpt > kT || gs8 % cpt) ++cpt;
const int tpr = cpr / cpt, tpg = gs8 / cpt;
if (r4d_numel(w) < n || r4d_numel(b) < n || (mod && r4d_numel(mod) < 2 * n) ||
r4d_numel(st) < groups * (2 + 3 * kGnParts))
return R4D_NO(RAD_E_SHAPE);
@@ -849,22 +852,22 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
return R4D_NO(RAD_E_STRIDE);
long long rx = 0, ldx = 0, ry = 0, ldy = 0;
if (!rows8(x, n, &rx, &ldx) || !rows8(y, n, &ry, &ldy)) return R4D_NO(RAD_E_STRIDE);
/* Over y's rows, as libref's (x may hold more); M is not read. Counts are f32 sums: exact
* while a group's M n / groups values stay under 2^24. */
/* Over y's rows, as libref's (x may hold more); M is not read. A part's count is exact in f32
* (rpp cg <= 2^24); the merged counts only weigh the merges, and the variance divides by the
* group's exact count. */
const long long M = ry;
if (M <= 0 || M > rx || M > ry || M * (n / groups) >= (1ll << 24)) return R4D_NO(RAD_E_SHAPE);
const int slots = kT >> cpr_log;
if (M <= 0 || M > rx || M > ry || M * cg >= (1ll << 31)) return R4D_NO(RAD_E_SHAPE);
const int slots = kT / tpr;
/* Whole passes of the block a part, as few parts as fill the scratch. */
long long rpp = (M + kGnParts - 1) / kGnParts;
rpp = (rpp + slots - 1) / slots * slots;
const int parts = (int)((M + rpp - 1) / rpp);
const int gs8 = (int)(n / groups / CW);
float* S = (float*)r4d_wp(st);
const float eps = (float)r4d_getf(a, "eps", 1e-5);
int rc;
#define GN_P(TX, C4) \
rc = R4D_EMIT(stream, (gn_part_kernel<TX, C4>), dim3((unsigned)parts), dim3(kT), 0, \
(const TX*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, (int)rpp)
(const TX*)r4d_p(x), S, (int)M, (int)groups, tpr, cpt, tpg, (int)ldx, (int)rpp)
if (is_f32(x)) {
if (CW == 8) GN_P(float, 8);
else if (CW == 4) GN_P(float, 4);
@@ -877,14 +880,14 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
#undef GN_P
if (rc != RAD_OK) return R4D_NO(rc);
rc = R4D_EMIT(stream, gn_final_kernel, dim3((unsigned)groups), dim3(kT), 0, S, (int)groups,
parts, eps);
parts, (float)(M * cg), eps);
if (rc != RAD_OK) return R4D_NO(rc);
const int modk = !mod ? 0 : is_f32(mod) ? 2 : 1;
const dim3 grid((unsigned)((M + slots - 1) / slots));
const dim3 grid((unsigned)((M * cpr + kT - 1) / kT));
#define GN_A2(TX, TY, C4) \
return R4D_EMIT(stream, (gn_apply_kernel<TX, TY, C4>), grid, dim3(kT), 0, (const TX*)r4d_p(x),\
(TY*)r4d_wp(y), r4d_p(w), r4d_p(b), r4d_p(mod), (const float*)S, (int)M, \
(int)n, cpr_log, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \
(int)n, cpr, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \
modk, silu)
#define GN_A(TX, TY) \
do { if (CW == 8) GN_A2(TX, TY, 8); if (CW == 4) GN_A2(TX, TY, 4); GN_A2(TX, TY, 2); } while (0)