radiance 1.8.1

- MiniMax-H3 and FastH3 no longer stop the server on a prompt longer than 16 tokens (FastH3) or
  128 tokens (MiniMax-H3)
- latent upscaling for the MiniMax-H3 containers: with LBH-123-AI's latent upscaler in the
  container, `latent_upscale` runs the first steps at a smaller size and refines the latent at the
  full size; `upscale_refine_steps` sets how many steps refine, and the video object reports both
- rad-convert --in-place extends a container whose weights the plugin has regrouped since
- plugin ABI 22: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-18 15:41:44 +02:00
1 parent 7a7707a955
commit 816e24bd46
43 files changed
+4458 -81

No files matched your search

+4
View File
@@ -79,6 +79,10 @@ set(R4D_UNITS
# decoder's patch unfold, tiles, stitch and rotary positions, and the soundtrack decoder's
# alias-free SnakeBeta.
"r4d_video|"
# A video latent upscaler: the 3x3x3 convolution as an implicit GEMM over voxel rows, the group
# norm, the temporal depthwise convolution, the per-frame bilinear resize, the patch fold and the
# re-noise.
"r4d_upscaler|"
# Video sparse attention: the tile selection a distilled video transformer was trained with and
# the block-sparse attention over it.
"r4d_vsa|"
+40
View File
@@ -359,6 +359,17 @@ __global__ __launch_bounds__(kThreads) void narrow_f16_kernel(
__builtin_bit_cast(uint16_t, (_Float16)bf2f(x[(size_t)m * x_ld + i]));
}
// ---------------------------------------------------------------------------- cast f32 -> bf16
// ref_cast: the value rounded to nearest even once.
__global__ __launch_bounds__(kThreads) void narrow_bf16_kernel(
const float* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld,
uint32_t y_ld, uint32_t M) {
const uint32_t i = blockIdx.x * kThreads + threadIdx.x;
if (i >= n) return;
for (uint32_t m = blockIdx.y; m < M; m += gridDim.y)
y[(size_t)m * y_ld + i] = f32_to_bf16(x[(size_t)m * x_ld + i]);
}
// ---------------------------------------------------------------------------- the audio tower
// Gemma 4's USM conformer: elementwise rectifier and clamp, the subsampler's segment-wise
// convolution, the light-conv block's causal depthwise convolution, the relative-position table,
@@ -866,6 +877,17 @@ extern "C" int r4d_narrow_bf16_f16(long x, long y, int M, int n, int x_ld, int y
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_narrow_f32_bf16(long x, long y, int M, int n, int x_ld, int y_ld,
long stream) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
hipLaunchKernelGGL(narrow_bf16_kernel,
dim3((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M)),
dim3(kThreads), 0, (hipStream_t)stream, (const float*)x, (uint16_t*)y,
(uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_relu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
@@ -1216,6 +1238,24 @@ extern "C" int r4d_rad_cast_f16(const RadArgs* a, RadStream s) {
(int)y_ld, (long)(uintptr_t)s));
}
/* ------------------------------------------------------------------ cast f32 -> bf16 */
extern "C" int r4d_rad_cast_bf16(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, 0);
const RadTensor* y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
if (x->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
R4D_NEED(dt_bf16(y));
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
long long M = 0, Mx = 0;
const long long y_ld = r4d_rows_pitch(y, n, &M);
const long long x_ld = r4d_rows_pitch(x, n, &Mx);
if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE);
return enc_status(r4d_narrow_f32_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, (int)x_ld,
(int)y_ld, (long)(uintptr_t)s));
}
/* ------------------------------------------------------------------ the audio tower */
extern "C" int r4d_rad_relu(const RadArgs* a, RadStream s) {
+72
View File
@@ -1290,6 +1290,78 @@ extern "C" int r4d_rad_unrelayout_conv_tap(const RadParam* p, int n_p, int opera
return RAD_OK;
}
/* ---- conv3d_ndhwc: PyTorch's [cout][cin][kt][k][k] stored tap-major, [cout][kt][k][k][cin].
*
* conv2d_nhwc's reordering with the frame tap outermost: the implicit GEMM (r4d_upscaler.hip)
* contracts over K = (tap, channel), tap = (dt k + dy) k + dx, the channel innermost, so a 16-byte
* read of a voxel row is eight consecutive K. Operand 1 of conv3d_ndhwc; the bias is read as
* stored. */
namespace {
int conv3d_geom(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout,
long long* cin, long long* taps) {
*cout = r4d_pgeti_or(p, n_p, "cout", 0);
*cin = r4d_pgeti_or(p, n_p, "cin", 0);
const long long k = r4d_pgeti_or(p, n_p, "k", 0), kt = r4d_pgeti_or(p, n_p, "kt", 0);
if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || k <= 0 || kt <= 0) return RAD_E_SHAPE;
*taps = kt * k * k;
if (pl[0].dtype != RAD_BF16 || rad_tensor_numel(&pl[0]) != *cout * *cin * *taps)
return RAD_E_SHAPE;
return RAD_OK;
}
} /* namespace */
extern "C" int r4d_rad_layout_conv3d_tap(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
(void)sel;
if (!out) return RAD_E_INVAL;
if (operand != CONV_W_OPERAND) return RAD_E_UNSUPPORTED;
if (!enc || !rad_enc_is(enc, "plain")) return RAD_E_DTYPE;
long long co, ci, taps;
const int rc = conv3d_geom(p, n_p, pl, n, &co, &ci, &taps);
if (rc != RAD_OK) return rc;
fill(out, "r4d.conv3d.tap_major", RAD_BF16, co, taps * ci, co * taps * ci * 2);
return RAD_OK;
}
extern "C" int r4d_rad_relayout_conv3d_tap(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, void* dst,
int64_t dst_bytes) {
RadLayout L;
const int rc = r4d_rad_layout_conv3d_tap(p, n_p, operand, enc, sel, pl, n, &L);
if (rc != RAD_OK) return rc;
if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
long long co, ci, taps;
conv3d_geom(p, n_p, pl, n, &co, &ci, &taps);
const uint16_t* s = (const uint16_t*)pl[0].data;
uint16_t* d = (uint16_t*)dst;
for (long long o = 0; o < co; ++o)
for (long long c = 0; c < ci; ++c)
for (long long t = 0; t < taps; ++t)
d[(o * taps + t) * ci + c] = s[(o * ci + c) * taps + t];
return RAD_OK;
}
extern "C" int r4d_rad_unrelayout_conv3d_tap(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const void* src, int64_t src_bytes,
const RadTensor* pl, int n) {
RadLayout L;
const int rc = r4d_rad_layout_conv3d_tap(p, n_p, operand, enc, sel, pl, n, &L);
if (rc != RAD_OK) return rc;
if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
long long co, ci, taps;
conv3d_geom(p, n_p, pl, n, &co, &ci, &taps);
const uint16_t* s = (const uint16_t*)src;
uint16_t* d = (uint16_t*)pl[0].data;
for (long long o = 0; o < co; ++o)
for (long long c = 0; c < ci; ++c)
for (long long t = 0; t < taps; ++t)
d[(o * ci + c) * taps + t] = s[(o * taps + t) * ci + c];
return RAD_OK;
}
/* ---- conv1d and conv_t1d: a vocoder's 1-D weights, reordered so K runs over (tap, channel) with
* the channel innermost, as conv2d_nhwc's (r4d_audio.hip). Operand 1 of both.
*
+17
View File
@@ -200,6 +200,14 @@ int r4d_rad_vtile_gather (const RadArgs*, RadStream);
int r4d_rad_vtile_stitch (const RadArgs*, RadStream);
int r4d_rad_grid_pos3 (const RadArgs*, RadStream);
int r4d_rad_snake_aa (const RadArgs*, RadStream);
/* r4d_upscaler.hip: a video latent upscaler's 3D convolution, group norm, temporal depthwise
* convolution and resize, the patch fold and the re-noise. */
int r4d_rad_conv3d_ndhwc (const RadArgs*, RadStream);
int r4d_rad_group_norm (const RadArgs*, RadStream);
int r4d_rad_tconv_dw (const RadArgs*, RadStream);
int r4d_rad_resize_bilinear (const RadArgs*, RadStream);
int r4d_rad_patch_fold (const RadArgs*, RadStream);
int r4d_rad_flow_renoise (const RadArgs*, RadStream);
/* r4d_vsa.hip: video sparse attention's selection (scratch for the tile means) and attention. */
int r4d_rad_vsa_select (const RadArgs*, RadStream);
int64_t r4d_rad_vsa_select_scratch (const RadArgs*);
@@ -491,6 +499,14 @@ int r4d_rad_relayout_conv_tap(const RadParam*, int, int, const RadEncoding*, con
const RadTensor*, int, void*, int64_t);
int r4d_rad_unrelayout_conv_tap(const RadParam*, int, int, const RadEncoding*, const int*,
const void*, int64_t, const RadTensor*, int);
/* conv3d_ndhwc's weight, PyTorch's [cout][cin][kt][k][k] stored tap-major [cout][kt][k][k][cin]
* (r4d_layout.cpp). */
int r4d_rad_layout_conv3d_tap(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_conv3d_tap(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_unrelayout_conv3d_tap(const RadParam*, int, int, const RadEncoding*, const int*,
const void*, int64_t, const RadTensor*, int);
/* conv1d's weight, PyTorch's [cout][cin][k] stored [cout][k][cin], and conv_t1d's, PyTorch's
* [cin][cout][2s] stored [s][cout][2][cin] (r4d_layout.cpp). */
int r4d_rad_layout_conv1d_tap(const RadParam*, int, int, const RadEncoding*, const int*,
@@ -557,6 +573,7 @@ int r4d_rad_seg_mean (const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope (const RadArgs*, RadStream);
int r4d_rad_cast_widen (const RadArgs*, RadStream);
int r4d_rad_cast_f16 (const RadArgs*, RadStream);
int r4d_rad_cast_bf16 (const RadArgs*, RadStream);
int r4d_rad_pool_rows (const RadArgs*, RadStream);
int r4d_rad_relu (const RadArgs*, RadStream);
int r4d_rad_silu (const RadArgs*, RadStream);
+124
View File
@@ -2331,6 +2331,34 @@ static const RadParamSpec pGridPos3[] = { P_INT("M"), P_INT("T"), P_INT("H"), P_
P_INT("period"), P_F64("scale") };
static const RadOperandSpec oGridPos3[] = { { "y", RAD_OPD_OUT, 0 } };
/* ---- a video latent upscaler (r4d_upscaler.hip); the same specs as libref's. `geom` is the
* request's volume, i32 on the device; patch_fold takes patch_unfold's specs. */
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("kt"), P_STR("dtype") };
static const RadOperandSpec oConv3d[] = {
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 },
{ "geom", RAD_OPD_IN, 0 }, { "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pGroupNorm[] = { P_INT("M"), P_INT("n"), P_INT("groups"), P_F64("eps"),
P_STR("act"), P_STR("dtype") };
static const RadOperandSpec oGroupNorm[] = {
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 },
{ "mod", RAD_OPD_IN, 1 }, { "stats", RAD_OPD_INOUT, 0 }, { "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pTconvDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") };
static const RadOperandSpec oTconvDw[] = {
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 },
{ "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
};
static const RadOperandSpec oResizeBil[] = {
{ "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stream"),
P_STR("dtype") };
static const RadOperandSpec oFlowRenoise[] = {
{ "sigma", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
};
/* ---- video sparse attention (r4d_vsa.hip); the same specs as libref's. `segs` cuts the packed
* rows into dense segments and the video grid, `geom` is the request's latent geometry; `sel` is
* vsa_select's output and attn_vsa's input. `v` of vsa_select is read only for `coarse`. */
@@ -3017,6 +3045,25 @@ static const RadOpSchema kSchemas[] = {
"tail."),
SCHEMA("grid_pos3", pGridPos3, oGridPos3,
"a video decoder's rotary positions over tiles of `period` rows, f32 [3, M]."),
SCHEMA("conv3d_ndhwc", pConv3d, oConv3d,
"a stride-1 `same` 3D convolution over NDHWC voxel rows of the device volume geom = "
"(T, H, W), PyTorch's [cout, cin, kt, k, k] weight, f32 accumulation; with `res`, "
"y = rd(rd(acc + b) + res), res may alias y."),
SCHEMA("group_norm", pGroupNorm, oGroupNorm,
"nn.GroupNorm over all of y's rows (biased variance, rstd in f32), then the optional "
"modulation v (1 + mod[0:n]) + mod[n:2n] and `act` (none or silu), one rounding; "
"stats[2g], stats[2g + 1] hold group g's mean and rstd, the rest is scratch."),
SCHEMA("tconv_dw", pTconvDw, oTconvDw,
"a depthwise convolution along the frames of the device volume geom = (T, H, W), "
"frames outside zero, taps in ascending order in f32, one rounding after the bias."),
SCHEMA("resize_bilinear", pGenMn, oResizeBil,
"each frame resized as torch's bilinear interpolation at a size, align_corners=False, "
"geom = (T, h, w, H, W), f32 and one rounding."),
SCHEMA("patch_fold", pPatchUnfold, oPatchUnfold,
"patch_unfold's inverse: voxel rows to f32 patch rows, x mul + add per channel."),
SCHEMA("flow_renoise", pFlowRenoise, oFlowRenoise,
"x = (1 - sigma) x + sigma z, z the (seed, stream) normal stream at element k n + c, "
"each step one f32 rounding."),
SCHEMA("vsa_select", pVsa, oVsaSelect,
"video sparse attention's selection over tiles of at most 64 rows (dense segments in "
"chunks, the video grid in tile_t x tile_h x tile_w boxes): f32 tile means of q and k, "
@@ -3312,6 +3359,11 @@ static const RadConstraint cCastWiden[] = {
static const RadConstraint cCastF16[] = {
C_IN("from", "bf16"), C_IN("to", "f16"),
};
/* `cast` narrowing f32 -> bf16, rounded to nearest even: an f32 latent into a bf16 network (the
* MiniMax-H3 latent upscaler's input voxels). */
static const RadConstraint cCastNarrow[] = {
C_IN("from", "f32"), C_IN("to", "bf16"),
};
/* The encoder's dense attention: bidirectional, any window, at the (head_dim, gqa) pairs
* r4d_attn_dense_bf16.hip compiles. */
/* Causal or not at head_dim 64: a vision tower's heads, and a codec's sliding causal layers. */
@@ -4196,6 +4248,18 @@ static const RadConstraint cGenF32[] = { C_IN("dtype", "f32") };
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
* 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) };
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) };
static const RadConstraint cLnModQ[] = { C_IN("dtype", "bf16"), C_DIV("n", 128), C_LE("n", 8192),
C_EQ("group", 128) };
/* The lane copies move 32-bit words, so any row of whole words: bf16 latents and an f32 mask. */
@@ -4356,6 +4420,15 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_cast_f16, nullptr, nullptr, nullptr,
r4d_shape_cast },
{ "cast_f32_bf16", "cast", "elem",
"y = x, f32 narrowed to bf16",
"any M and n; both row pitches are read off the operands",
"f32 in, bf16 out, rounded to nearest even",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cCastNarrow), NOTUNE,
nullptr, nullptr, r4d_rad_cast_bf16, nullptr, nullptr, nullptr,
r4d_shape_cast },
{ "act_mul_bf16", "act_mul", "elem",
"gated activation over two operands: act(a) rounded, times b",
"any n; a, b and y each at their own row pitch, so both may be column slices of one buffer",
@@ -7224,6 +7297,57 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cSnakeAa), NOTUNE,
nullptr, nullptr, r4d_rad_snake_aa },
/* ------------------------------------------------------------------- a video latent upscaler */
{ "conv3d_ndhwc_bf16", "conv3d_ndhwc", "conv",
"a 3 x 3 x 3 video convolution as an implicit GEMM over (tap, cin): the weight stored tap-major "
"and read into registers, the voxels' tap neighbours staged through LDS",
"128 voxels x 128 output channels a block, 64 K a stage; k = kt = 3, cin % 8 == 0 (a multiple "
"of 64 decodes the tap once per cin / 64 stages); row pitches honoured, res may alias y",
"bf16 voxels, weight and residual, bf16 or f32 bias, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cConv3d), NOTUNE,
nullptr, nullptr, r4d_rad_conv3d_ndhwc, nullptr, r4d_rad_layout_conv3d_tap,
r4d_rad_relayout_conv3d_tap, nullptr, r4d_rad_unrelayout_conv3d_tap },
{ "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",
"bf16 or f32 rows, bf16 or f32 gain, bias and modulation, f32 statistics",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGroupNorm), NOTUNE,
nullptr, nullptr, r4d_rad_group_norm },
{ "tconv_dw_bf16", "tconv_dw", "conv",
"a depthwise convolution along the frames: a thread an 8-channel chunk of a frame position, the "
"5-frame window in registers over every frame",
"k = 5, n % 8 == 0, row pitches honoured", "bf16 voxels, weight and bias, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cTconvDw), NOTUNE,
nullptr, nullptr, r4d_rad_tconv_dw },
{ "resize_bilinear", "resize_bilinear", "elem",
"torch's per-frame bilinear resize at a size: a thread an 8-channel chunk of an output voxel",
"n % 8 == 0, any sizes, row pitches honoured", "bf16 or f32 voxels, f32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cResizeBil), NOTUNE,
nullptr, nullptr, r4d_rad_resize_bilinear },
{ "patch_fold_f32", "patch_fold", "elem",
"voxel rows folded to normalised patch rows, the geometry read on the device",
"C <= 64, row pitches honoured", "bf16 or f32 voxels, f32 patch rows",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cPatchFold), NOTUNE,
nullptr, nullptr, r4d_rad_patch_fold },
{ "flow_renoise_f32", "flow_renoise", "elem",
"a clean latent re-noised to sigma from a fresh normal stream: a thread a value",
"any M and n, row pitches honoured", "f32 latent and sigma, u32 seed words",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenF32), NOTUNE,
nullptr, nullptr, r4d_rad_flow_renoise },
};
/* ================================================================================== the exports */
+774 -1
View File
@@ -6421,6 +6421,643 @@ void snake_aa_cases(const Plugin& pl) {
} /* namespace vid */
/* ---- a video latent upscaler's ops, at MiniMax-H3's shapes ---------------------------------------
*
* The upscaler runs a 37-frame clip at its 42 x 24 latent (the source) and at 84 x 48 (the
* target), 512 channels, 24 at its two ends; a 15 s clip is 102 frames. Each case compares with
* the host port of its libref function (libref/ref_video.cpp): the temporal convolution, the
* resize and the fold bit for bit, since the kernels keep the reference's order; the 3D
* convolution to a relative L2 over sampled output rows (its f32 sum runs in its own order), every
* face voxel of the first and last frames among them; the group norm to a relative L2 against f64
* statistics, its own bytes identical over two runs; the noise through the device's log, sin and
* cos. Rows and columns an op must not write are filled with a marker and checked after. */
namespace ups {
using namespace au;
/* f(i) for i in [0, n), strided over the host's cores. */
template <class F> void par_for(int64_t n, F&& f) {
const unsigned hc = std::thread::hardware_concurrency();
const int nt = (int)std::max(1u, std::min(32u, hc ? hc : 1u));
std::vector<std::thread> th;
for (int k = 0; k < nt; ++k)
th.emplace_back([&, k]() { for (int64_t i = k; i < n; i += nt) f(i); });
for (std::thread& t : th) t.join();
}
constexpr uint16_t kMark = 0x7f7fu; /* a bf16 marker no kernel here writes: 3.39e38 */
/* A bf16 operand of `rows` rows at pitch `ld`: its first `fill` rows' first n columns from `v`
* (rounded in place), every other element the marker. */
void* up_rows(std::vector<float>& v, int64_t rows, int64_t n, int64_t ld, int64_t fill) {
std::vector<uint16_t> b((size_t)(rows * ld), kMark);
for (int64_t r = 0; r < fill; ++r)
for (int64_t c = 0; c < n; ++c) {
const uint16_t h = h_to_bf16(v[(size_t)(r * n + c)]);
b[(size_t)(r * ld + c)] = h;
v[(size_t)(r * n + c)] = h_bf16(h);
}
void* d = dalloc(b.size() * 2);
if (d) st_memcpy(d, b.data(), b.size() * 2, hipMemcpyHostToDevice);
return d;
}
std::vector<uint16_t> down_u16(void* d, size_t n) {
std::vector<uint16_t> b(n);
st_memcpy(b.data(), d, n * 2, hipMemcpyDeviceToHost);
return b;
}
/* Markers an op overwrote: columns [n, ld) of the first `used` rows, and every row from `used`. */
int64_t marks_moved(const std::vector<uint16_t>& b, int64_t rows, int64_t n, int64_t ld,
int64_t used) {
int64_t bad = 0;
for (int64_t r = 0; r < rows; ++r)
for (int64_t c = r < used ? n : 0; c < ld; ++c) bad += b[(size_t)(r * ld + c)] != kMark;
return bad;
}
RadTensor pitched(void* d, uint32_t dt, int64_t rows, int64_t n, int64_t ld) {
RadTensor t = T(d, dt, { rows, n });
t.stride[0] = ld;
return t;
}
/* ------------------------------------------------------------------ conv3d_ndhwc */
struct Vol { int64_t T, H, W; };
/* Every voxel on a face of the first and last frames, and a hashed sample of the rest of about
* `want` rows. */
std::vector<int64_t> conv_rows(const Vol& v, int64_t M, int64_t want) {
std::vector<int64_t> rows;
const int64_t HW = v.H * v.W;
const uint32_t every = (uint32_t)std::max<int64_t>(1, M / want);
for (int64_t r = 0; r < M; ++r) {
const int64_t t = r / HW, y = (r / v.W) % v.H, x = r % v.W;
const bool face = (t == 0 || t == v.T - 1) &&
(y == 0 || y == v.H - 1 || x == 0 || x == v.W - 1);
if (face || st_mix32((uint32_t)r * 2654435761u) % every == 0) rows.push_back(r);
}
return rows;
}
/* libref's conv3d_ndhwc at output row r: the products (exact in f32) summed in f64, rounded to f32,
* the bias added in f32 and rounded; with a residual, that plus the residual, rounded. `wt` is the
* weight tap-major, as the row stores it. */
void conv3d_row(const std::vector<float>& x, int64_t cin, const std::vector<float>& wt,
const std::vector<float>& b, const float* res, const Vol& v, int64_t cout,
int64_t r, float* out) {
const int64_t HW = v.H * v.W, t = r / HW, y = (r / v.W) % v.H, xx = r % v.W;
std::vector<double> acc((size_t)cout, 0.0);
for (int64_t tap = 0; tap < 27; ++tap) {
const int64_t nt = t + tap / 9 - 1, ny = y + (tap / 3) % 3 - 1, nx = xx + tap % 3 - 1;
if (nt < 0 || nt >= v.T || ny < 0 || ny >= v.H || nx < 0 || nx >= v.W) continue;
const float* xr = &x[(size_t)((nt * HW + ny * v.W + nx) * cin)];
for (int64_t o = 0; o < cout; ++o) {
const float* wr = &wt[(size_t)((o * 27 + tap) * cin)];
double s = 0.0;
for (int64_t c = 0; c < cin; ++c) s += (double)(wr[c] * xr[c]);
acc[(size_t)o] += s;
}
}
for (int64_t o = 0; o < cout; ++o) {
float f = bfr((float)acc[(size_t)o] + b[(size_t)o]);
if (res) f = bfr(f + res[o]);
out[o] = f;
}
}
struct ConvCase {
const char* what;
Vol v;
int64_t cin, cout;
int res; /* 0 none, 1 its own operand, 2 the output itself */
bool bf32; /* an f32 bias */
int64_t xpad, ypad, yextra; /* pitch padding, output rows past the volume */
int64_t mshort; /* the M parameter this short of T H W: the volume's rows are written */
int64_t sample; /* rows checked besides the faces; 0 every row */
};
void conv3d_case(const RadKernelInfo* r, const ConvCase& c) {
const Vol& v = c.v;
const int64_t vol = v.T * v.H * v.W, M = vol, K = 27 * c.cin;
const int64_t ldx = c.cin + c.xpad, ldy = c.cout + c.ypad, yrows = M + c.yextra;
const std::string nm = fmt("conv3d_ndhwc_bf16 %s: %lld -> %lld at %lld x %lld, %lld frames%s%s%s",
c.what, (long long)c.cin, (long long)c.cout, (long long)v.H,
(long long)v.W, (long long)v.T,
c.res == 2 ? ", res in place" : c.res ? ", res" : "",
c.bf32 ? ", f32 bias" : "",
c.xpad || c.ypad || c.yextra || c.mshort ? ", pitched" : "");
g_seed = 0xc03dull + (uint64_t)(c.cin * 131 + c.cout * 7 + v.T);
std::vector<float> x = randv((size_t)(vol * c.cin), 1.0f);
std::vector<float> w = randv((size_t)(c.cout * K), 1.5f / std::sqrt((float)K));
std::vector<float> b = randv((size_t)c.cout, 0.5f);
std::vector<float> res = c.res ? randv((size_t)(M * c.cout), 1.0f) : std::vector<float>();
for (auto& e : w) e = bfr(e);
if (!c.bf32) for (auto& e : b) e = bfr(e);
std::vector<float> wt((size_t)(c.cout * K));
for (int64_t o = 0; o < c.cout; ++o)
for (int64_t ci = 0; ci < c.cin; ++ci)
for (int64_t t = 0; t < 27; ++t)
wt[(size_t)((o * 27 + t) * c.cin + ci)] = w[(size_t)((o * c.cin + ci) * 27 + t)];
std::vector<RadParam> ps = { PI("M", M - c.mshort), PI("cin", c.cin), PI("cout", c.cout),
PI("k", 3), PI("kt", 3), PS("dtype", "bf16") };
void* dw = stored_weight(r, ps, w, c.cout, K, nm.c_str());
void* dx = up_rows(x, vol, c.cin, ldx, vol);
std::vector<float> bb = b;
void* db = c.bf32 ? up_f32(b) : up_bf16(bb);
void* dres = c.res == 1 ? up_rows(res, M, c.cout, c.cout, M) : nullptr;
/* In place, y starts as the residual. */
void* dy = up_rows(res, yrows, c.cout, ldy, c.res == 2 ? M : 0);
if (!dw || !dx || !db || !dy || (c.res == 1 && !dres)) {
ok(nm.c_str(), false, "hipMalloc failed");
return;
}
RadTensor tres = c.res == 1 ? T(dres, RAD_BF16, { M, c.cout })
: c.res == 2 ? pitched(dy, RAD_BF16, M, c.cout, ldy)
: T(nullptr, RAD_BF16, { 1 });
if (!c.res) absent(tres);
const int rc = launch(r, { pitched(dx, RAD_BF16, vol, c.cin, ldx), T(dw, RAD_BF16, { c.cout, K }),
T(db, c.bf32 ? RAD_F32 : RAD_BF16, { c.cout }),
TI32({ 3 }, { (int32_t)v.T, (int32_t)v.H, (int32_t)v.W }), tres,
pitched(dy, RAD_BF16, yrows, c.cout, ldy) },
ps);
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); return; }
const std::vector<uint16_t> yb = down_u16(dy, (size_t)(yrows * ldy));
std::vector<int64_t> rows;
if (c.sample) {
rows = conv_rows(v, M, c.sample);
} else {
for (int64_t i = 0; i < M; ++i) rows.push_back(i);
}
std::vector<float> want(rows.size() * (size_t)c.cout), got(want.size());
par_for((int64_t)rows.size(), [&](int64_t i) {
const int64_t rr = rows[(size_t)i];
conv3d_row(x, c.cin, wt, b, c.res ? &res[(size_t)(rr * c.cout)] : nullptr, v, c.cout, rr,
&want[(size_t)i * c.cout]);
for (int64_t o = 0; o < c.cout; ++o)
got[(size_t)i * c.cout + o] = h_bf16(yb[(size_t)(rr * ldy + o)]);
});
check(fmt("%s, %zu rows", nm.c_str(), rows.size()), got, want, 5e-4);
const int64_t moved = marks_moved(yb, yrows, c.cout, ldy, M);
ok((nm + ": columns past cout and rows past the volume untouched").c_str(), moved == 0,
fmt("%lld marker values written", (long long)moved));
}
void conv3d_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "conv3d_ndhwc_bf16");
if (!r) { ok("conv3d_ndhwc_bf16", false, "row absent"); return; }
const Vol src{ 37, 42, 24 }, dst{ 37, 84, 48 };
for (const ConvCase& c : {
/* The model's four convolutions at its two sizes. */
ConvCase{ "conv_in", src, 24, 512, 0, false, 0, 0, 0, 0, 3000 },
ConvCase{ "source block", src, 512, 512, 2, false, 0, 0, 0, 0, 3000 },
ConvCase{ "target block", dst, 512, 512, 0, true, 0, 0, 0, 0, 3000 },
ConvCase{ "conv_out", dst, 512, 24, 0, false, 0, 0, 0, 0, 3000 },
/* Edges, every row checked: an odd volume (no block or tile fills) with pitched
* operands, rows past the volume and a declared M short of it, into 40 channels (a
* partial tile); one frame (no temporal neighbour); one row of voxels; two channel
* tiles a tap into 136 channels. */
ConvCase{ "odd volume", Vol{ 3, 5, 7 }, 64, 40, 1, false, 8, 16, 5, 3, 0 },
ConvCase{ "one frame", Vol{ 1, 9, 13 }, 16, 24, 2, true, 0, 8, 2, 0, 0 },
ConvCase{ "one row", Vol{ 4, 1, 21 }, 8, 8, 0, false, 8, 0, 0, 0, 0 },
ConvCase{ "two tiles a tap", Vol{ 2, 11, 6 }, 128, 136, 2, false, 0, 0, 7, 0, 0 },
})
conv3d_case(r, c);
/* A 15 s clip at the target size: 411264 rows, the largest volume the model runs. */
conv3d_case(r, ConvCase{ "102 frames", Vol{ 102, 84, 48 }, 512, 512, 2, false, 0, 0, 0, 0, 2000 });
/* Refusals: a 5-wide kernel, a channel count off the 16-byte chunk. */
ok("conv3d_ndhwc_bf16 refuses k 5",
launch(r, { TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 8, 1000 }), TA(RAD_BF16, { 8 }),
TI32({ 3 }, { 2, 2, 2 }), TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 8, 8 }) },
{ PI("M", 8), PI("cin", 8), PI("cout", 8), PI("k", 5), PI("kt", 3),
PS("dtype", "bf16") }) == RAD_E_SHAPE);
ok("conv3d_ndhwc_bf16 refuses cin 12",
launch(r, { TA(RAD_BF16, { 8, 12 }), TA(RAD_BF16, { 8, 324 }), TA(RAD_BF16, { 8 }),
TI32({ 3 }, { 2, 2, 2 }), TA(RAD_BF16, { 8, 8 }), TA(RAD_BF16, { 8, 8 }) },
{ PI("M", 8), PI("cin", 12), PI("cout", 8), PI("k", 3), PI("kt", 3),
PS("dtype", "bf16") }) == RAD_E_SHAPE);
}
/* ------------------------------------------------------------------ group_norm */
/* libref's group_norm: the statistics in f64, rstd = 1 / sqrt(var + eps) in f32, the rest in f32
* and one rounding, to bf16 when `bf`. */
void gn_ref(const std::vector<float>& x, int64_t M, int64_t n, int64_t groups,
const std::vector<float>& w, const std::vector<float>& b,
const std::vector<float>* mod, bool silu, float eps, bool bf, std::vector<float>* y,
std::vector<float>* mean, std::vector<float>* rstd) {
const int64_t gs = n / groups;
mean->assign((size_t)groups, 0.0f);
rstd->assign((size_t)groups, 0.0f);
par_for(groups, [&](int64_t g) {
double s = 0.0;
for (int64_t r = 0; r < M; ++r)
for (int64_t c = g * gs; c < (g + 1) * gs; ++c) s += x[(size_t)(r * n + c)];
const double mu = s / (double)(M * gs);
double q = 0.0;
for (int64_t r = 0; r < M; ++r)
for (int64_t c = g * gs; c < (g + 1) * gs; ++c) {
const double d = x[(size_t)(r * n + c)] - mu;
q += d * d;
}
(*mean)[(size_t)g] = (float)mu;
(*rstd)[(size_t)g] = 1.0f / std::sqrt((float)(q / (double)(M * gs)) + eps);
});
y->assign((size_t)(M * n), 0.0f);
par_for(M, [&](int64_t r) {
for (int64_t c = 0; c < n; ++c) {
const int64_t g = c / gs;
float v = (x[(size_t)(r * n + c)] - (*mean)[(size_t)g]) * (*rstd)[(size_t)g] *
w[(size_t)c] + b[(size_t)c];
if (mod) v = v * (1.0f + (*mod)[(size_t)c]) + (*mod)[(size_t)(n + c)];
if (silu) v = v / (1.0f + std::exp(-v));
(*y)[(size_t)(r * n + c)] = bf ? bfr(v) : v;
}
});
}
void group_norm_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "group_norm");
if (!r) { ok("group_norm", false, "row absent"); return; }
struct G {
const char* what;
int64_t M, n, groups;
bool xf, yf, wf; /* f32 rows in, out; an f32 gain and bias */
int mod; /* 0 none, 1 bf16, 2 f32 */
bool silu, inplace;
float offset; /* added to every value: a mean far from zero */
int64_t pad;
};
for (const G& g : {
/* The target size modulated with SiLU (a block's second norm), then plain with SiLU
* in place (its first); the source size over a large mean. */
G{ "target, modulated", 37 * 84 * 48, 512, 32, false, false, false, 1, true, false, 0.0f, 0 },
G{ "target, in place", 37 * 84 * 48, 512, 32, false, false, true, 0, true, true, 0.0f, 0 },
G{ "source, mean 40", 37 * 42 * 24, 512, 32, false, false, false, 2, false, false, 40.0f, 0 },
/* Edges: f32 rows both ways, pitched; one row; 64 channels in 8 groups. */
G{ "f32 rows", 37, 512, 32, true, true, true, 2, true, false, 1.0f, 8 },
G{ "f32 in, bf16 out", 101, 512, 32, true, false, false, 0, false, false, -3.0f, 16 },
G{ "one row", 1, 512, 32, false, false, false, 1, true, false, 0.0f, 0 },
G{ "64 channels", 1000, 64, 8, false, true, false, 0, true, false, 0.0f, 8 },
}) {
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,
(long long)M, (long long)n, (long long)g.groups);
g_seed = 0x6a0ull + (uint64_t)M;
std::vector<float> x = randv((size_t)(M * n), 2.0f);
for (auto& e : x) e += g.offset;
std::vector<float> w = randv((size_t)n, 1.0f), b = randv((size_t)n, 0.5f);
std::vector<float> mod = randv((size_t)(2 * n), 0.5f);
if (!g.wf) { for (auto& e : w) e = bfr(e); for (auto& e : b) e = bfr(e); }
if (g.mod == 1) for (auto& e : mod) e = bfr(e);
/* x at its pitch and two rows longer than y, rows the statistics must not read (huge
* values); in place, y is the same buffer and both views M rows. */
void* dx = nullptr;
if (g.xf) {
std::vector<float> h((size_t)(rows * ld), 1e30f);
for (int64_t i = 0; i < M; ++i)
for (int64_t c = 0; c < n; ++c) h[(size_t)(i * ld + c)] = x[(size_t)(i * n + c)];
dx = up_f32(h);
} else {
dx = up_rows(x, rows, n, ld, M);
}
std::vector<float> none;
void* dy = g.inplace ? dx : g.yf ? dalloc((size_t)(rows * ld) * 4) : up_rows(none, rows, n, ld, 0);
void* dw = g.wf ? up_f32(w) : up_bf16(w);
void* db = g.wf ? up_f32(b) : up_bf16(b);
void* dm = g.mod == 2 ? up_f32(mod) : g.mod == 1 ? up_bf16(mod) : nullptr;
void* ds = dalloc((size_t)(g.groups * (2 + 3 * 1024)) * 4);
if (!dx || !dy || !dw || !db || !ds) { ok(nm.c_str(), false, "hipMalloc failed"); continue; }
RadTensor tm = T(dm, g.mod == 2 ? RAD_F32 : RAD_BF16, { 2 * n });
if (!g.mod) absent(tm);
const uint32_t xdt = g.xf ? RAD_F32 : RAD_BF16, ydt = g.yf ? RAD_F32 : RAD_BF16;
const std::vector<RadTensor> ts = {
pitched(dx, xdt, g.inplace ? M : rows, n, ld), T(dw, g.wf ? RAD_F32 : RAD_BF16, { n }),
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"),
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,
&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);
std::vector<float> got((size_t)(M * n));
for (int64_t i = 0; i < M; ++i)
for (int64_t c = 0; c < n; ++c) got[(size_t)(i * n + c)] = yall[(size_t)(i * ld + c)];
if (g.yf) {
double e = 0, q = 0;
for (size_t i = 0; i < want.size(); ++i) {
e += (double)(got[i] - want[i]) * (got[i] - want[i]);
q += (double)want[i] * want[i];
}
const double rl = std::sqrt(e / q);
ok(fmt("%s numerics (rel_l2 %.3g, bound 1e-5)", nm.c_str(), rl).c_str(), rl <= 1e-5);
} else {
check(nm + " numerics", got, want, 1e-3);
}
const std::vector<float> st = down_f32(ds, (size_t)(2 * g.groups));
double dmean = 0, drstd = 0;
for (int64_t k = 0; k < g.groups; ++k) {
dmean = std::max(dmean, std::fabs((double)st[(size_t)(2 * k)] - mean[(size_t)k]) *
(double)rstd[(size_t)k]);
drstd = std::max(drstd, std::fabs((double)st[(size_t)(2 * k + 1)] / rstd[(size_t)k] - 1.0));
}
ok(fmt("%s statistics (mean off by %.2g std, rstd by %.2g; bound 1e-5)", nm.c_str(), dmean,
drstd).c_str(),
dmean <= 1e-5 && drstd <= 1e-5);
if (!g.yf && !g.inplace) {
const int64_t moved = marks_moved(down_u16(dy, yel), rows, n, ld, M);
ok((nm + ": pitch columns and the buffer past y's rows untouched").c_str(), moved == 0,
fmt("%lld marker values written", (long long)moved));
}
if (!g.inplace) {
/* A second run: the same bytes, output and statistics. */
std::vector<uint8_t> y1(yel * (g.yf ? 4 : 2)), y2(y1.size());
st_memcpy(y1.data(), dy, y1.size(), hipMemcpyDeviceToHost);
const std::vector<float> s1 = down_f32(ds, (size_t)(2 * g.groups));
const int rc2 = launch(r, ts, ps);
st_memcpy(y2.data(), dy, y2.size(), hipMemcpyDeviceToHost);
const std::vector<float> s2 = down_f32(ds, (size_t)(2 * g.groups));
ok((nm + ": a second run gives the same bytes").c_str(),
rc2 == RAD_OK && y1 == y2 && differ(s1, s2) == 0);
}
}
RadTensor nomod = T(nullptr, RAD_BF16, { 1 });
absent(nomod);
ok("group_norm refuses 12 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"),
PS("dtype", "bf16") }) == RAD_E_SHAPE);
}
/* ------------------------------------------------------------------ tconv_dw */
void tconv_dw_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "tconv_dw_bf16");
if (!r) { ok("tconv_dw_bf16", false, "row absent"); return; }
/* `mshort`: the M parameter this short of the volume, whose rows are written regardless. */
struct C { const char* what; Vol v; int64_t n, xpad, ypad, mshort; };
for (const C& c : { C{ "target", Vol{ 37, 84, 48 }, 512, 0, 0, 0 },
C{ "source", Vol{ 37, 42, 24 }, 512, 0, 0, 0 },
C{ "102 frames", Vol{ 102, 42, 24 }, 512, 0, 0, 0 },
C{ "two frames, pitched", Vol{ 2, 3, 7 }, 64, 8, 16, 0 },
C{ "one frame, M declared short", Vol{ 1, 5, 5 }, 32, 0, 8, 4 },
C{ "six frames, M declared short", Vol{ 6, 1, 3 }, 8, 8, 0, 1 } }) {
const int64_t P = c.v.H * c.v.W, vol = c.v.T * P, M = vol, n = c.n, k = 5;
const int64_t ldx = n + c.xpad, ldy = n + c.ypad, yrows = M + 3;
const std::string nm = fmt("tconv_dw_bf16 %s: %lld frames of %lld x %lld x %lld", c.what,
(long long)c.v.T, (long long)c.v.H, (long long)c.v.W,
(long long)n);
g_seed = 0x7d0ull + (uint64_t)vol;
std::vector<float> x = randv((size_t)(vol * n), 2.0f), w = randv((size_t)(n * k), 0.6f);
std::vector<float> b = randv((size_t)n, 0.4f), none;
void* dx = up_rows(x, vol, n, ldx, vol);
void* dw = up_bf16(w);
void* db = up_bf16(b);
void* dy = up_rows(none, yrows, n, ldy, 0);
if (!dx || !dw || !db || !dy) { ok(nm.c_str(), false, "hipMalloc failed"); continue; }
const int rc = launch(r, { pitched(dx, RAD_BF16, vol, n, ldx),
T(dw, RAD_BF16, { n, 1, k, 1, 1 }), T(db, RAD_BF16, { n }),
TI32({ 3 }, { (int32_t)c.v.T, (int32_t)c.v.H, (int32_t)c.v.W }),
pitched(dy, RAD_BF16, yrows, n, ldy) },
{ PI("M", M - c.mshort), PI("n", n), PI("k", k), PS("dtype", "bf16") });
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
const std::vector<uint16_t> yb = down_u16(dy, (size_t)(yrows * ldy));
std::vector<float> got((size_t)(M * n)), want((size_t)(M * n));
par_for(M, [&](int64_t row) {
const int64_t t = row / P, p = row % P;
for (int64_t ch = 0; ch < n; ++ch) {
float acc = 0.0f;
for (int64_t j = 0; j < k; ++j) {
const int64_t f = t + j - k / 2;
if (f < 0 || f >= c.v.T) continue;
acc = acc + w[(size_t)(ch * k + j)] * x[(size_t)((f * P + p) * n + ch)];
}
acc = acc + b[(size_t)ch];
want[(size_t)(row * n + ch)] = bfr(acc);
got[(size_t)(row * n + ch)] = h_bf16(yb[(size_t)(row * ldy + ch)]);
}
});
const int64_t bad = differ(got, want), moved = marks_moved(yb, yrows, n, ldy, M);
ok((nm + " exact, pitch columns and rows past the volume untouched").c_str(), bad == 0 && moved == 0,
fmt("%lld values differ, %lld markers written", (long long)bad, (long long)moved));
}
}
/* ------------------------------------------------------------------ resize_bilinear */
/* upsample_bilinear2d's source index and lambdas at a size, align_corners=False, in f32. */
void bil_axis_h(int64_t o, int64_t in, int64_t out, int64_t* i0, int64_t* i1, float* l0,
float* l1) {
const float s = (float)in / (float)out;
float src = s * ((float)o + 0.5f) - 0.5f;
src = src < 0.0f ? 0.0f : src;
*i0 = (int64_t)src;
*i1 = *i0 + (*i0 < in - 1 ? 1 : 0);
*l1 = src - (float)*i0;
*l0 = 1.0f - *l1;
}
void resize_bilinear_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "resize_bilinear");
if (!r) { ok("resize_bilinear", false, "row absent"); return; }
struct C { const char* what; int64_t T, h, w, H, W, n; bool f32; int64_t pad; };
for (const C& c : { C{ "x2 to the target", 37, 42, 24, 84, 48, 512, false, 0 },
C{ "x4 to the target", 37, 20, 12, 84, 48, 512, false, 0 },
C{ "shrink", 3, 84, 48, 42, 24, 512, false, 0 },
C{ "odd sizes, pitched", 2, 7, 5, 13, 11, 64, true, 8 },
C{ "one voxel to 3 x 2", 2, 1, 1, 3, 2, 16, false, 8 },
C{ "uneven, pitched", 5, 9, 4, 5, 10, 32, false, 16 } }) {
const int64_t xr = c.T * c.h * c.w, M = c.T * c.H * c.W, n = c.n, ld = n + c.pad;
const int64_t yrows = M + 2;
const std::string nm = fmt("resize_bilinear %s: %lld x %lld -> %lld x %lld, %lld frames, %s",
c.what, (long long)c.h, (long long)c.w, (long long)c.H,
(long long)c.W, (long long)c.T, c.f32 ? "f32" : "bf16");
g_seed = 0x2e5ull + (uint64_t)(xr + M);
std::vector<float> x = randv((size_t)(xr * n), 3.0f), none;
void* dx = nullptr;
void* dy = nullptr;
if (c.f32) {
std::vector<float> h((size_t)(xr * ld), 0.0f);
for (int64_t i = 0; i < xr; ++i)
for (int64_t ch = 0; ch < n; ++ch) h[(size_t)(i * ld + ch)] = x[(size_t)(i * n + ch)];
dx = up_f32(h);
dy = up_f32(std::vector<float>((size_t)(yrows * ld), -7.0f));
} else {
dx = up_rows(x, xr, n, ld, xr);
dy = up_rows(none, yrows, n, ld, 0);
}
if (!dx || !dy) { ok(nm.c_str(), false, "hipMalloc failed"); continue; }
const uint32_t dt = c.f32 ? RAD_F32 : RAD_BF16;
const int rc = launch(r, { pitched(dx, dt, xr, n, ld),
TI32({ 5 }, { (int32_t)c.T, (int32_t)c.h, (int32_t)c.w,
(int32_t)c.H, (int32_t)c.W }),
pitched(dy, dt, yrows, n, ld) },
{ PI("M", M), PI("n", n), PS("dtype", c.f32 ? "f32" : "bf16") });
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
const size_t yel = (size_t)(yrows * ld);
const std::vector<float> yall = c.f32 ? down_f32(dy, yel) : down_bf16(dy, yel);
std::vector<float> got((size_t)(M * n)), want((size_t)(M * n));
par_for(M, [&](int64_t row) {
const int64_t t = row / (c.H * c.W), i = (row / c.W) % c.H, j = row % c.W;
int64_t i0, i1, j0, j1;
float ly0, ly1, lx0, lx1;
bil_axis_h(i, c.h, c.H, &i0, &i1, &ly0, &ly1);
bil_axis_h(j, c.w, c.W, &j0, &j1, &lx0, &lx1);
auto X = [&](int64_t a, int64_t bb, int64_t ch) {
return x[(size_t)(((t * c.h + a) * c.w + bb) * n + ch)];
};
for (int64_t ch = 0; ch < n; ++ch) {
const float v = ly0 * (lx0 * X(i0, j0, ch) + lx1 * X(i0, j1, ch)) +
ly1 * (lx0 * X(i1, j0, ch) + lx1 * X(i1, j1, ch));
want[(size_t)(row * n + ch)] = c.f32 ? v : bfr(v);
got[(size_t)(row * n + ch)] = yall[(size_t)(row * ld + ch)];
}
});
int64_t moved = 0;
if (c.f32) {
for (int64_t row = 0; row < yrows; ++row)
for (int64_t ch = row < M ? n : 0; ch < ld; ++ch)
moved += yall[(size_t)(row * ld + ch)] != -7.0f;
} else {
moved = marks_moved(down_u16(dy, yel), yrows, n, ld, M);
}
const int64_t bad = differ(got, want);
ok((nm + " exact, pitch columns and rows past the volume untouched").c_str(), bad == 0 && moved == 0,
fmt("%lld values differ, %lld markers written", (long long)bad, (long long)moved));
}
}
/* ------------------------------------------------------------------ patch_fold */
void patch_fold_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "patch_fold_f32");
if (!r) { ok("patch_fold_f32", false, "row absent"); return; }
struct C { const char* what; int64_t F, Hp, Wp, C, pt, ph, pw; bool bf; int64_t pad; };
for (const C& c : { C{ "the target latent, bf16", 37, 42, 24, 24, 1, 2, 2, true, 0 },
C{ "the target latent, f32", 37, 42, 24, 24, 1, 2, 2, false, 0 },
C{ "two frames a patch, pitched", 3, 4, 5, 24, 2, 2, 2, false, 8 },
C{ "3 x 1 patches, bf16, pitched", 2, 3, 7, 16, 1, 3, 1, true, 8 } }) {
const int64_t K = c.C * c.pt * c.ph * c.pw, rows = c.F * c.Hp * c.Wp;
const int64_t Hv = c.Hp * c.ph, Wv = c.Wp * c.pw, vox = c.F * c.pt * Hv * Wv;
const int64_t ldx = c.C + c.pad, ldy = K + c.pad, yrows = rows + 2;
const std::string nm = fmt("patch_fold_f32 %s: %lld x %lld x %lld patches of %lld x %lld x %lld",
c.what, (long long)c.F, (long long)c.Hp, (long long)c.Wp,
(long long)c.pt, (long long)c.ph, (long long)c.pw);
g_seed = 0xf01dull + (uint64_t)vox;
std::vector<float> x = randv((size_t)(vox * c.C), 2.0f);
std::vector<float> mul = randv((size_t)c.C, 1.3f), add = randv((size_t)c.C, 0.7f);
const std::string smul = vid::list_of(mul), sadd = vid::list_of(add);
void* dx = nullptr;
if (c.bf) {
dx = up_rows(x, vox, c.C, ldx, vox);
} else {
std::vector<float> h((size_t)(vox * ldx), 0.0f);
for (int64_t i = 0; i < vox; ++i)
for (int64_t ch = 0; ch < c.C; ++ch) h[(size_t)(i * ldx + ch)] = x[(size_t)(i * c.C + ch)];
dx = up_f32(h);
}
void* dy = up_f32(std::vector<float>((size_t)(yrows * ldy), -7.0f));
if (!dx || !dy) { ok(nm.c_str(), false, "hipMalloc failed"); continue; }
const int rc = launch(r, { pitched(dx, c.bf ? RAD_BF16 : RAD_F32, vox, c.C, ldx),
TI32({ 3 }, { (int32_t)c.F, (int32_t)c.Hp, (int32_t)c.Wp }),
pitched(dy, RAD_F32, yrows, K, ldy) },
{ PI("M", rows), PI("C", c.C), PI("pt", c.pt), PI("ph", c.ph),
PI("pw", c.pw), PS("mul", smul.c_str()), PS("add", sadd.c_str()),
PS("dtype", c.bf ? "bf16" : "f32") });
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
const std::vector<float> yall = down_f32(dy, (size_t)(yrows * ldy));
std::vector<float> got((size_t)(rows * K)), want((size_t)(rows * K));
int64_t moved = 0;
for (int64_t pr = 0; pr < yrows; ++pr)
for (int64_t col = 0; col < ldy; ++col) {
const float g = yall[(size_t)(pr * ldy + col)];
if (pr >= rows || col >= K) { moved += g != -7.0f; continue; }
const int64_t f = pr / (c.Hp * c.Wp), i = (pr / c.Wp) % c.Hp, j = pr % c.Wp;
const int64_t ch = col / (c.pt * c.ph * c.pw), sub = col % (c.pt * c.ph * c.pw);
const int64_t a = sub / (c.ph * c.pw), bb = (sub / c.pw) % c.ph, d = sub % c.pw;
const int64_t v = ((f * c.pt + a) * Hv + i * c.ph + bb) * Wv + j * c.pw + d;
const float p = x[(size_t)(v * c.C + ch)] * mul[(size_t)ch];
want[(size_t)(pr * K + col)] = p + add[(size_t)ch];
got[(size_t)(pr * K + col)] = g;
}
const int64_t bad = differ(got, want);
ok((nm + " exact, pitch columns and rows past the patches untouched").c_str(), bad == 0 && moved == 0,
fmt("%lld values differ, %lld markers written", (long long)bad, (long long)moved));
}
/* The round trip: patch rows unfolded to voxels and folded back, both lists the identity. */
const RadKernelInfo* ru = find(pl, "patch_unfold_f32");
if (!ru) { ok("patch_fold_f32 round trip", false, "patch_unfold_f32 absent"); return; }
for (const int64_t pt : { (int64_t)1, (int64_t)2 }) {
const int64_t C = 24, F = 3, Hp = 4, Wp = 5, ph = 2, pw = 2, K = C * pt * ph * pw;
const int64_t rows = F * Hp * Wp, vox = rows * pt * ph * pw;
std::vector<float> p = randv((size_t)(rows * K), 2.0f);
const std::vector<float> ones((size_t)C, 1.0f), zeros((size_t)C, 0.0f);
const std::string s1 = vid::list_of(ones), s0 = vid::list_of(zeros);
void* dp = up_f32(p);
void* dv = dalloc((size_t)(vox * C) * 4);
void* dq = dalloc((size_t)(rows * K) * 4);
std::vector<RadParam> ps = { PI("M", vox), PI("C", C), PI("pt", pt), PI("ph", ph),
PI("pw", pw), PS("mul", s1.c_str()), PS("add", s0.c_str()),
PS("dtype", "f32") };
const RadTensor geom = TI32({ 3 }, { (int32_t)F, (int32_t)Hp, (int32_t)Wp });
const int rc1 = launch(ru, { T(dp, RAD_F32, { rows, K }), geom, T(dv, RAD_F32, { vox, C }) }, ps);
ps[0] = PI("M", rows);
const int rc2 = launch(r, { T(dv, RAD_F32, { vox, C }), geom, T(dq, RAD_F32, { rows, K }) }, ps);
const int64_t bad = rc1 == RAD_OK && rc2 == RAD_OK ? differ(down_f32(dq, p.size()), p) : -1;
ok(fmt("patch_fold_f32 undoes patch_unfold_f32 at pt %lld", (long long)pt).c_str(), bad == 0,
fmt("rc %d / %d, %lld values differ", rc1, rc2, (long long)bad));
}
}
/* ------------------------------------------------------------------ flow_renoise */
void flow_renoise_cases(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "flow_renoise_f32");
if (!r) { ok("flow_renoise_f32", false, "row absent"); return; }
struct C { const char* what; int64_t M, n, ld, extra; float sigma; uint64_t seed; };
for (const C& c : { C{ "the video's patch rows", 37 * 42 * 24, 96, 96, 0, 0.37f, 0x123456789abcdefull },
C{ "the soundtrack's rows, pitched", 1152, 32, 40, 3, 0.8f, 42ull } }) {
const std::string nm = fmt("flow_renoise_f32 %s: %lld x %lld, sigma %.2f", c.what,
(long long)c.M, (long long)c.n, (double)c.sigma);
const int64_t rows = c.M + c.extra;
g_seed = 0x5eedull + (uint64_t)c.M;
const std::vector<float> x = randv((size_t)(rows * c.ld), 1.5f);
void* dx = up_f32(x);
void* ds = up_f32(std::vector<float>{ c.sigma });
void* dk = dalloc(8);
const uint32_t words[2] = { (uint32_t)c.seed, (uint32_t)(c.seed >> 32) };
if (!dx || !ds || !dk) { ok(nm.c_str(), false, "hipMalloc failed"); continue; }
st_memcpy(dk, words, 8, hipMemcpyHostToDevice);
/* x is a view of the buffer's first M rows; the rows after it are not x's. */
const int rc = launch(r, { T(ds, RAD_F32, { 1 }), T(dk, RAD_U32, { 2 }),
pitched(dx, RAD_F32, c.M, c.n, c.ld) },
{ PI("M", c.M), PI("n", c.n), PI("stream", 1), PS("dtype", "f32") });
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
const std::vector<float> got = down_f32(dx, x.size());
double e = 0, q = 0, worst = 0;
int64_t moved = 0;
for (int64_t k = 0; k < rows; ++k)
for (int64_t ch = 0; ch < c.ld; ++ch) {
const size_t i = (size_t)(k * c.ld + ch);
if (k >= c.M || ch >= c.n) { moved += got[i] != x[i]; continue; }
const float z = rad_philox_normal_s(c.seed, 1, (uint64_t)(k * c.n + ch));
const float a = (1.0f - c.sigma) * x[i];
const float bz = c.sigma * z;
const float want = a + bz;
e += (double)(got[i] - want) * (got[i] - want);
q += (double)want * want;
worst = std::max(worst, (double)std::fabs(got[i] - want));
}
const double rl = std::sqrt(e / q);
ok(fmt("%s (rel_l2 %.3g, worst %.3g; bounds 1e-6, 1e-5), the rest untouched", nm.c_str(),
rl, worst).c_str(),
rl <= 1e-6 && worst <= 1e-5 && moved == 0,
fmt("%lld values outside written", (long long)moved));
}
}
} /* namespace ups */
/* ---- a video generator's f32 forms, its biased GEMMs and its rotary, against libref's arithmetic
*
* A diffusion transformer's patch projections and heads, its timestep MLP and a video decoder's
@@ -11040,6 +11677,133 @@ static void video_perf(const Plugin& pl, int iters, const char* only) {
}
}
if (want("upscaler")) {
std::printf("\nconv3d_ndhwc (conv3d_ndhwc_bf16) beside gemm_nt_bias at bf16 "
"(gemm_bf16_nt_bias_tiled) at the same M, N and K = 27 cin: a video latent "
"upscaler's 3 x 3 x 3 convolutions, %d launches each\n", iters);
const RadKernelInfo* cv = find(pl, "conv3d_ndhwc_bf16");
const RadKernelInfo* gb = find(pl, "gemm_bf16_nt_bias_tiled");
struct V { const char* what; int64_t T, H, W, cin, cout; bool gemm; };
for (const V& v : { V{ "target block", 37, 84, 48, 512, 512, true },
V{ "source block", 37, 42, 24, 512, 512, true },
V{ "conv_in", 37, 42, 24, 24, 512, false },
V{ "conv_out", 37, 84, 48, 512, 24, false },
V{ "target block, 102 frames", 102, 84, 48, 512, 512, false } }) {
const int64_t M = v.T * v.H * v.W, K = 27 * v.cin, N = v.cout;
const double flop = 2.0 * (double)M * N * K;
if (v.gemm && gb) {
void* da = dalloc((size_t)(M * K) * 2);
void* dw = dalloc((size_t)(N * K) * 2);
void* db = dalloc((size_t)N * 4);
void* dy = dalloc((size_t)(M * N) * 2);
if (!da || !dw || !db || !dy) { std::printf(" %s: hipMalloc failed\n", v.what); dfree_all(); continue; }
rand_fill(da, (size_t)(M * K) * 2);
rand_fill(dw, (size_t)(N * K) * 2);
RadTensor tr = T(nullptr, RAD_BF16, { 1 });
absent(tr);
const double us = time_row(gb, { T(da, RAD_BF16, { M, K }), T(dw, RAD_BF16, { N, K }),
T(db, RAD_F32, { N }), tr, T(dy, RAD_BF16, { M, N }) },
{ PI("M", M), PI("N", N), PI("K", K), PS("dtype", "bf16") },
iters);
if (us < 0) std::printf(" %-26s gemm_nt_bias rc %d\n", v.what, (int)us);
else std::printf(" %-26s gemm_nt_bias M %6lld N %4lld K %5lld %9.1f us %6.1f TFLOP/s\n",
v.what, (long long)M, (long long)N, (long long)K, us, flop / (us * 1e6));
dfree_all();
}
if (!cv) { std::printf(" conv3d_ndhwc_bf16 absent\n"); break; }
void* dx = dalloc((size_t)(M * v.cin) * 2);
void* dw = dalloc((size_t)(N * K) * 2);
void* db = dalloc((size_t)N * 2);
void* dy = dalloc((size_t)(M * N) * 2);
if (!dx || !dw || !db || !dy) { std::printf(" %s: hipMalloc failed\n", v.what); dfree_all(); continue; }
rand_fill(dx, (size_t)(M * v.cin) * 2);
rand_fill(dw, (size_t)(N * K) * 2);
RadTensor tr = T(nullptr, RAD_BF16, { 1 });
absent(tr);
const double us = time_row(cv, { T(dx, RAD_BF16, { M, v.cin }), T(dw, RAD_BF16, { N, K }),
T(db, RAD_BF16, { N }),
TI32({ 3 }, { (int32_t)v.T, (int32_t)v.H, (int32_t)v.W }), tr,
T(dy, RAD_BF16, { M, N }) },
{ PI("M", M), PI("cin", v.cin), PI("cout", N), PI("k", 3),
PI("kt", 3), PS("dtype", "bf16") },
iters);
if (us < 0) std::printf(" %-26s conv3d rc %d\n", v.what, (int)us);
else std::printf(" %-26s conv3d M %6lld N %4lld K %5lld %9.1f us %6.1f TFLOP/s\n",
v.what, (long long)M, (long long)N, (long long)K, us, flop / (us * 1e6));
dfree_all();
}
/* The rest of a block at the target size, 512 channels: what each moves through memory. */
[&] {
std::printf(" the norm and elementwise ops at 84 x 48 x 37 x 512, %d launches each\n", iters);
const int64_t T_ = 37, H = 84, W = 48, n = 512, M = T_ * H * W, Ms = T_ * 42 * 24;
void* dx = dalloc((size_t)(M * n) * 2);
void* dy = dalloc((size_t)(M * n) * 2);
void* dw = dalloc((size_t)n * 5 * 2);
void* db = dalloc((size_t)n * 2);
void* dm = dalloc((size_t)(2 * n) * 2);
void* ds = dalloc((size_t)(32 * (2 + 3 * 1024)) * 4);
void* dp = dalloc((size_t)(Ms * 96) * 4);
void* dsig = dalloc(4);
void* dseed = dalloc(8);
if (!dx || !dy || !dw || !db || !dm || !ds || !dp || !dsig || !dseed) {
std::printf(" hipMalloc failed\n");
dfree_all();
return;
}
rand_fill(dx, (size_t)(M * n) * 2);
rand_fill(dw, (size_t)n * 5 * 2);
rand_fill(db, (size_t)n * 2);
rand_fill(dm, (size_t)(2 * n) * 2);
{
const float sg = 0.4f;
st_memcpy(dsig, &sg, 4, hipMemcpyHostToDevice);
}
const std::string ones = [&] {
std::string s;
for (int i = 0; i < 24; ++i) s += i ? " 1" : "1";
return s;
}();
const RadTensor geom = TI32({ 3 }, { (int32_t)T_, (int32_t)H, (int32_t)W });
struct E { const char* what; const char* row; std::vector<RadTensor> ts;
std::vector<RadParam> ps; double bytes; };
for (const E& e : {
E{ "group_norm, modulated, SiLU (x read twice)", "group_norm",
{ T(dx, RAD_BF16, { M, n }), T(db, RAD_BF16, { n }), T(db, RAD_BF16, { n }),
T(dm, RAD_BF16, { 2 * n }), T(ds, RAD_F32, { 32 * (2 + 3 * 1024) }),
T(dy, RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PI("groups", 32), PF("eps", 1e-5), PS("act", "silu"),
PS("dtype", "bf16") },
(double)M * n * 6 },
E{ "tconv_dw, 5 frames", "tconv_dw_bf16",
{ T(dx, RAD_BF16, { M, n }), T(dw, RAD_BF16, { n, 1, 5, 1, 1 }), T(db, RAD_BF16, { n }),
geom, T(dy, RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PI("k", 5), PS("dtype", "bf16") }, (double)M * n * 4 },
E{ "resize_bilinear, 42 x 24 -> 84 x 48", "resize_bilinear",
{ T(dx, RAD_BF16, { Ms, n }),
TI32({ 5 }, { (int32_t)T_, 42, 24, (int32_t)H, (int32_t)W }),
T(dy, RAD_BF16, { M, n }) },
{ PI("M", M), PI("n", n), PS("dtype", "bf16") }, (double)(M + Ms) * n * 2 },
E{ "patch_fold, 24 channels to 96-wide f32", "patch_fold_f32",
{ T(dx, RAD_BF16, { M, 24 }), TI32({ 3 }, { (int32_t)T_, 42, 24 }),
T(dp, RAD_F32, { Ms, 96 }) },
{ PI("M", Ms), PI("C", 24), PI("pt", 1), PI("ph", 2), PI("pw", 2),
PS("mul", ones.c_str()), PS("add", ones.c_str()), PS("dtype", "bf16") },
(double)M * 24 * 2 + (double)Ms * 96 * 4 },
E{ "flow_renoise, 96-wide f32 rows", "flow_renoise_f32",
{ T(dsig, RAD_F32, { 1 }), T(dseed, RAD_U32, { 2 }), T(dp, RAD_F32, { Ms, 96 }) },
{ PI("M", Ms), PI("n", 96), PI("stream", 1), PS("dtype", "f32") },
(double)Ms * 96 * 8 } }) {
const RadKernelInfo* r = find(pl, e.row);
if (!r) { std::printf(" %s: row absent\n", e.row); continue; }
const double us = time_row(r, e.ts, e.ps, iters);
if (us < 0) std::printf(" %-44s rc %d\n", e.what, (int)us);
else std::printf(" %-44s %9.1f us %6.1f GB/s\n", e.what, us, e.bytes / (us * 1e3));
}
dfree_all();
}();
}
if (want("mod")) {
std::printf("\ngemm_nt_q_bias at fp8a8 (gemm_fp8a8_bias_nt_m16): a modulation projection, its "
"50 timesteps into a column block of the table\n");
@@ -18503,6 +19267,13 @@ static void device_phase(const Plugin& pl) {
if (sel("flow_x0_step_f32")) vid::flow_x0_cases(pl);
if (sel("grid_pos3")) vid::grid_pos3_cases(pl);
if (sel("snake_aa_f32")) vid::snake_aa_cases(pl);
/* A video latent upscaler's ops, at its source and target sizes. */
if (sel("conv3d_ndhwc_bf16")) ups::conv3d_cases(pl);
if (sel("group_norm")) ups::group_norm_cases(pl);
if (sel("tconv_dw_bf16")) ups::tconv_dw_cases(pl);
if (sel("resize_bilinear")) ups::resize_bilinear_cases(pl);
if (sel("patch_fold_f32")) ups::patch_fold_cases(pl);
if (sel("flow_renoise_f32")) ups::flow_renoise_cases(pl);
if (sel("vsa_select_h128_bf16")) vsa::select_cases(pl);
if (sel("attn_vsa_h128_bf16")) vsa::attn_cases(pl);
if (sel("quant_cols_fp8_bf16")) vsa::quant_cols_cases(pl);
@@ -19052,7 +19823,9 @@ static void usage(void) {
" (the video decoder's bf16 linears), f32 (the f32 GEMMs), conv (the\n"
" audio decoder's convolutions), mod (the fp8 modulation projection),\n"
" attn and attn64 (dense attention at 3K to 106K rows, and over the\n"
" decoder's tiles); every section without one.\n"
" 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"
" --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"
+942
View File
@@ -0,0 +1,942 @@
// R4D -- a video latent upscaler's ops (docs/OPS.md, "The latent upscaler"): MiniMax-H3's 3D-conv
// latent resizer, a stack of 3x3x3 convolutions over 512-channel voxel rows with group norms,
// depthwise temporal convolutions and one spatial resize between two resolutions, plus the patch
// fold back to the latent's own rows and the re-noising of a clean latent.
//
// Activations are voxel rows: row (t, y, x) row-major over (frames, rows, columns), channels
// innermost. A request's volume is a device operand (`geom`, i32), never a parameter, so every
// kernel reads it on the device; one the operands cannot hold writes nothing, and rows past what
// the volume and the output hold are left alone.
//
// Each kernel rounds where its libref function does (libref/ref_video.cpp), under the library's
// -ffp-contract=off: the convolutions accumulate in f32 in their own order and round once (twice
// with the residual), the group norm's statistics are f32 merges in a fixed order, and the resize,
// the fold and the re-noise are the reference's arithmetic in its order (the noise through the
// device's log, sin and cos).
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "r4d_gdn_wmma.h"
#include "rad_philox.h"
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
namespace {
constexpr int kT = 256;
// Eight consecutive values of a bf16 or f32 row as floats, and a store rounded to its dtype.
__device__ __forceinline__ void ld8(const uint16_t* p, float* f) {
const uint4 u = *(const uint4*)p;
f[0] = bf16w_lo(u.x); f[1] = bf16w_hi(u.x); f[2] = bf16w_lo(u.y); f[3] = bf16w_hi(u.y);
f[4] = bf16w_lo(u.z); f[5] = bf16w_hi(u.z); f[6] = bf16w_lo(u.w); f[7] = bf16w_hi(u.w);
}
__device__ __forceinline__ void ld8(const float* p, float* f) {
const float4 a = *(const float4*)p, b = *(const float4*)(p + 4);
f[0] = a.x; f[1] = a.y; f[2] = a.z; f[3] = a.w; f[4] = b.x; f[5] = b.y; f[6] = b.z; f[7] = b.w;
}
__device__ __forceinline__ void st8(uint16_t* p, const float* f) {
uint4 u;
u.x = bf16x2_rne(f[0], f[1]);
u.y = bf16x2_rne(f[2], f[3]);
u.z = bf16x2_rne(f[4], f[5]);
u.w = bf16x2_rne(f[6], f[7]);
*(uint4*)p = u;
}
__device__ __forceinline__ void st8(float* p, const float* f) {
*(float4*)p = make_float4(f[0], f[1], f[2], f[3]);
*(float4*)(p + 4) = make_float4(f[4], f[5], f[6], f[7]);
}
// Eight per-channel values of an f32 or bf16 vector, its dtype known only at run time.
__device__ __forceinline__ void ld8w(const void* p, bool f32, int c, float* f) {
if (f32) ld8((const float*)p + c, f);
else ld8((const uint16_t*)p + c, f);
}
// The volume a request runs at: (T, H, W) and its row count, or false for a geometry the operands
// cannot hold (`rows` rows of the input).
__device__ __forceinline__ bool volume_of(const int* geom, long long rows, int* T, int* H, int* W,
long long* vol) {
*T = geom[0];
*H = geom[1];
*W = geom[2];
if (*T <= 0 || *H <= 0 || *W <= 0) return false;
*vol = (long long)*T * *H * *W;
return *vol <= rows;
}
// ---------------------------------------------------------------------------- conv3d_ndhwc
// An implicit GEMM over voxel rows: y[voxel][cout] = sum over (tap, cin) of x[voxel's tap
// neighbour][cin] * w[cout][tap][cin], the weight stored tap-major (r4d_layout.cpp relayouts
// PyTorch's [cout][cin][3][3][3] at load), so K = 27 cin runs over taps then channels and a 64-wide
// K tile of a voxel is eight 16-byte reads of one neighbour row. No im2col buffer.
//
// The block is gemm_nt_bias's large-grid tile (vit_gemm_wa_kernel, r4d_vit_bf16.hip): 128 output
// channels x 128 voxels, eight waves as 4 (weight) x 2 (voxels), a wave 2 x 4 WMMA tiles. The
// weight is the WMMA's A operand, read from global straight into registers; the voxels are its B
// operand, staged through LDS (double-buffered, one barrier a tile) and read by the four waves that
// share their rows. Staging both operands through LDS would take all of gfx1201's LDS bandwidth
// (64 bytes a clock per CU) at one WMMA every 16 clocks per SIMD; this costs 256 bytes of fragment
// reads and 64 of stores per WMMA, the weight's bytes coming through the vector cache. A lane's
// accumulator is eight consecutive output channels of one voxel, so the bias, the residual and the
// store are 16-byte accesses.
//
// K is relabelled inside a staged tile as gemm_nt_bias does (lane half h, k step s and element e
// hold k = 32h + 8s + e of the tile, in both operands), so a lane's weight fragments for a tile are
// one 64-byte run of its row and its voxel fragment one 16-byte LDS read; the summation order is
// that permutation's.
//
// The gather reads x as a raw buffer, whose reads at or past its size return zeros, so a neighbour
// outside the volume is the offset kOob and is staged with no select. A thread stages one 16-byte
// chunk column of four voxel rows, so it decomposes its four voxels into (t, y, x) once. With cin a
// multiple of 64 (C64) a K tile lies inside one tap: the four neighbours' byte offsets are
// recomputed only when the tap changes, every cin / 64 tiles, from a block-uniform (dt, dy, dx),
// and the tile's channel offset rides in the load's scalar offset. Otherwise (the 24-channel input)
// each chunk's tap follows its own K, every tile. The weight is a raw buffer too, the tile's K in
// the load's scalar offset and a chunk's in its immediate (the 24-channel input reads it through a
// guarded load instead, its last tile running past K), so neither operand's addresses cost vector
// arithmetic per tile.
//
// Measured on the R9700 at 300 W, warm, against gemm_nt_bias at bf16 at the same M, N and K = 27
// cin: 512 -> 512 at 84 x 48 x 37 148 TFLOP/s (the GEMM 146), at 42 x 24 x 37 149 (145). The
// select-and-pointer form of the gather this replaces ran 136 and 134: its loop issued twice the
// GEMM's vector instructions. The weight through global loads at a uniform base is 0.2-1% slower;
// raster groups of 4 or 16 bands are within noise of 8. 512 -> 24 (the output convolution) runs at
// 30 with 13/16 of its 128-wide channel tile idle, a few milliseconds of a whole upscale.
constexpr uint32_t kCTW = 2, kCTA = 4, kCWW = 4, kCWA = 2;
constexpr uint32_t kCBN = kCWW * kCTW * 16, kCBM = kCWA * kCTA * 16; // channels x voxels
constexpr uint32_t kCThreads = kCWW * kCWA * 32;
constexpr uint32_t kCFK = 64; // K a staged tile
constexpr uint32_t kCPB = kCFK * 2 + 16; // LDS row pitch, bytes
constexpr uint32_t kCCPR = kCFK * 2 / 16; // 16-byte chunks a row
constexpr uint32_t kCRS = kCThreads / kCCPR; // rows one staging pass
constexpr uint32_t kCSPT = kCBM / kCRS; // rows a thread stages
constexpr uint32_t kCWC = kCFK / 16; // a lane's weight chunks
constexpr uint32_t kCGroup = 8; // voxel bands a raster group
constexpr int kTaps = 27;
static_assert(kCBM % kCRS == 0, "whole rows a thread");
constexpr uint32_t kOob = 0xFFFF0000u; // past every x the shim accepts, after any added offset
// gfx12's raw-buffer descriptor word 3 (composable_kernel's for gfx11 and gfx12): offsets checked
// against the size, reads out of range returning zero.
constexpr int kBufWord3 = 0x31004000;
template <bool RES>
__device__ __forceinline__ unsigned short conv_finish(float acc, float bv, unsigned short r) {
unsigned short t = f32_to_bf16(acc + bv);
if constexpr (RES) t = f32_to_bf16(bf2f(r) + bf2f(t));
return t;
}
/* `vec` (host-checked): y, res and the bias take 16-byte accesses at every eight-column boundary.
* `xrows` bounds the volume the device geometry may name, `xbytes` is x's extent (at most kOob)
* and `Mcap` bounds the rows written. */
template <bool C64, bool RES, bool BF32>
__global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
const unsigned short* __restrict__ X, const unsigned short* __restrict__ Wt,
const void* __restrict__ bias, const unsigned short* R, unsigned short* C,
const int* __restrict__ geom, unsigned ldx, unsigned ldr, unsigned ldc, int Mcap, int xrows,
unsigned xbytes, int cin, int N, unsigned vec) {
typedef r4d_u32x4 U4;
__shared__ __attribute__((aligned(16))) unsigned char s_a[2][kCBM * kCPB];
int gT, gH, gW;
long long vol;
if (!volume_of(geom, xrows, &gT, &gH, &gW, &vol)) return;
const int HW = gH * gW;
const int Mv = vol < (long long)Mcap ? (int)vol : Mcap;
const uint32_t tid = threadIdx.x, lane = tid & 31u;
const uint32_t wave = __builtin_amdgcn_readfirstlane(tid >> 5);
const uint32_t ww = wave % kCWW, wa = wave / kCWW;
// Grouped raster, as gemm_nt_bias's: kCGroup voxel bands sweep the channels together, so the
// bands' shared halo rows and a channel slice's weight stay in L2 between them.
uint32_t bm = blockIdx.x, bn = blockIdx.y;
if (gridDim.x > kCGroup) {
const uint32_t per = kCGroup * gridDim.y;
const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x;
const uint32_t first = (lin / per) * kCGroup, r = lin % per;
const uint32_t gm = min(gridDim.x - first, kCGroup);
bm = first + r % gm;
bn = r / gm;
}
const uint32_t m0 = bm * kCBM, n0 = bn * kCBN;
if (m0 >= (uint32_t)Mv) return;
// This thread's staged rows and their voxels; a row past the volume sits outside every frame.
const uint32_t ch = tid % kCCPR;
int vm[kCSPT], vt[kCSPT], vy[kCSPT], vx[kCSPT];
uint32_t adst[kCSPT];
#pragma unroll
for (uint32_t i = 0; i < kCSPT; ++i) {
const uint32_t r = tid / kCCPR + kCRS * i;
const int m = (int)(m0 + r);
adst[i] = r * kCPB + ch * 16u;
vm[i] = m;
vt[i] = -4;
vy[i] = 0;
vx[i] = 0;
if (m < Mv) {
vt[i] = m / HW;
const int rem = m - vt[i] * HW;
vy[i] = rem / gW;
vx[i] = rem - vy[i] * gW;
}
}
// The four neighbours' byte offsets at a tap, kOob outside the volume; with C64 they include
// the thread's chunk column.
const __amdgpu_buffer_rsrc_t xr =
__builtin_amdgcn_make_buffer_rsrc(const_cast<unsigned short*>(X), 0, (int)xbytes, kBufWord3);
uint32_t off[kCSPT];
auto at_tap = [&](int tap) {
const int dt = tap / 9 - 1, dy = (tap / 3) % 3 - 1, dx = tap % 3 - 1;
const int delta = dt * HW + dy * gW + dx;
#pragma unroll
for (uint32_t i = 0; i < kCSPT; ++i) {
const bool ok = tap < kTaps && (unsigned)(vt[i] + dt) < (unsigned)gT &&
(unsigned)(vy[i] + dy) < (unsigned)gH &&
(unsigned)(vx[i] + dx) < (unsigned)gW;
off[i] = ok ? (uint32_t)(vm[i] + delta) * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob;
}
};
// Weight: lane row (l & 15) of each tile, elements [32h, 32h + 32) of the staged tile, as byte
// offsets to which a tile adds its K. Rows past N re-read row N-1; nothing past N is stored.
const uint32_t K = (uint32_t)kTaps * (uint32_t)cin;
const __amdgpu_buffer_rsrc_t wr = __builtin_amdgcn_make_buffer_rsrc(
const_cast<unsigned short*>(Wt), 0, (int)((uint32_t)N * K * 2u), kBufWord3);
uint32_t woff[kCTW];
#pragma unroll
for (uint32_t i = 0; i < kCTW; ++i)
woff[i] = min(n0 + (ww * kCTW + i) * 16u + (lane & 15u), (uint32_t)N - 1u) * K * 2u +
(lane >> 4) * kCFK;
const uint32_t frow = (wa * kCTA * 16u + (lane & 15u)) * kCPB + (lane >> 4) * kCFK;
v8f acc[kCTW][kCTA];
#pragma unroll
for (uint32_t i = 0; i < kCTW; ++i)
#pragma unroll
for (uint32_t j = 0; j < kCTA; ++j) acc[i][j] = (v8f)(0.f);
auto mma_tile = [&](const unsigned char* sa, const U4 (&cur)[kCTW][kCWC]) {
#pragma unroll
for (uint32_t s = 0; s < kCWC; ++s) {
v8bf bfr_[kCTA];
#pragma unroll
for (uint32_t j = 0; j < kCTA; ++j)
bfr_[j] = __builtin_bit_cast(v8bf, *(const U4*)(sa + frow + j * 16u * kCPB + s * 16u));
#pragma unroll
for (uint32_t i = 0; i < kCTW; ++i) {
const v8bf af = __builtin_bit_cast(v8bf, cur[i][s]);
#pragma unroll
for (uint32_t j = 0; j < kCTA; ++j) acc[i][j] = mma(af, bfr_[j], acc[i][j]);
}
}
};
// The K walk: C64 counts a tap's channel tiles (uniform); otherwise each thread follows its
// chunk's (tap, channel) and the last tile may run past K, its weight chunks zeroed there.
const uint32_t nk = (K + kCFK - 1u) / kCFK;
const uint32_t ctiles = (uint32_t)cin / kCFK;
int tap = 0;
uint32_t cc = 0, ci = 0;
if constexpr (C64) {
at_tap(0);
} else {
tap = (int)(ch * 8u / (uint32_t)cin);
ci = ch * 8u - (uint32_t)tap * (uint32_t)cin;
at_tap(tap);
}
auto advance = [&]() {
if constexpr (C64) {
if (++cc == ctiles) {
cc = 0;
at_tap(++tap);
}
} else {
ci += kCFK;
while (ci >= (uint32_t)cin) { ci -= (uint32_t)cin; ++tap; }
at_tap(tap);
}
};
U4 pa[kCSPT], w0[kCTW][kCWC], w1[kCTW][kCWC];
const U4 zero = (U4)(0u);
/* Every load is issued unconditionally (the last tile's prefetch re-reads the last tile), so
* the loop's waits count exactly. */
auto load = [&](uint32_t k0, U4 (&w)[kCTW][kCWC]) {
#pragma unroll
for (uint32_t i = 0; i < kCSPT; ++i) {
if constexpr (C64)
pa[i] = __builtin_amdgcn_raw_buffer_load_b128(xr, (int)off[i], (int)(cc * kCFK * 2u), 0);
else
pa[i] = __builtin_amdgcn_raw_buffer_load_b128(xr, (int)(off[i] + ci * 2u), 0, 0);
}
const unsigned char* const wb = (const unsigned char*)Wt + (size_t)k0 * 2u;
#pragma unroll
for (uint32_t i = 0; i < kCTW; ++i)
#pragma unroll
for (uint32_t c = 0; c < kCWC; ++c) {
if constexpr (C64) {
w[i][c] = __builtin_amdgcn_raw_buffer_load_b128(wr, (int)(woff[i] + c * 16u),
(int)(k0 * 2u), 0);
} else {
const bool in = k0 + (lane >> 4) * (kCFK / 2u) + c * 8u < K;
w[i][c] = in ? *(const U4*)(wb + (in ? woff[i] + c * 16u : 0u)) : zero;
}
}
};
auto stage = [&](uint32_t buf) {
unsigned char* const sa = s_a[buf];
#pragma unroll
for (uint32_t i = 0; i < kCSPT; ++i) *(U4*)(sa + adst[i]) = pa[i];
};
auto tile = [&](uint32_t t, uint32_t buf, U4 (&cur)[kCTW][kCWC], U4 (&nxt)[kCTW][kCWC]) {
stage(buf);
lds_barrier();
if (t + 1u < nk) advance();
load(min(t + 1u, nk - 1u) * kCFK, nxt);
mma_tile(s_a[buf], cur);
};
load(0, w0);
uint32_t t = 0;
for (; t + 1u < nk; t += 2u) {
tile(t, 0, w0, w1);
tile(t + 1u, 1, w1, w0);
}
if (t < nk) tile(t, 0, w0, w1);
// D is [channel][voxel]: eight consecutive channels of one output row a lane a tile. The
// residual is read by the thread that stores the same element, so it may alias y.
#pragma unroll
for (uint32_t i = 0; i < kCTW; ++i)
#pragma unroll
for (uint32_t j = 0; j < kCTA; ++j) {
const uint32_t m = m0 + (wa * kCTA + j) * 16u + (lane & 15u);
const uint32_t n = n0 + (ww * kCTW + i) * 16u + (lane >> 4) * 8u;
if (m >= (uint32_t)Mv) continue;
const v8f v = acc[i][j];
if (vec && n + 8u <= (uint32_t)N) {
float bv[8];
if constexpr (BF32) {
const float4 b0 = *(const float4*)((const float*)bias + n);
const float4 b1 = *(const float4*)((const float*)bias + n + 4);
bv[0] = b0.x; bv[1] = b0.y; bv[2] = b0.z; bv[3] = b0.w;
bv[4] = b1.x; bv[5] = b1.y; bv[6] = b1.z; bv[7] = b1.w;
} else {
const uint4 b = *(const uint4*)((const unsigned short*)bias + n);
const uint32_t d[4] = { b.x, b.y, b.z, b.w };
#pragma unroll
for (uint32_t e = 0; e < 8; ++e) bv[e] = bf2f((unsigned short)(d[e / 2] >> (16 * (e % 2))));
}
uint32_t rr[4] = { 0u, 0u, 0u, 0u };
if constexpr (RES) {
const uint4 r4 = *(const uint4*)(R + (size_t)m * ldr + n);
rr[0] = r4.x; rr[1] = r4.y; rr[2] = r4.z; rr[3] = r4.w;
}
uint32_t o[4];
#pragma unroll
for (uint32_t e = 0; e < 8; e += 2)
o[e / 2] = (uint32_t)conv_finish<RES>(v[e], bv[e], (unsigned short)rr[e / 2]) |
((uint32_t)conv_finish<RES>(v[e + 1], bv[e + 1],
(unsigned short)(rr[e / 2] >> 16)) << 16);
*(uint4*)(C + (size_t)m * ldc + n) = make_uint4(o[0], o[1], o[2], o[3]);
} else {
#pragma unroll
for (uint32_t e = 0; e < 8; ++e) {
if (n + e >= (uint32_t)N) continue;
const float bv = BF32 ? ((const float*)bias)[n + e]
: bf2f(((const unsigned short*)bias)[n + e]);
const unsigned short r = RES ? R[(size_t)m * ldr + n + e] : (unsigned short)0;
C[(size_t)m * ldc + n + e] = conv_finish<RES>(v[e], bv, r);
}
}
}
}
// ---------------------------------------------------------------------------- group_norm
// nn.GroupNorm over all of y's rows in three launches, every reduction in a fixed order so two runs
// 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).
// 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).
// 3. apply: a thread an 8-channel chunk, v = (x - mean) rstd w + b, the modulation and SiLU in
// f32, one rounding.
//
// The scratch beyond the 2 groups leading values holds part p of group g at 3 (g kGnParts + p).
constexpr int kGnParts = 1024;
__device__ __forceinline__ void chan_merge(float& n, float& mean, float& m2, float nb, float mb,
float m2b) {
if (nb == 0.0f) return;
if (n == 0.0f) { n = nb; mean = mb; m2 = m2b; return; }
const float nab = n + nb;
const float f = nb / nab;
const float d = mb - mean;
mean = mean + d * f;
m2 = m2 + m2b + d * d * n * f;
n = nab;
}
/* `cpr_log`: log2 of the chunks a row (n / 8, a power of two dividing the block); `gs8` the chunks
* a group. */
template <typename TX>
__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) {
__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 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[8];
ld8(x + (size_t)r * ldx + c * 8, v);
if (cnt == 0.0f) shift = v[0];
#pragma unroll
for (int j = 0; j < 8; ++j) {
const float d = v[j] - shift;
s1 += d;
s2 += d * d;
}
cnt += 8.0f;
}
float mean = 0.0f, m2 = 0.0f;
if (cnt > 0.0f) {
const float q = s1 / cnt;
mean = shift + q;
m2 = fmaxf(s2 - s1 * q, 0.0f);
}
sh[0][tid] = cnt;
sh[1][tid] = mean;
sh[2][tid] = m2;
__syncthreads();
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;
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;
o[0] = N;
o[1] = Mn;
o[2] = Q;
}
}
__global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats, int groups,
int parts, 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;
float N = 0.0f, Mn = 0.0f, Q = 0.0f;
for (int p = tid; p < parts; p += kT) chan_merge(N, Mn, Q, P[3 * p], P[3 * p + 1], P[3 * p + 2]);
sh[0][tid] = N;
sh[1][tid] = Mn;
sh[2][tid] = Q;
__syncthreads();
for (int s = kT / 2; s > 0; s >>= 1) {
if (tid < s) {
float a = sh[0][tid], b = sh[1][tid], q = sh[2][tid];
chan_merge(a, b, q, sh[0][tid + s], sh[1][tid + s], sh[2][tid + s]);
sh[0][tid] = a;
sh[1][tid] = b;
sh[2][tid] = q;
}
__syncthreads();
}
if (tid == 0) {
const float var = sh[2][0] / sh[0][0];
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. */
template <typename TX, typename TY>
__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,
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);
if (r >= M) return;
const int ck = tid & ((1 << cpr_log) - 1), c = ck * 8;
const int g = ck / gs8;
const float mean = stats[2 * g], rstd = stats[2 * g + 1];
float v[8], wv[8], bv[8];
ld8(x + (size_t)r * ldx + c, v);
ld8w(w, wf != 0, c, wv);
ld8w(b, bf != 0, c, bv);
#pragma unroll
for (int j = 0; j < 8; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j];
if (modk) {
float sc[8], sf[8];
ld8w(mod, modk == 2, c, sc);
ld8w(mod, modk == 2, n + c, sf);
#pragma unroll
for (int j = 0; j < 8; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j];
}
if (silu) {
#pragma unroll
for (int j = 0; j < 8; ++j) v[j] = v[j] / (1.0f + expf(-v[j]));
}
st8(y + (size_t)r * ldy + c, v);
}
// ---------------------------------------------------------------------------- tconv_dw
// A depthwise convolution along the frames: a thread one 8-channel chunk of one frame position,
// walking every frame with the k-frame window in registers, so each input row is read once.
// kTdFB frames a step: their loads are issued together, then the step's outputs, each the taps in
// ascending order in f32 and one rounding after the bias. The grid strides over (position, chunk).
constexpr int kTdK = 5;
constexpr int kTdFB = 4;
__global__ __launch_bounds__(kT) void tconv_dw_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const uint16_t* __restrict__ b,
uint16_t* __restrict__ y, const int* __restrict__ geom, int Mcap, int xrows, int n, int ldx,
int ldy) {
int gT, gH, gW;
long long vol;
if (!volume_of(geom, xrows, &gT, &gH, &gW, &vol)) return;
const int Mv = vol < (long long)Mcap ? (int)vol : Mcap;
const int P = gH * gW, cpr = n / 8;
const long long pairs = (long long)P * cpr;
constexpr int H = kTdK / 2, WIN = kTdFB + kTdK - 1;
for (long long q = (long long)blockIdx.x * kT + threadIdx.x; q < pairs;
q += (long long)gridDim.x * kT) {
const int p = (int)(q / cpr), c = (int)(q % cpr) * 8;
float wv[8][kTdK], bv[8];
#pragma unroll
for (int e = 0; e < 8; ++e) {
#pragma unroll
for (int j = 0; j < kTdK; ++j) wv[e][j] = bf2f(w[(size_t)(c + e) * kTdK + j]);
}
ld8(b + c, bv);
// win[i] holds frame t0 - H + i; frames outside [0, T) stay zero and add nothing.
uint4 win[WIN];
#pragma unroll
for (int i = 0; i < WIN; ++i) win[i] = make_uint4(0u, 0u, 0u, 0u);
#pragma unroll
for (int i = H; i < kTdK - 1; ++i)
if (i - H < gT) win[i] = *(const uint4*)(x + ((size_t)(i - H) * P + p) * ldx + c);
for (int t0 = 0; t0 < gT; t0 += kTdFB) {
#pragma unroll
for (int i = kTdK - 1; i < WIN; ++i) {
const int f = t0 - H + i;
win[i] = f < gT ? *(const uint4*)(x + ((size_t)f * P + p) * ldx + c)
: make_uint4(0u, 0u, 0u, 0u);
}
#pragma unroll
for (int s = 0; s < kTdFB; ++s) {
const int t = t0 + s;
const long long row = (long long)t * P + p;
if (t >= gT || row >= Mv) break;
float acc[8];
#pragma unroll
for (int e = 0; e < 8; ++e) acc[e] = 0.0f;
#pragma unroll
for (int j = 0; j < kTdK; ++j) {
const int f = t + j - H;
if (f < 0 || f >= gT) continue;
float xv[8];
const uint4 u = win[s + j];
xv[0] = bf16w_lo(u.x); xv[1] = bf16w_hi(u.x); xv[2] = bf16w_lo(u.y);
xv[3] = bf16w_hi(u.y); xv[4] = bf16w_lo(u.z); xv[5] = bf16w_hi(u.z);
xv[6] = bf16w_lo(u.w); xv[7] = bf16w_hi(u.w);
#pragma unroll
for (int e = 0; e < 8; ++e) acc[e] = acc[e] + wv[e][j] * xv[e];
}
#pragma unroll
for (int e = 0; e < 8; ++e) acc[e] = acc[e] + bv[e];
st8(y + (size_t)row * ldy + c, acc);
}
#pragma unroll
for (int i = 0; i < kTdK - 1; ++i) win[i] = win[i + kTdFB];
}
}
}
// ---------------------------------------------------------------------------- resize_bilinear
// torch's bilinear resize of each frame, align_corners=False at a given size (upsample_bilinear2d's
// source index and lambdas, in f32): a thread one 8-channel chunk of one output voxel, its two
// rows' and two columns' taps recomputed from its indices.
__device__ __forceinline__ void bil_axis(int o, int in, int out, int* i0, int* i1, float* l0,
float* l1) {
const float s = (float)in / (float)out;
float src = s * ((float)o + 0.5f) - 0.5f;
src = src < 0.0f ? 0.0f : src;
*i0 = (int)src;
*i1 = *i0 + (*i0 < in - 1 ? 1 : 0);
*l1 = src - (float)*i0;
*l0 = 1.0f - *l1;
}
template <typename TV>
__global__ __launch_bounds__(kT) void resize_bilinear_kernel(
const TV* __restrict__ x, TV* __restrict__ y, const int* __restrict__ geom, long long cap,
long long xrows, int cpr, int ldx, int ldy) {
const int T = geom[0], h = geom[1], w = geom[2], H = geom[3], W = geom[4];
if (T <= 0 || h <= 0 || w <= 0 || H <= 0 || W <= 0) return;
if ((long long)T * h * w > xrows) return;
const long long rows = (long long)T * H * W;
const long long id = (long long)blockIdx.x * kT + threadIdx.x;
const long long r = id / cpr;
if (r >= rows || r >= cap) return;
const int c = (int)(id % cpr) * 8;
const int t = (int)(r / ((long long)H * W));
const int rem = (int)(r - (long long)t * H * W);
const int oi = rem / W, oj = rem - oi * W;
int i0, i1, j0, j1;
float ly0, ly1, lx0, lx1;
bil_axis(oi, h, H, &i0, &i1, &ly0, &ly1);
bil_axis(oj, w, W, &j0, &j1, &lx0, &lx1);
const size_t f0 = (size_t)t * h * w;
float a[8], b[8], d[8], e[8], o[8];
ld8(x + (f0 + (size_t)i0 * w + j0) * ldx + c, a);
ld8(x + (f0 + (size_t)i0 * w + j1) * ldx + c, b);
ld8(x + (f0 + (size_t)i1 * w + j0) * ldx + c, d);
ld8(x + (f0 + (size_t)i1 * w + j1) * ldx + c, e);
#pragma unroll
for (int k = 0; k < 8; ++k)
o[k] = ly0 * (lx0 * a[k] + lx1 * b[k]) + ly1 * (lx0 * d[k] + lx1 * e[k]);
st8(y + (size_t)r * ldy + c, o);
}
// ---------------------------------------------------------------------------- patch_fold
// patch_unfold's inverse: voxel rows to patch rows, f32, a thread an output value. The two lists
// are f32 kernel arguments.
constexpr int kMaxChan = 64;
struct ChanList { float v[kMaxChan]; };
template <typename TX>
__global__ __launch_bounds__(kT) void patch_fold_kernel(
const TX* __restrict__ x, const int* __restrict__ geom, float* __restrict__ y, ChanList mul,
ChanList add, int C, int pt, int ph, int pw, int ldx, int ldy, long long cap, long long xrows) {
const int F = geom[0], Hp = geom[1], Wp = geom[2];
if (F <= 0 || Hp <= 0 || Wp <= 0) return;
const long long Hv = (long long)Hp * ph, Wv = (long long)Wp * pw;
if ((long long)F * pt * Hv * Wv > xrows) return;
const int K = C * pt * ph * pw;
const long long rows = (long long)F * Hp * Wp;
const long long id = (long long)blockIdx.x * kT + threadIdx.x;
const long long r = id / K;
if (r >= rows || r >= cap) return;
const int col = (int)(id % K);
const int c = col / (pt * ph * pw), sub = col % (pt * ph * pw);
const int a = sub / (ph * pw), bb = (sub / pw) % ph, d = sub % pw;
const long long f = r / ((long long)Hp * Wp), i = (r / Wp) % Hp, j = r % Wp;
const long long vox = ((f * pt + a) * Hv + i * ph + bb) * Wv + j * pw + d;
float v;
if constexpr (sizeof(TX) == 2) v = bf2f(x[vox * ldx + c]);
else v = x[vox * ldx + c];
y[r * ldy + col] = v * mul.v[c] + add.v[c];
}
// ---------------------------------------------------------------------------- flow_renoise
// x = (1 - s) x + s z, z element k n + c of the (seed, stream) normal stream: a thread a value,
// each product and the sum one f32 rounding.
__global__ __launch_bounds__(kT) void flow_renoise_kernel(
const float* __restrict__ sigma, const uint32_t* __restrict__ seed, float* __restrict__ x,
int n, int ldx, long long total, unsigned long long stream) {
const long long id = (long long)blockIdx.x * kT + threadIdx.x;
if (id >= total) return;
const long long k = id / n;
const int c = (int)(id % n);
const float s = sigma[0];
const uint64_t sd = (uint64_t)seed[0] | ((uint64_t)seed[1] << 32);
const float z = rad_philox_normal_s(sd, stream, (uint64_t)id);
float* p = x + k * ldx + c;
const float a = (1.0f - s) * *p;
const float bz = s * z;
*p = a + bz;
}
inline bool is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; }
inline bool is_f32(const RadTensor* t) { return t && t->dtype == RAD_F32; }
inline bool is_i32(const RadTensor* t) { return t && t->dtype == RAD_I32; }
// A row-major operand's row count and pitch, the pitch a multiple of eight elements and the base
// 16-byte aligned, so a row's eight-element chunks are 16- or 32-byte accesses.
inline bool rows8(const RadTensor* t, long long n, long long* rows, long long* ld) {
if (!t || n <= 0 || (n & 7)) return false;
*ld = r4d_rows_pitch(t, n, rows);
return *ld >= 0 && !(*ld & 7) && !((uintptr_t)t->data & 15);
}
// A space-separated list of floats kept in f32, as libref's parse_f32_list.
int parse_f32_list(const char* s, float* out, int max) {
int n = 0;
while (s && *s) {
char* end = nullptr;
const double v = std::strtod(s, &end);
if (end == s) break;
if (n == max) return max + 1;
out[n++] = (float)v;
s = end;
}
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
/* ------------------------------------------------------------------ conv3d_ndhwc */
enum { C3_X = 0, C3_W, C3_B, C3_GEOM, C3_RES, C3_Y };
extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) {
const RadTensor *x = r4d_opt(a, C3_X), *w = r4d_opt(a, C3_W), *b = r4d_opt(a, C3_B);
const RadTensor *geom = r4d_opt(a, C3_GEOM), *res = r4d_opt(a, C3_RES), *y = r4d_opt(a, C3_Y);
if (!x || !w || !b || !geom || !y) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(w) || !is_bf16(y) || (!is_bf16(b) && !is_f32(b)) ||
!is_i32(geom) || (res && !is_bf16(res)))
return R4D_NO(RAD_E_DTYPE);
const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0);
/* 3 x 3 x 3 only: the tap decode is the kernel's constant. */
if (r4d_geti_or(a, "k", 3) != 3 || r4d_geti_or(a, "kt", 3) != 3) return R4D_NO(RAD_E_SHAPE);
if (cin <= 0 || cout <= 0 || (cin & 7)) return R4D_NO(RAD_E_SHAPE);
const long long K = (long long)kTaps * cin;
if (r4d_numel(w) < cout * K || r4d_numel(b) < cout || r4d_numel(geom) < 3)
return R4D_NO(RAD_E_SHAPE);
if (!r4d_contig(w) || !r4d_contig(b) || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE);
long long rx = 0, ldx = 0, ry = 0, rr = 0;
if (!rows8(x, cin, &rx, &ldx) || !r4d_aligned(r4d_p(w), 16)) return R4D_NO(RAD_E_STRIDE);
const long long ldy = r4d_rows_pitch(y, cout, &ry);
const long long ldr = res ? r4d_rows_pitch(res, cout, &rr) : 0;
if (ldy < 0 || ldr < 0) return R4D_NO(RAD_E_STRIDE);
/* The rows written are the device volume's, as libref's; the outputs bound them (and the
* grid), M is not read. */
long long Mcap = ry;
if (res && Mcap > rr) Mcap = rr;
/* Byte offsets into x and the weight are 32-bit; x's extent (its last row ends at cin) is
* the gather's buffer size, below the out-of-range offset. */
const long long xbytes = ((rx - 1) * ldx + cin) * 2;
if (Mcap <= 0 || rx <= 0 || xbytes > (long long)kOob || cout * K * 2 >= (1ll << 32) ||
Mcap >= (1ll << 31) || cin > 16384)
return R4D_NO(RAD_E_SHAPE);
auto Xp = (const unsigned short*)r4d_p(x);
auto Wp = (const unsigned short*)r4d_p(w);
auto Rp = (const unsigned short*)r4d_p(res);
auto Cp = (unsigned short*)r4d_wp(y);
const void* Bp = r4d_p(b);
const unsigned vec = (ldy % 8) == 0 && r4d_aligned(Cp, 16) && r4d_aligned(Bp, 16) &&
(!res || ((ldr % 8) == 0 && r4d_aligned(Rp, 16)));
const dim3 grid((unsigned)((Mcap + kCBM - 1) / kCBM), (unsigned)((cout + kCBN - 1) / kCBN));
const bool c64 = cin % kCFK == 0, bf32 = is_f32(b);
#define C3_L(C6, RS, BF) \
return R4D_EMIT(stream, (conv3d_kernel<C6, RS, BF>), grid, dim3(kCThreads), 0, Xp, Wp, Bp, Rp, \
Cp, (const int*)r4d_p(geom), (unsigned)ldx, (unsigned)ldr, (unsigned)ldy, \
(int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, vec)
#define C3_RES(C6, BF) do { if (res) C3_L(C6, true, BF); C3_L(C6, false, BF); } while (0)
#define C3_BF(C6) do { if (bf32) C3_RES(C6, true); C3_RES(C6, false); } while (0)
if (c64) C3_BF(true);
C3_BF(false);
#undef C3_BF
#undef C3_RES
#undef C3_L
}
/* ------------------------------------------------------------------ group_norm */
enum { GN_X = 0, GN_W, GN_B, GN_MOD, GN_STATS, GN_Y };
extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
const RadTensor *x = r4d_opt(a, GN_X), *w = r4d_opt(a, GN_W), *b = r4d_opt(a, GN_B);
const RadTensor *mod = r4d_opt(a, GN_MOD), *st = r4d_opt(a, GN_STATS), *y = r4d_opt(a, GN_Y);
if (!x || !w || !b || !st || !y) return R4D_NO(RAD_E_INVAL);
if ((!is_bf16(x) && !is_f32(x)) || (!is_bf16(y) && !is_f32(y)) || (!is_bf16(w) && !is_f32(w)) ||
(!is_bf16(b) && !is_f32(b)) || (mod && !is_bf16(mod) && !is_f32(mod)) || !is_f32(st))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), groups = r4d_geti_or(a, "groups", 0);
const char* act = r4d_gets(a, "act");
int silu = 0;
if (act && *act) {
if (!std::strcmp(act, "silu")) silu = 1;
else if (std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL);
}
/* A thread an 8-channel chunk inside one group, a row's chunks a power of two dividing the
* 256-thread block. */
const int cpr_log = (n > 0 && !(n & 7)) ? log2_exact(n / 8) : -1;
if (cpr_log < 0 || n / 8 > kT || groups <= 0 || groups > kT || n % groups ||
(n / groups) % 8)
return R4D_NO(RAD_E_SHAPE);
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);
if (!r4d_contig(w) || !r4d_contig(b) || (mod && !r4d_contig(mod)) || !r4d_contig(st) ||
!r4d_aligned(r4d_p(w), 16) || !r4d_aligned(r4d_p(b), 16) || !r4d_aligned(r4d_p(mod), 16))
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. */
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;
/* 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 / 8);
float* S = (float*)r4d_wp(st);
const float eps = (float)r4d_getf(a, "eps", 1e-5);
int rc;
if (is_f32(x))
rc = R4D_EMIT(stream, gn_part_kernel<float>, dim3((unsigned)parts), dim3(kT), 0,
(const float*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx,
(int)rpp);
else
rc = R4D_EMIT(stream, gn_part_kernel<uint16_t>, dim3((unsigned)parts), dim3(kT), 0,
(const uint16_t*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx,
(int)rpp);
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);
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));
#define GN_A(TX, TY) \
return R4D_EMIT(stream, (gn_apply_kernel<TX, TY>), 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), \
modk, silu)
if (is_f32(x)) {
if (is_f32(y)) GN_A(float, float);
GN_A(float, uint16_t);
}
if (is_f32(y)) GN_A(uint16_t, float);
GN_A(uint16_t, uint16_t);
#undef GN_A
}
/* ------------------------------------------------------------------ tconv_dw */
enum { TD_X = 0, TD_W, TD_B, TD_GEOM, TD_Y };
extern "C" int r4d_rad_tconv_dw(const RadArgs* a, RadStream stream) {
const RadTensor *x = r4d_opt(a, TD_X), *w = r4d_opt(a, TD_W), *b = r4d_opt(a, TD_B);
const RadTensor *geom = r4d_opt(a, TD_GEOM), *y = r4d_opt(a, TD_Y);
if (!x || !w || !b || !geom || !y) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(w) || !is_bf16(b) || !is_bf16(y) || !is_i32(geom))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), k = r4d_geti_or(a, "k", 0);
if (n <= 0 || (n & 7) || k != kTdK || r4d_numel(w) < n * k || r4d_numel(b) < n ||
r4d_numel(geom) < 3)
return R4D_NO(RAD_E_SHAPE);
if (!r4d_contig(w) || !r4d_contig(b) || !r4d_contig(geom) || !r4d_aligned(r4d_p(b), 16))
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);
/* The device volume's rows, at most y's; M is not read. */
const long long M = ry;
if (M <= 0 || rx * ldx >= (1ll << 40)) return R4D_NO(RAD_E_SHAPE);
/* One frame position's chunks a thread, at most the rows' worth; the kernel strides over the
* device geometry's (position, chunk) pairs. */
const long long pairs = M * (n / 8);
const unsigned blocks = (unsigned)std::min<long long>((pairs + kT - 1) / kT, 2048);
return R4D_EMIT(stream, tconv_dw_kernel, dim3(blocks), dim3(kT), 0,
(const uint16_t*)r4d_p(x), (const uint16_t*)r4d_p(w),
(const uint16_t*)r4d_p(b), (uint16_t*)r4d_wp(y), (const int*)r4d_p(geom),
(int)M, (int)std::min<long long>(rx, (1ll << 31) - 1), (int)n, (int)ldx,
(int)ldy);
}
/* ------------------------------------------------------------------ resize_bilinear */
enum { RB_X = 0, RB_GEOM, RB_Y };
extern "C" int r4d_rad_resize_bilinear(const RadArgs* a, RadStream stream) {
const RadTensor *x = r4d_opt(a, RB_X), *geom = r4d_opt(a, RB_GEOM), *y = r4d_opt(a, RB_Y);
if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL);
if ((!is_bf16(x) && !is_f32(x)) || x->dtype != y->dtype || !is_i32(geom))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
if (n <= 0 || (n & 7) || r4d_numel(geom) < 5) return R4D_NO(RAD_E_SHAPE);
if (!r4d_contig(geom)) 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);
/* The device volume's rows, at most y's; M is not read. */
const long long M = ry;
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
const long long total = M * (n / 8);
const dim3 grid((unsigned)((total + kT - 1) / kT));
if (is_f32(x))
return R4D_EMIT(stream, resize_bilinear_kernel<float>, grid, dim3(kT), 0,
(const float*)r4d_p(x), (float*)r4d_wp(y), (const int*)r4d_p(geom), M, rx,
(int)(n / 8), (int)ldx, (int)ldy);
return R4D_EMIT(stream, resize_bilinear_kernel<uint16_t>, grid, dim3(kT), 0,
(const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(y), (const int*)r4d_p(geom), M,
rx, (int)(n / 8), (int)ldx, (int)ldy);
}
/* ------------------------------------------------------------------ patch_fold */
enum { PF_X = 0, PF_GEOM, PF_Y };
extern "C" int r4d_rad_patch_fold(const RadArgs* a, RadStream stream) {
const RadTensor *x = r4d_opt(a, PF_X), *geom = r4d_opt(a, PF_GEOM), *y = r4d_opt(a, PF_Y);
if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL);
if ((!is_f32(x) && !is_bf16(x)) || !is_f32(y) || !is_i32(geom)) return R4D_NO(RAD_E_DTYPE);
const long long C = r4d_geti_or(a, "C", 0), pt = r4d_geti_or(a, "pt", 0);
const long long ph = r4d_geti_or(a, "ph", 0), pw = r4d_geti_or(a, "pw", 0);
ChanList mul{}, add{};
if (C <= 0 || C > kMaxChan || pt <= 0 || ph <= 0 || pw <= 0 ||
parse_f32_list(r4d_gets(a, "mul"), mul.v, kMaxChan) != C ||
parse_f32_list(r4d_gets(a, "add"), add.v, kMaxChan) != C || r4d_numel(geom) < 3)
return R4D_NO(RAD_E_SHAPE);
const long long K = C * pt * ph * pw;
long long rx = 0, ry = 0;
const long long ldx = r4d_rows_pitch(x, C, &rx), ldy = r4d_rows_pitch(y, K, &ry);
if (ldx < 0 || ldy < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE);
/* The device geometry's patches, at most y's rows; M is not read. */
const long long M = ry;
if (M <= 0 || rx <= 0) return R4D_NO(RAD_E_SHAPE);
const long long total = M * K;
const dim3 grid((unsigned)((total + kT - 1) / kT));
if (is_f32(x))
return R4D_EMIT(stream, patch_fold_kernel<float>, grid, dim3(kT), 0,
(const float*)r4d_p(x), (const int*)r4d_p(geom), (float*)r4d_wp(y), mul,
add, (int)C, (int)pt, (int)ph, (int)pw, (int)ldx, (int)ldy, M, rx);
return R4D_EMIT(stream, patch_fold_kernel<uint16_t>, grid, dim3(kT), 0,
(const uint16_t*)r4d_p(x), (const int*)r4d_p(geom), (float*)r4d_wp(y), mul,
add, (int)C, (int)pt, (int)ph, (int)pw, (int)ldx, (int)ldy, M, rx);
}
/* ------------------------------------------------------------------ flow_renoise */
enum { FR_SIGMA = 0, FR_SEED, FR_X };
extern "C" int r4d_rad_flow_renoise(const RadArgs* a, RadStream stream) {
const RadTensor *sg = r4d_opt(a, FR_SIGMA), *seed = r4d_opt(a, FR_SEED), *x = r4d_opt(a, FR_X);
if (!sg || !seed || !x) return R4D_NO(RAD_E_INVAL);
if (!is_f32(sg) || !is_f32(x) || (seed->dtype != RAD_U32 && seed->dtype != RAD_I32))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), sm = r4d_geti_or(a, "stream", 0);
if (n <= 0 || sm < 0 || r4d_numel(sg) < 1 || r4d_numel(seed) < 2) return R4D_NO(RAD_E_SHAPE);
long long rx = 0;
const long long ldx = r4d_rows_pitch(x, n, &rx);
if (ldx < 0 || !r4d_contig(seed)) return R4D_NO(RAD_E_STRIDE);
/* Every row of x, as libref's; M is not read. */
const long long M = rx;
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
const long long total = M * n;
return R4D_EMIT(stream, flow_renoise_kernel, dim3((unsigned)((total + kT - 1) / kT)), dim3(kT),
0, (const float*)r4d_p(sg), (const uint32_t*)r4d_p(seed), (float*)r4d_wp(x),
(int)n, (int)ldx, total, (unsigned long long)sm);
}