radiance 1.8.0

- video: MiniMax-H3 and FastVideo's FastH3 8-Step V2, a video with its stereo soundtrack from text
  on OpenAI's /v1/videos, block fp8 on two cards
- music: MiniMax-Music3, songs from lyrics and a description on /v1/audio/speech
- speech: Breeze-TTS-2 on /v1/audio/speech and vLLM-Omni's realtime WebSocket
- runtime LoRA adapters beside the base model, picked per request by `model` (baKon, #105)
- several agent streams keep their cached history: --checkpoint-slots auto, the new default, sizes
  the snapshot store by --max-num-seqs (#108)
- the Swift 1.5 27B W4 releases convert and serve: compressed-tensors AWQ and GPTQ int4, AutoRound,
  ModelOpt NVFP4 (#110)
- the image's host tests pass where perf_event_open is refused, as in BuildKit's sandbox (#106)
- plugin ABI 21: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-18 11:38:37 +02:00
1 parent 91127395ee
commit 7a7707a955
179 files changed
+37542 -1892

No files matched your search

+14 -1
View File
@@ -72,9 +72,22 @@ set(R4D_UNITS
# implicit-GEMM convolution and pixel ops.
"r4d_attn_gen|"
"r4d_gen|"
# The audio generator: a vocoder's 1-D convolutions and snake activation, the guided top-k
# sampler for a frame's codes, the frame and window ops, and a depth decoder's short attention.
"r4d_audio|"
# The video generator: a diffusion transformer's modulated RMS norm and sampler step, the video
# decoder's patch unfold, tiles, stitch and rotary positions, and the soundtrack decoder's
# alias-free SnakeBeta.
"r4d_video|"
# Video sparse attention: the tile selection a distilled video transformer was trained with and
# the block-sparse attention over it.
"r4d_vsa|"
# Vision tower ops: layer norm, the learned-grid position embedding, and the biased GEMM with
# activation and residual fused into its store.
"r4d_vit_bf16|"
# The same biased GEMM over f32 operands (a diffusion transformer's patch projections and heads,
# a video decoder's 1x1 projections), on the f32 FMA tile r4d_audio's f32 convolutions share.
"r4d_gemm_f32_nt_bias|"
"r4d_gdn_chunk_scan_k128_v128_c64_bf16|-mcumode"
"r4d_gdn_conv_w4_h128_bf16|"
"r4d_gdn_kkt_solve_k128_c64_bf16|"
@@ -149,7 +162,7 @@ set(R4D_UNITS
# expert_scale, each one kernel for a chain of small ones.
"r4d_norm_join_bf16|"
"r4d_expert_scale_bf16|"
# Runtime LoRA's two halves (lora_shrink, lora_expand), per-row adapter slot; scalar f32 v1.
# Runtime LoRA's two halves (lora_shrink, lora_expand), per-row adapter slot: scalar and tiled rows.
"r4d_lora_bf16|"
"r4d_dflash_conv_t2_g16_bf16|"
"r4d_dflash_select_bf16|"
+1 -1
View File
@@ -59,7 +59,7 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set.
| `dflash_conv_t2_g16_bf16` | the drafter's causal conv, two taps, 16 groups |
| `dflash_select_bf16` | the drafter's candidate selector: edge scores and the greedy path walk |
| `dequant_w4_bf16` | unpacks a 4-bit fragment-ordered weight back to bf16 |
| `lora_shrink` / `lora_expand` | runtime LoRA's two halves beside a trunk GEMM, each row's adapter read from a per-row slot on the device (base rows untouched). Tiled rows (preferred): `t = x A[slot]^T` WMMA bf16 over 16-row x 16-j tiles with a K split fixed by K and R (`lora_shrink_wmma`, `lora_shrink_wmma_q` for fp8/i8 codes), `y += scale ⊙ (t B[slot]^T)` over 32-row x 128-column tiles with B[slot] staged in LDS, libref's bytes (`lora_expand_tiled`); a tile of base rows leaves on one ballot, a mixed tile runs one pass a slot. Scalar v1 rows (`_scalar`): one block a row / one thread an output, and the f16/f32-activation shrink. A row's bytes are independent of M in every row |
| `lora_shrink` / `lora_expand` | runtime LoRA's two halves beside a trunk GEMM, each row's adapter read from a per-row slot on the device (base rows untouched). Tiled rows (preferred): `t = x A[slot]^T` WMMA bf16 over 16-row x 16-j tiles with a K split fixed by K and R (`lora_shrink_wmma`, `lora_shrink_wmma_q` for fp8/i8 codes), `y += scale ⊙ (t B[slot]^T)` over 32-row x 128-column tiles with B[slot] staged in LDS, libref's bytes (`lora_expand_tiled`); a tile of base rows leaves on one ballot, a mixed tile runs one pass a slot. Scalar rows (`_scalar`): one block a row / one thread an output, and the f16/f32-activation shrink. A row's bytes are independent of M in every row |
| `quant_act_i8` / `quant_act_i8_asum` | per-row int8 activation quantiser, in the r4d GEMMs' fragment byte order; the `_asum` form also emits the per-group row sums the asymmetric GEMMs need |
| `had_quant_act_i8` | the same with a block Walsh-Hadamard rotation first, which is what makes one scale per row viable |
| `rmsnorm_had_quant_i8` | residual add, RMS norm, rotate and quantise in one kernel |
+41 -4
View File
@@ -1,19 +1,20 @@
# libr4d/isa: reading the machine code the kernels became
Nine scripts and four microbenchmarks. A wall-clock timer cannot tell "this kernel is slow" from
Nine scripts and six microbenchmarks. A wall-clock timer cannot tell "this kernel is slow" from
"this kernel is at the memory wall"; the disassembly plus one calibration number can, without a GPU
run. The trace tools are the exception: they need the GPU, and they are the only instruments here
that report the geometry a kernel was launched with rather than every geometry it could have had.
BUILD=/path/to/build ./res.sh | head -40 # every kernel: vgpr/lds/scratch
BUILD=... ./dis.sh r4d_gemm_fp8a8 ILb1ELb0ELj8ELj1ELj8ELj64ELb0E
BUILD=... ./dis.sh r4d_gemm_fp8a8 gemm_8a8_prefill_kernelILb0E
BUILD=... ./waterfall.sh # divergent VGPR indices, per kernel
./loop.sh # its K loop, classified
./trace.sh traces/dec -- ./bin/radiance ... # then: ./tsum.sh traces/dec/k_kernel_trace.csv
`res.sh` prints mangled names; the substring `dis.sh` takes picks one template instantiation, and
the parameter order is in the kernel's declaration (`gemm_fp8a8_kernel` is
`<Full, AW, NT, MT, MW, FK, GATED, I8>`, so `ILb1ELb0ELj8ELj1ELj8ELj64ELb0E` is the prefill tile).
`<Full, NT, MW, FK, GATED, I8, BIAS>`, so `ILb1ELj4ELj8ELj256ELb0E` is the narrow tile at four token
tiles and eight waves; `gemm_8a8_prefill_kernelILb0E` is the fp8 prefill tile).
`loop.sh` anchors on `v_wmma` by default and takes the smallest backward branch containing every
anchor, because a largest-loop search finds the epilogue, a long unrolled store chain.
@@ -34,10 +35,13 @@ anchor, because a largest-loop search finds the epilogue, a long unrolled store
| `graphrate.hip` | what a dispatch costs the host to submit, and what capturing a fixed sequence saves |
| `launchreg.hip` + `launchreg_lib.hip` | whether a launch costs more when the module registers more kernels, and what crossing into a `.so` costs |
| `blockcopy.hip` | contiguous versus scattered device-to-host copy, at KV-block granularity |
| `wmmapeak.hip` | sustained fp8, iu8 and bf16 WMMA TFLOP/s at the card's clock and power limit, with the sclk, power and temperature it ran at |
| `wmmamix.hip` | what a VALU instruction, an LDS read and an LDS write cost next to fp8 WMMA, and LDS bandwidth per CU |
Each script's header states its traps and how to read its output. The microbenchmarks are built by
hand: `clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 <name>.hip -o <name>` for `isarate`,
`graphrate` and `blockcopy`, and `build_launchreg.sh` for the two-object launchreg pair.
`graphrate`, `blockcopy`, `wmmapeak` and `wmmamix`, and `build_launchreg.sh` for the two-object
launchreg pair.
## Instruction slot cost on gfx1201
@@ -62,6 +66,39 @@ gfx1201 has no dense 16x16x32 fp8 WMMA (`llvm-mc -mcpu=gfx1201` rejects it). The
form is `v_swmmac_f32_16x16x32_fp8_fp8`, the 2:4 sparse one, so the GEMMs here already use the
widest dense op there is.
## Sustained WMMA rate, and what the rest of a K loop costs
`wmmapeak.hip` measures the ceiling a GEMM is held against: random operands rotating through eight
fragments, every block resident, eight seconds after eight of warm-up. At the 300 W limit, with
three blocks a WGP (the occupancy of the prefill tiles):
| op | TFLOP/s | sclk | per CU per clock |
|---|---|---|---|
| `v_wmma_f32_16x16x16_fp8_fp8` | 330 | 2536 MHz | 2037 FLOP (8 clocks a WMMA a SIMD) |
| `v_wmma_i32_16x16x16_iu8` | 334 | 2561 MHz | 2038 |
| `v_wmma_f32_16x16x16_bf16` | 170 | 2703 MHz | 984 (16 clocks) |
The power limit, not issue, sets these: with zero operands the same fp8 loop runs 418 TFLOP/s at
3.25 GHz, so how hard the multipliers switch is most of the power, and a GEMM timed on constant
operands reads fast (the fp8 prefill tile: 262 TFLOP/s on `--perfw8`'s 0x38 fill, 205 on random
codes; `--perfvideo` fills random ones). At full occupancy the fp8 run sometimes
settles at 260-270 TFLOP/s with hwmon reporting 2.8 GHz, a state in which the reported clock
overstates the delivered one; quote the three-blocks figure.
`wmmamix.hip` adds one kind of instruction at a time to eight independent WMMA chains a wave. With
zero operands (the clock is then real), against 8.36 SIMD clocks a WMMA at six waves a SIMD:
- a VALU instruction costs 1.05-1.4 SIMD clocks, serial with the WMMA (8 adds per 8 WMMA: 9.63
clocks a WMMA; 64: 16.7). A fold's arithmetic does not hide under the matrix work; VOPD pairs
are the only way to halve it.
- LDS serves 64 bytes a clock per CU, loads and stores alike (32 `ds_load_b64` or 16
`ds_load_b128` per 8 WMMA: 31.5 clocks a WMMA). At the WMMA rate that is 256 bytes of LDS per
fp8 WMMA and 512 per bf16 one. Below the limit a load costs about a clock of issue.
- nine fragment reads and two staging stores per 8 WMMA (a 1 x 8 tile staging both operands)
run at 73% with nothing else in the loop; four and one at 90%.
- one dependent chain a wave runs as fast as eight at six waves a SIMD (96%); occupancy moves the
rate from 94% (four waves) to 98% (twelve).
## The profiler
`rocprofv3 --pmc` does not work on this platform. With any counter set and any kernel filter, on
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/sh
# Disassemble ONE kernel out of one translation unit, into $ISA_OUT/one.s.
#
# BUILD=... dis.sh r4d_gemm_fp8a8 ILb1ELb0ELj8ELj1ELj8ELj64ELb0E
# BUILD=... dis.sh r4d_gemm_fp8a8 gemm_8a8_prefill_kernelILb0E
#
# The pattern is a substring of the MANGLED name, which is how a template instantiation is named:
# res.sh prints those, and the template parameter order is in the kernel declaration. llvm-objdump
+229
View File
@@ -0,0 +1,229 @@
// What a VALU instruction, an LDS read and an LDS write cost next to fp8 WMMA on gfx1201, what LDS
// delivers per CU, and how the WMMA rate depends on waves per SIMD. A GEMM's K loop is a mix of
// these, and the answer decides its tile: whether the fold's arithmetic hides under the matrix work
// (it does not: VALU and WMMA issue serially on a SIMD) and how many LDS bytes a WMMA may cost
// (64 B a clock per CU, loads and stores together, so 256 B per WMMA at the WMMA rate).
//
// Every row is a kernel of eight independent WMMA chains a wave plus V VALU adds, L LDS loads and S
// LDS stores per eight WMMA, at the occupancy its LDS padding allows (every block resident, so no
// tail). It runs about a second; the result is SIMD clocks per WMMA from the elapsed time and the
// card's mean sclk (hwmon freq1_input), so it is clock-independent as long as the clock is real.
//
// clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 wmmamix.hip -o wmmamix
// ./wmmamix [z]
//
// With `z` every operand is zero: the multipliers barely switch, the card stays under its power
// limit at its top clock, and the per-clock costs are clean. With random operands a power limit
// holds the clock down and, at some settings, stretches it below what hwmon reports; wmmapeak.hip
// is the throughput instrument for that case.
#include <hip/hip_runtime.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dirent.h>
#include <string>
#include <thread>
#include <type_traits>
#include <vector>
typedef int i2v __attribute__((ext_vector_type(2)));
typedef float f8v __attribute__((ext_vector_type(8)));
typedef unsigned u2v __attribute__((ext_vector_type(2)));
typedef unsigned u4v __attribute__((ext_vector_type(4)));
// V VALU adds, L LDS loads of B bytes a lane, S ds_store_b64 per eight WMMA; C independent chains
// (8 = all independent, 1 = one dependent chain).
template <int LDS, int V, int L, int B, int S, int C>
__global__ __launch_bounds__(256) void mix(const uint32_t* src, float* out, int iters) {
__shared__ __attribute__((aligned(16))) char pad[LDS];
const uint32_t lane = threadIdx.x & 31u, wave = threadIdx.x >> 5;
pad[threadIdx.x] = (char)threadIdx.x;
__syncthreads();
const uint32_t* p = src + ((blockIdx.x & 63u) * 32u + lane) * 32u;
i2v a[8], b[8];
#pragma unroll
for (int i = 0; i < 8; ++i) {
a[i] = (i2v){ (int)p[2 * i], (int)p[2 * i + 1] };
b[i] = (i2v){ (int)p[16 + 2 * i], (int)p[17 + 2 * i] };
}
f8v c[8];
#pragma unroll
for (int i = 0; i < 8; ++i) c[i] = (f8v)(0.0f);
float f[32];
#pragma unroll
for (int i = 0; i < 32; ++i) f[i] = (float)(threadIdx.x + i);
const float kk = 1.0000001f;
typedef typename std::conditional<B == 8, u2v, u4v>::type RT;
RT r[L > 0 ? L : 1];
#pragma unroll
for (int i = 0; i < (L > 0 ? L : 1); ++i) r[i] = RT{};
// A fragment read's address pattern: lane row (l & 15) at a padded pitch, half k by lane half,
// so sixteen rows land on distinct banks.
const uint32_t la = (uint32_t)(uintptr_t)pad + (lane & 15u) * (B == 8 ? 72u : 144u) +
(lane >> 4) * B + wave * 2304u;
const uint32_t sa = (uint32_t)(uintptr_t)pad + threadIdx.x * 8u;
const u2v sv = { threadIdx.x, lane };
for (int it = 0; it < iters; ++it) {
#pragma unroll
for (int i = 0; i < 8; ++i) {
c[i % C] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a[i], b[(i + 3) & 7],
c[i % C]);
#pragma unroll
for (int v = i * V / 8; v < (i + 1) * V / 8; ++v)
asm volatile("v_add_f32 %0, %0, %1" : "+v"(f[v & 31]) : "v"(kk));
#pragma unroll
for (int l = i * L / 8; l < (i + 1) * L / 8; ++l) {
if constexpr (B == 8)
asm volatile("ds_load_b64 %0, %1 offset:%2" : "+v"(r[l]) : "v"(la), "i"((l % 8) * 16));
else
asm volatile("ds_load_b128 %0, %1 offset:%2" : "+v"(r[l]) : "v"(la), "i"((l % 4) * 32));
}
#pragma unroll
for (int s = i * S / 8; s < (i + 1) * S / 8; ++s)
asm volatile("ds_store_b64 %0, %1 offset:%2" ::"v"(sa), "v"(sv), "i"((s % 8) * 2048));
}
if (L > 0 || S > 0) asm volatile("s_wait_dscnt 0x0" ::: "memory");
}
float s = 0.0f;
#pragma unroll
for (int i = 0; i < 8; ++i)
#pragma unroll
for (int t = 0; t < 8; ++t) s += c[i][t];
#pragma unroll
for (int i = 0; i < 32; ++i) s += f[i];
#pragma unroll
for (int i = 0; i < (L > 0 ? L : 1); ++i) s += (float)(r[i].x ^ r[i].y);
s += (float)pad[(threadIdx.x * 7u) % LDS];
if (s == -1.0f) out[0] = s;
}
static long read_long(const std::string& path) {
FILE* f = std::fopen(path.c_str(), "r");
if (!f) return -1;
long v = -1;
if (std::fscanf(f, "%ld", &v) != 1) v = -1;
std::fclose(f);
return v;
}
static std::string g_hw; // the hwmon directory of device 0
template <int LDS, int V, int L, int B, int S, int C>
static void run(const char* name, const uint32_t* d, float* o) {
hipDeviceProp_t prop;
(void)hipGetDeviceProperties(&prop, 0);
int per = 0;
(void)hipOccupancyMaxActiveBlocksPerMultiprocessor(&per, mix<LDS, V, L, B, S, C>, 256, 0);
const int blocks = per * prop.multiProcessorCount;
const int iters = 20000;
hipEvent_t e0, e1;
(void)hipEventCreate(&e0);
(void)hipEventCreate(&e1);
(void)hipEventRecord(e0);
hipLaunchKernelGGL((mix<LDS, V, L, B, S, C>), dim3(blocks), dim3(256), 0, 0, d, o, iters);
(void)hipEventRecord(e1);
(void)hipEventSynchronize(e1);
float ms1 = 0;
(void)hipEventElapsedTime(&ms1, e0, e1);
const int reps = (int)(1000.0f / ms1) + 1;
for (int r = 0; r < reps / 3; ++r)
hipLaunchKernelGGL((mix<LDS, V, L, B, S, C>), dim3(blocks), dim3(256), 0, 0, d, o, iters);
(void)hipDeviceSynchronize();
std::atomic<bool> stop{ false };
double mhz = 0, watt = 0;
int n = 0;
std::thread th([&] {
while (!stop) {
const long f = read_long(g_hw + "/freq1_input");
if (f > 0) { mhz += f / 1e6; watt += read_long(g_hw + "/power1_average") / 1e6; ++n; }
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
});
(void)hipEventRecord(e0);
for (int r = 0; r < reps; ++r)
hipLaunchKernelGGL((mix<LDS, V, L, B, S, C>), dim3(blocks), dim3(256), 0, 0, d, o, iters);
(void)hipEventRecord(e1);
(void)hipEventSynchronize(e1);
stop = true;
th.join();
float ms = 0;
(void)hipEventElapsedTime(&ms, e0, e1);
const double clk = n ? mhz / n : 0.0;
const double wmma = 8.0 * iters * (double)blocks * 8.0 * reps;
// 64 CUs x 2 SIMDs; HIP's multiProcessorCount is the WGP count, 32.
const double simds = 4.0 * prop.multiProcessorCount;
const double clk_per = simds * (double)ms * 1e-3 * clk * 1e6 / wmma;
std::printf(" %-28s %4.1f waves/SIMD %5.0f MHz %4.0f W %6.1f TFLOP/s %6.2f clk/WMMA/SIMD"
" (%5.1f%% of 8)\n",
name, (double)blocks * 8.0 / simds, clk, n ? watt / n : 0.0,
wmma * 8192.0 / ((double)ms * 1e9), clk_per, 800.0 / clk_per);
(void)hipEventDestroy(e0);
(void)hipEventDestroy(e1);
}
int main(int argc, char** argv) {
const bool zero = argc > 1 && argv[1][0] == 'z';
char bus[64] = {};
if (hipDeviceGetPCIBusId(bus, sizeof(bus), 0) == hipSuccess) {
for (char* q = bus; *q; ++q) *q = (char)std::tolower(*q);
const std::string base = std::string("/sys/bus/pci/devices/") + bus + "/hwmon";
if (DIR* dd = opendir(base.c_str())) {
while (dirent* e = readdir(dd))
if (!std::strncmp(e->d_name, "hwmon", 5)) { g_hw = base + "/" + e->d_name; break; }
closedir(dd);
}
}
if (g_hw.empty()) { std::printf("no hwmon node for device 0: the clock cannot be read\n"); return 1; }
const size_t nw = 64 * 32 * 32;
std::vector<uint32_t> h(nw);
uint64_t x = 88172645463325252ull;
for (auto& w : h) {
uint32_t v = 0;
for (int b = 0; b < 4; ++b) {
x ^= x << 13; x ^= x >> 7; x ^= x << 17;
const uint32_t r = (uint32_t)x;
v |= (((r & 0x80u) | ((6u + (r >> 8) % 4u) << 3) | (r & 7u)) & 0xFFu) << (8 * b);
}
w = zero ? 0u : v;
}
uint32_t* d;
float* o;
(void)hipMalloc(&d, nw * 4);
(void)hipMalloc(&o, 4);
(void)hipMemcpy(d, h.data(), nw * 4, hipMemcpyHostToDevice);
std::printf("fp8 WMMA mixes, %s operands, sensors %s\n", zero ? "zero" : "random", g_hw.c_str());
std::printf("occupancy (blocks a WGP set by LDS)\n");
run<65536, 0, 0, 8, 0, 8>("wmma only", d, o);
run<40000, 0, 0, 8, 0, 8>("wmma only", d, o);
run<32768, 0, 0, 8, 0, 8>("wmma only", d, o);
run<20480, 0, 0, 8, 0, 8>("wmma only", d, o);
run<8192, 0, 0, 8, 0, 8>("wmma only", d, o);
std::printf("dependent chains\n");
run<40000, 0, 0, 8, 0, 1>("1 chain", d, o);
run<40000, 0, 0, 8, 0, 4>("4 chains", d, o);
std::printf("VALU adds per 8 WMMA\n");
run<40000, 8, 0, 8, 0, 8>("8 valu", d, o);
run<40000, 16, 0, 8, 0, 8>("16 valu", d, o);
run<40000, 32, 0, 8, 0, 8>("32 valu", d, o);
run<40000, 64, 0, 8, 0, 8>("64 valu", d, o);
std::printf("LDS loads per 8 WMMA (a bf16 or fp8 fragment read is 256 or 512 B a wave)\n");
run<40000, 0, 4, 8, 0, 8>("4 ds_load_b64", d, o);
run<40000, 0, 9, 8, 0, 8>("9 ds_load_b64", d, o);
run<40000, 0, 12, 8, 0, 8>("12 ds_load_b64", d, o);
run<40000, 0, 16, 8, 0, 8>("16 ds_load_b64", d, o);
run<40000, 0, 32, 8, 0, 8>("32 ds_load_b64", d, o);
run<40000, 0, 8, 16, 0, 8>("8 ds_load_b128", d, o);
run<40000, 0, 16, 16, 0, 8>("16 ds_load_b128", d, o);
std::printf("LDS stores per 8 WMMA\n");
run<40000, 0, 0, 8, 2, 8>("2 ds_store_b64", d, o);
run<40000, 0, 0, 8, 16, 8>("16 ds_store_b64", d, o);
std::printf("mixes\n");
run<40000, 0, 9, 8, 2, 8>("9 load + 2 store", d, o);
run<40000, 0, 4, 8, 1, 8>("4 load + 1 store", d, o);
run<40000, 16, 9, 8, 2, 8>("16 valu + 9 load + 2 store", d, o);
return 0;
}
+242
View File
@@ -0,0 +1,242 @@
// Sustained WMMA throughput on gfx1201 at the card's own clock and power limit: the ceiling a GEMM
// is measured against. isarate.hip answers a ratio of issue slots and needs no clock; this answers
// TFLOP/s, which at a power limit depends on how hard the multipliers switch, so the operands are
// random bits rotating through eight A and eight B fragments (consecutive instructions never see
// the same inputs) and the run is long enough for the clock to settle under the limit.
//
// Each wave issues eight independent accumulator chains back to back, every block of the launch is
// resident at once (the grid is the occupancy calculator's answer times the WGP count, so there is
// no tail), and launches repeat for the requested seconds after a warm-up of the same length. The
// card's own sensors (hwmon freq1_input, power1_average, temp edge) are sampled from a host thread
// during the timed window; the hwmon node is found from the HIP device's PCI bus id.
//
// clang++ -x hip -O3 -std=c++17 --offload-arch=gfx1201 wmmapeak.hip -o wmmapeak
// ./wmmapeak [device] [seconds] [tile]
//
// A non-zero `tile` pads every block to 36864 B of unused LDS, the fp8 prefill tile's footprint
// (three blocks a WGP), to read the ceiling at that occupancy; 0 is full occupancy.
#include <hip/hip_runtime.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dirent.h>
#include <string>
#include <thread>
#include <vector>
typedef int i2v __attribute__((ext_vector_type(2)));
typedef int i8v __attribute__((ext_vector_type(8)));
typedef float f8v __attribute__((ext_vector_type(8)));
typedef __bf16 v8bf __attribute__((ext_vector_type(8)));
enum { kFp8 = 0, kBf16 = 1, kIu8 = 2 };
// Operand dwords a lane holds per fragment: two for the 8-bit forms, four for bf16.
template <int OP> struct Frag;
template <> struct Frag<kFp8> { typedef i2v T; static constexpr int dw = 2; };
template <> struct Frag<kIu8> { typedef i2v T; static constexpr int dw = 2; };
template <> struct Frag<kBf16> { typedef v8bf T; static constexpr int dw = 4; };
template <int OP>
__device__ __forceinline__ f8v mma(typename Frag<OP>::T a, typename Frag<OP>::T b, f8v c) {
if constexpr (OP == kFp8) return __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c);
if constexpr (OP == kBf16) return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c);
if constexpr (OP == kIu8)
return __builtin_bit_cast(f8v, __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(
true, a, true, b, __builtin_bit_cast(i8v, c), false));
}
template <int OP>
__device__ __forceinline__ typename Frag<OP>::T load_frag(const uint32_t* p) {
typedef typename Frag<OP>::T T;
union { uint32_t w[Frag<OP>::dw]; T f; } u;
#pragma unroll
for (int i = 0; i < Frag<OP>::dw; ++i) u.w[i] = p[i];
return u.f;
}
// `src` holds 16 fragments' worth of random dwords per lane (8 A, then 8 B); `out` receives a sum
// that is never -1 in practice, so the chains stay live.
template <int OP, int LDS>
__global__ __launch_bounds__(256) void peak(const uint32_t* __restrict__ src, float* out,
int iters) {
__shared__ char pad[LDS ? LDS : 4];
pad[threadIdx.x & 3] = (char)threadIdx.x;
typedef typename Frag<OP>::T T;
constexpr int dw = Frag<OP>::dw;
const uint32_t lane = threadIdx.x & 31u;
const uint32_t* p = src + ((size_t)(blockIdx.x & 63u) * 32u + lane) * 16u * dw;
T a[8], b[8];
#pragma unroll
for (int i = 0; i < 8; ++i) { a[i] = load_frag<OP>(p + i * dw); b[i] = load_frag<OP>(p + (8 + i) * dw); }
f8v c[8];
#pragma unroll
for (int i = 0; i < 8; ++i) c[i] = (f8v)(0.0f);
for (int it = 0; it < iters; ++it) {
#pragma unroll
for (int i = 0; i < 8; ++i) c[i] = mma<OP>(a[i], b[(i + 3) & 7], c[i]);
}
float s = 0.0f;
#pragma unroll
for (int i = 0; i < 8; ++i)
#pragma unroll
for (int t = 0; t < 8; ++t) s += c[i][t];
if (s == -1.0f) out[0] = s + (float)pad[0];
}
// ---- the card's sensors ------------------------------------------------------------------------
static std::string hwmon_dir(int dev) {
char bus[64] = {};
if (hipDeviceGetPCIBusId(bus, sizeof(bus), dev) != hipSuccess) return "";
for (char* q = bus; *q; ++q) *q = (char)std::tolower(*q);
const std::string base = std::string("/sys/bus/pci/devices/") + bus + "/hwmon";
DIR* d = opendir(base.c_str());
if (!d) return "";
std::string found;
while (dirent* e = readdir(d))
if (!std::strncmp(e->d_name, "hwmon", 5)) { found = base + "/" + e->d_name; break; }
closedir(d);
return found;
}
static long read_long(const std::string& path) {
FILE* f = std::fopen(path.c_str(), "r");
if (!f) return -1;
long v = -1;
if (std::fscanf(f, "%ld", &v) != 1) v = -1;
std::fclose(f);
return v;
}
struct Sensors {
double mhz_sum = 0, mhz_min = 1e30, mhz_max = 0, w_sum = 0, t_max = 0;
int n = 0;
};
static void sample(const std::string& hw, std::atomic<bool>* stop, Sensors* s) {
while (!stop->load()) {
const long f = read_long(hw + "/freq1_input"), p = read_long(hw + "/power1_average"),
t = read_long(hw + "/temp1_input");
if (f > 0) {
const double mhz = (double)f / 1e6;
s->mhz_sum += mhz;
if (mhz < s->mhz_min) s->mhz_min = mhz;
if (mhz > s->mhz_max) s->mhz_max = mhz;
s->w_sum += p > 0 ? (double)p / 1e6 : 0.0;
if ((double)t / 1e3 > s->t_max) s->t_max = (double)t / 1e3;
++s->n;
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
template <int OP, int LDS>
static void run(const char* name, int dev, double secs, const uint32_t* d_src, float* d_out,
const std::string& hw) {
hipDeviceProp_t prop;
(void)hipGetDeviceProperties(&prop, dev);
int per = 0;
(void)hipOccupancyMaxActiveBlocksPerMultiprocessor(&per, peak<OP, LDS>, 256, 0);
const int blocks = per * prop.multiProcessorCount;
// About 20 ms a launch at any rate: calibrate on one short launch.
int iters = 4096;
hipEvent_t e0, e1;
(void)hipEventCreate(&e0);
(void)hipEventCreate(&e1);
hipLaunchKernelGGL((peak<OP, LDS>), dim3(blocks), dim3(256), 0, 0, d_src, d_out, iters);
(void)hipEventRecord(e0);
hipLaunchKernelGGL((peak<OP, LDS>), dim3(blocks), dim3(256), 0, 0, d_src, d_out, iters);
(void)hipEventRecord(e1);
(void)hipEventSynchronize(e1);
float ms = 0;
(void)hipEventElapsedTime(&ms, e0, e1);
iters = (int)((double)iters * 20.0 / (ms > 0.01f ? ms : 0.01f));
if (iters < 256) iters = 256;
const int launches = (int)(secs * 1000.0 / 20.0) + 1;
// Warm-up of the same length, so the timed window starts at the settled clock.
for (int i = 0; i < launches; ++i)
hipLaunchKernelGGL((peak<OP, LDS>), dim3(blocks), dim3(256), 0, 0, d_src, d_out, iters);
(void)hipDeviceSynchronize();
Sensors s;
std::atomic<bool> stop{false};
std::thread th;
if (!hw.empty()) th = std::thread(sample, hw, &stop, &s);
(void)hipEventRecord(e0);
for (int i = 0; i < launches; ++i)
hipLaunchKernelGGL((peak<OP, LDS>), dim3(blocks), dim3(256), 0, 0, d_src, d_out, iters);
(void)hipEventRecord(e1);
(void)hipEventSynchronize(e1);
stop = true;
if (th.joinable()) th.join();
(void)hipEventElapsedTime(&ms, e0, e1);
const double flop = 8192.0 * 8.0 * 8.0 * (double)iters * (double)blocks * (double)launches;
const double tf = flop / ((double)ms * 1e9);
const double mhz = s.n ? s.mhz_sum / s.n : 0.0;
// Per CU per clock (64 CUs; HIP's multiProcessorCount is the WGP count, half of it).
const double per_clk = mhz > 0 ? tf * 1e12 / (2.0 * prop.multiProcessorCount * mhz * 1e6) : 0.0;
std::printf(" %-6s %3d blocks x 256 %8.1f ms %7.1f TFLOP/s sclk %6.0f MHz (min %4.0f max "
"%4.0f) %5.1f W %4.0f C %6.0f FLOP/clk/CU\n",
name, blocks, ms, tf, mhz, s.n ? s.mhz_min : 0.0, s.mhz_max, s.n ? s.w_sum / s.n : 0.0,
s.t_max, per_clk);
(void)hipEventDestroy(e0);
(void)hipEventDestroy(e1);
}
int main(int argc, char** argv) {
const int dev = argc > 1 ? std::atoi(argv[1]) : 0;
const double secs = argc > 2 ? std::atof(argv[2]) : 3.0;
const int tile = argc > 3 ? std::atoi(argv[3]) : 0;
(void)hipSetDevice(dev);
const std::string hw = hwmon_dir(dev);
std::printf(" WMMA sustained, device %d, %.1f s timed after %.1f s warm, sensors %s, power cap "
"%.0f W\n",
dev, secs, secs, hw.empty() ? "(none)" : hw.c_str(),
hw.empty() ? 0.0 : (double)read_long(hw + "/power1_cap") / 1e6);
// Random operand bits, 64 blocks' worth so neighbouring blocks differ. The 8-bit forms take
// every byte but E4M3's NaN codes and keep the exponent near one; bf16 likewise near one, so
// nothing overflows over the run.
const size_t nw = (size_t)64 * 32 * 16 * 4;
std::vector<uint32_t> h8(nw), h16(nw), hi8(nw);
uint64_t x = 0x9E3779B97F4A7C15ull;
auto rnd = [&]() { x ^= x << 13; x ^= x >> 7; x ^= x << 17; return (uint32_t)x; };
for (size_t i = 0; i < nw; ++i) {
uint32_t w = 0;
for (int b = 0; b < 4; ++b) {
const uint32_t r = rnd();
const uint32_t e = 6u + (r >> 8) % 4u; // exponent field 6..9
w |= (((r & 0x80u) | (e << 3) | (r & 7u)) & 0xFFu) << (8 * b);
}
h8[i] = w;
uint32_t v = 0;
for (int hh = 0; hh < 2; ++hh) {
const uint32_t r = rnd();
const uint32_t e = 125u + (r >> 16) % 4u; // 2^-2 .. 2^1
v |= (((r & 0x8000u) | (e << 7) | (r & 0x7Fu)) & 0xFFFFu) << (16 * hh);
}
h16[i] = v;
hi8[i] = rnd();
}
uint32_t *d8, *d16, *di8;
float* dout;
(void)hipMalloc(&d8, nw * 4);
(void)hipMalloc(&d16, nw * 4);
(void)hipMalloc(&di8, nw * 4);
(void)hipMalloc(&dout, 4);
(void)hipMemcpy(d8, h8.data(), nw * 4, hipMemcpyHostToDevice);
(void)hipMemcpy(d16, h16.data(), nw * 4, hipMemcpyHostToDevice);
(void)hipMemcpy(di8, hi8.data(), nw * 4, hipMemcpyHostToDevice);
if (tile == 0) {
run<kFp8, 0>("fp8", dev, secs, d8, dout, hw);
run<kIu8, 0>("iu8", dev, secs, di8, dout, hw);
run<kBf16, 0>("bf16", dev, secs, d16, dout, hw);
} else {
run<kFp8, 36864>("fp8", dev, secs, d8, dout, hw);
run<kIu8, 36864>("iu8", dev, secs, di8, dout, hw);
run<kBf16, 36864>("bf16", dev, secs, d16, dout, hw);
}
return 0;
}
+11 -4
View File
@@ -554,12 +554,13 @@ int r4d_gemm_mxfp4a8_decode_max_m(void);
// R4D_GEMM_W4A8_GROUP). The `_block()` queries report it, and every entry point rejects a K that
// would leave a partial block.
//
// Three kernels, one per band, because the operand carrying the coarse (per-128-row) scale must be
// the one whose tile is wide; see the AW comment in r4d_gemm_fp8a8.hip.
// Three kernels, one per band. The two W8A8 ones put the weight on the WMMA A operand, so a lane's
// accumulator slots share one activation scale; see r4d_gemm_fp8a8.hip.
//
// M == 1 r4d_gemm_fp8a16_nt_m1 bf16 activation read directly, no quantise launch
// M <= 16 r4d_gemm_fp8a8_nt_m16 E4M3 activation, one 16-wide token tile, split-K
// any M r4d_gemm_fp8a8_tiled E4M3 activation, 128x128 tile, eight waves
// M <= 64 r4d_gemm_fp8a8_nt_m16 E4M3 activation, up to four 16-wide token tiles, split-K
// any M r4d_gemm_fp8a8_tiled E4M3 activation, 128x128 tile, eight waves; the weight read
// into registers, the activation staged through LDS
//
// `w_ld` is bytes per weight row and `sw_ld` elements per scale row, 0 meaning tight. All return 0
// or a negative code instead of throwing, since they are reachable from C consumers.
@@ -652,6 +653,12 @@ int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws,
int a_ld, int sa_ld, int w_ld, int sw_ld,
int q_ld, int s_ld, int y_ld, long stream);
int r4d_gemm_fp8a8_gated_nt_m16_max_m(void);
// The narrow GEMM with a bias: `bias` bf16 [N], added to each output column's f32 accumulator before
// its one rounding, and C written at row pitch `c_ld` (0 = N), so C may be a column slice of a wider
// buffer. Never split. M up to r4d_gemm_fp8a8_nt_m16_max_m(); K a multiple of 128, N of 16.
int r4d_gemm_fp8a8_bias_nt_m16(long a, long ascale, long wq, long ws, long bias, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
int c_ld, long stream);
int r4d_gemm_fp8a8_tiled(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
long stream);
+46 -25
View File
@@ -1,6 +1,8 @@
// R4D dense attention for an encoder: non-causal, varlen over cu_seqlens segments, grouped-query,
// with an optional two-sided window |i - j| < window. bf16 in and out, f16 operands, f32
// accumulate. Head widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair is a row.
// R4D dense attention, varlen over cu_seqlens segments, grouped-query: an encoder's, non-causal with
// an optional two-sided window, i - j < window behind and j - i < wright ahead (wright is
// `window_right`, or `window` for the symmetric |i - j| < window), or causal with an optional
// window behind (a codec's sliding layers). bf16 in and out, f16 operands, f32 accumulate. Head
// widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair is a row.
//
// Core from the vision kernel (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32
// column-distributed accumulator gives each lane one query row, softmax state is lane-private, and
@@ -36,8 +38,8 @@ template<int HD, int GQA, int NQB, int DSPLIT, int TILE>
__global__ __launch_bounds__(NQB * GQA * DSPLIT * 32)
void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, float scale, int window, int block,
int cdiv, int q_ld, int k_ld, int v_ld, int o_ld)
const int* __restrict__ cu, float scale, int window, int wright,
int block, int cdiv, int causal, int q_ld, int k_ld, int v_ld, int o_ld)
{
typedef DT16<1> D;
typedef D::frag frag16;
@@ -79,12 +81,13 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
if (slen <= 0 || q0 >= slen) return;
const int qlast = min(q0 + BQ, slen) - 1;
// The keys any query of this workgroup can see.
// The keys any query of this workgroup can see: none past its last query when causal.
int kb = 0, ke = slen;
if (window > 0) {
kb = max(0, q0 - (window - 1));
ke = min(slen, qlast + window);
if (!causal) ke = min(slen, qlast + wright);
}
if (causal) ke = min(ke, qlast + 1);
const bool blocks = block > 0;
if (blocks) {
kb = max(kb, q0 / block * block);
@@ -128,8 +131,9 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
// Whether any (query, key) pair of this tile is outside the window or past the keys.
// Workgroup-uniform, so interior tiles skip the test.
const bool mask = (k0 + TILE > ke) ||
(causal && k0 + TILE - 1 > q0) ||
(window > 0 && (k0 < qlast - (window - 1) ||
k0 + TILE - 1 > q0 + (window - 1))) ||
k0 + TILE - 1 > q0 + (wright - 1))) ||
(blocks && (q_straddle || k0 / block != (k0 + TILE - 1) / block ||
k0 / block != q0 / block));
@@ -223,7 +227,8 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
for (int e = 0; e < 8; ++e) {
const int key = kq + e;
const int d = qpos - key;
const bool ok = key < ke && (window <= 0 || (d < window && -d < window)) &&
const bool ok = key < ke && (!causal || d >= 0) &&
(window <= 0 || (d < window && -d < wright)) &&
(!blocks || key / block == qpos / block);
sc[e] = ok ? sc[e] : -INFINITY;
}
@@ -297,51 +302,63 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
// One instantiation per (head_dim, gqa), at a workgroup shape picked for it:
// h64 gqa1: 8 query blocks of 16, K/V tiles of 64 keys (the vision towers' heads)
// h256 gqa2: 8 query blocks x 2 heads, tiles of 32 (LDS: 37 KiB)
// h256 gqa4: 4 query blocks x 4 heads, tiles of 32 (LDS: 37 KiB)
// h512 gqa4: 2 query blocks x 4 heads x 2 head halves, tiles of 16 (LDS: 57 KiB)
template<int HD, int GQA, int NQB, int DSPLIT, int TILE>
static int r4d_attn_dense_launch(const void* q, const void* k, const void* v, void* o,
const void* cu, int num_seqs, int max_seqlen, int n_head_kv,
float scale, int window, int block, int cdiv, int q_ld, int k_ld,
int v_ld, int o_ld, hipStream_t s)
float scale, int window, int wright, int block, int cdiv,
int causal, int q_ld, int k_ld, int v_ld, int o_ld, hipStream_t s)
{
constexpr int BQ = NQB * 16;
dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv, num_seqs);
hipLaunchKernelGGL((r4d_attn_dense_kernel<HD, GQA, NQB, DSPLIT, TILE>), grid,
dim3(NQB * GQA * DSPLIT * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k,
(const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, block,
cdiv, q_ld, k_ld, v_ld, o_ld);
(const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, wright,
block, cdiv, causal, q_ld, k_ld, v_ld, o_ld);
const hipError_t e = hipGetLastError();
return e == hipSuccess ? 0 : -100 - (int)e;
}
// q, o: [tokens, n_head * head_dim]; k, v: [tokens, n_head_kv * head_dim], each at its own token
// pitch in elements. cu_seqlens is [num_seqs + 1] int32 on the device; max_seqlen is a host-side
// bound on the segment lengths, in rows, and sizes the grid. window 0 is the whole segment, block
// 0 no blocks; cu_seqlens counts in units cdiv rows apart.
// bound on the segment lengths, in rows, and sizes the grid. window 0 is the whole segment (with
// causal, every earlier key), wright 0 the window's own right side, block 0 no blocks; cu_seqlens
// counts in units cdiv rows apart.
extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v, void* o,
const void* cu_seqlens, int num_seqs, int max_seqlen,
int n_head, int n_head_kv, int head_dim, float scale,
int window, int block, int cdiv, int q_ld, int k_ld, int v_ld,
int o_ld, void* stream)
int o_ld, void* stream, int wright = 0, int causal = 0)
{
if (n_head <= 0 || n_head_kv <= 0 || n_head % n_head_kv) return -2;
if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3;
if (window < 0 || block < 0 || cdiv <= 0) return -4;
if (window < 0 || wright < 0 || block < 0 || cdiv <= 0 ||
(wright > 0 && (window == 0 || causal)))
return -4;
if (num_seqs <= 0 || max_seqlen <= 0) return 0;
if (wright == 0) wright = window;
const int gqa = n_head / n_head_kv;
hipStream_t s = (hipStream_t)stream;
if (head_dim == 64 && gqa == 1)
return r4d_attn_dense_launch<64, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen,
n_head_kv, scale, window, block, cdiv, q_ld,
k_ld, v_ld, o_ld, s);
n_head_kv, scale, window, wright, block,
cdiv, causal, q_ld, k_ld, v_ld, o_ld, s);
if (head_dim == 256 && gqa == 2)
return r4d_attn_dense_launch<256, 2, 8, 1, 32>(q, k, v, o, cu_seqlens, num_seqs,
max_seqlen, n_head_kv, scale, window, block,
cdiv, q_ld, k_ld, v_ld, o_ld, s);
max_seqlen, n_head_kv, scale, window,
wright, block, cdiv, causal, q_ld, k_ld,
v_ld, o_ld, s);
if (head_dim == 256 && gqa == 4)
return r4d_attn_dense_launch<256, 4, 4, 1, 32>(q, k, v, o, cu_seqlens, num_seqs,
max_seqlen, n_head_kv, scale, window,
wright, block, cdiv, causal, q_ld, k_ld,
v_ld, o_ld, s);
if (head_dim == 512 && gqa == 4)
return r4d_attn_dense_launch<512, 4, 2, 2, 16>(q, k, v, o, cu_seqlens, num_seqs,
max_seqlen, n_head_kv, scale, window, block,
cdiv, q_ld, k_ld, v_ld, o_ld, s);
max_seqlen, n_head_kv, scale, window,
wright, block, cdiv, causal, q_ld, k_ld,
v_ld, o_ld, s);
return -1;
}
@@ -357,7 +374,8 @@ extern "C" int r4d_rad_attn_dense(const RadArgs* a, RadStream s) {
const RadTensor* o = r4d_opt(a, DN_OUT);
if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL);
if (!r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE);
if (r4d_geti_or(a, "causal", 0) != 0) return R4D_NO(RAD_E_UNSUPPORTED);
const long long causal = r4d_geti_or(a, "causal", 0);
if (causal < 0 || causal > 1) return R4D_NO(RAD_E_SHAPE);
const long long head_dim = r4d_geti_or(a, "head_dim", 0);
const long long gqa = r4d_geti_or(a, "gqa", 1);
@@ -381,13 +399,16 @@ extern "C" int r4d_rad_attn_dense(const RadArgs* a, RadStream s) {
if (msl <= 0 || msl > total) msl = total;
const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)head_dim));
const long long window = r4d_geti_or(a, "window", 0);
const long long wright = r4d_geti_or(a, "window_right", 0);
const long long block = r4d_geti_or(a, "block", 0);
const long long cdiv = r4d_geti_or(a, "cu_div", 1);
/* A right side needs a non-causal window to be the right side of (libref refuses it alike). */
if (wright < 0 || (wright > 0 && (window == 0 || causal))) return R4D_NO(RAD_E_SHAPE);
const int e = r4d_attn_dense_bf16(q->data, k->data, v->data, o->data, cu->data, num_seqs,
(int)msl, (int)nh, (int)hk, (int)head_dim, scale,
(int)window, (int)block, (int)cdiv, (int)q_ld, (int)k_ld,
(int)v_ld, (int)o_ld, s);
(int)v_ld, (int)o_ld, s, (int)wright, (int)causal);
if (e == 0) return RAD_OK;
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
}
+249 -38
View File
@@ -22,6 +22,13 @@
// prefix tiles (a few hundred conditioning rows) as they are staged. A score is (q . k) * qs * ks
// with an exact integer dot product. At a DiT's 16384 rows this is ~38 -> ~32 ms, with image
// error below the spread between exact attention implementations.
//
// FP8 P.V form (`PV8`, op parameter `pv` "fp8", prefix-free and one query head a KV head): V as
// E4M3 codes with a scale per column (quant_cols_fp8's), P.V on v_wmma_f32_16x16x16_fp8_fp8 (half
// the cycles of bf16) with P as E4M3 codes of 448 p. E4M3 ends at 448, so the softmax keeps an
// exact running max, taken over a whole 64-key tile so that its test runs once a tile; the row
// sum takes the unrounded 448 p and the epilogue multiplies by the column scale. The V tile is
// staged as the transposing load over pairs of codes, split by byte permutes into V^T rows.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_common.h"
@@ -48,12 +55,16 @@ __device__ __forceinline__ float ps_amax8(uint4 u) {
fmaxf(fmaxf(fabsf(ps_lo(u.z)), fabsf(ps_hi(u.z))),
fmaxf(fabsf(ps_lo(u.w)), fabsf(ps_hi(u.w)))));
}
// log2(448) less 2^-16: exp2 of it is 448 (1 - 1.1e-5), under 448 with room for the hardware
// exp2's error, and still the E4M3 code of 448.
constexpr float kPsLog448 = 8.8073397f;
__device__ __forceinline__ uint2 ps_q8x8(uint4 u, float inv) {
return make_uint2(ps_q8x4(ps_lo(u.x), ps_hi(u.x), ps_lo(u.y), ps_hi(u.y), inv),
ps_q8x4(ps_lo(u.z), ps_hi(u.z), ps_lo(u.w), ps_hi(u.w), inv));
}
template<int HD, int GQA, int NQB, int TILE, bool I8>
template<int HD, int GQA, int NQB, int TILE, bool I8, bool PV8>
__global__ __launch_bounds__(NQB * GQA * 32)
void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const int8_t* __restrict__ gk8, const float* __restrict__ gks,
@@ -62,7 +73,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
const int* __restrict__ bt, int bt_pitch,
const uint16_t* __restrict__ kvc, int kv_heads,
float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld,
int v_ld, int o_ld)
int v_ld, int o_ld, const float* __restrict__ gvs)
{
typedef DT16<0> D;
typedef D::frag frag16;
@@ -92,11 +103,18 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
constexpr int K8G = HD / 16; // 16-byte pieces of an own key's row
constexpr int K8P = (TILE * K8G + NTHR - 1) / NTHR;
static_assert(!I8 || (DG == 16 && NTHR % 32 == 0), "an int8 prefix key is one half-wave");
// E4M3 V^T tile: HD rows of TILE key bytes padded by 8, so a fragment read's sixteen rows
// (8 bytes a lane) fall on distinct bank pairs. One 16-byte unit (16 dims of 8 keys) a thread:
// unit u is key group u / DG8 and dims 16 (u % DG8), so a wave reads whole half-rows.
constexpr int VSTR8 = TILE + 8;
constexpr int DG8 = HD / 16;
static_assert(!PV8 || (GQA == 1 && KGRP * DG8 == LGRP), "one E4M3 V unit a thread");
__shared__ __align__(16) uint16_t sK[I8 ? 8 : TILE * KSTR];
__shared__ __align__(16) int8_t sK8[I8 ? TILE * KSTR8 : 16];
__shared__ __align__(16) float sKs[I8 ? TILE : 4];
__shared__ __align__(16) uint16_t sV[HD * VSTR];
__shared__ __align__(16) uint16_t sV[PV8 ? 8 : HD * VSTR];
__shared__ __align__(16) uint8_t sV8[PV8 ? HD * VSTR8 : 16];
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
const int c = lane & 15, h = lane >> 4;
@@ -222,14 +240,21 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
}
}
}
#pragma unroll
for (int r = 0; r < VP; ++r) {
const int u = lgi + r * LGRP;
if (NTR % LGRP == 0 || u < NTR) {
const int kg = u % KGRP, dg = u / KGRP;
const int kk0 = k0 + kg * 8 + vj;
const int kk = (kk0 < klim) ? kk0 : klim - 1;
vr[r] = __builtin_bit_cast(uint4, load_tr_b128(vrow(pre, kk) + dg * 8));
if constexpr (PV8) {
const int kk0 = k0 + (lgi / DG8) * 8 + vj;
const int kk = (kk0 < klim) ? kk0 : klim - 1;
const uint8_t* v8 = (const uint8_t*)gv + (long)(s0 + kk) * v_ld + (long)kvh * HD;
vr[0] = __builtin_bit_cast(uint4, load_tr_b128(v8 + (lgi % DG8) * 16));
} else {
#pragma unroll
for (int r = 0; r < VP; ++r) {
const int u = lgi + r * LGRP;
if (NTR % LGRP == 0 || u < NTR) {
const int kg = u % KGRP, dg = u / KGRP;
const int kk0 = k0 + kg * 8 + vj;
const int kk = (kk0 < klim) ? kk0 : klim - 1;
vr[r] = __builtin_bit_cast(uint4, load_tr_b128(vrow(pre, kk) + dg * 8));
}
}
}
// Int8 prefix key: row absmax over its DG lanes (one half-wave, DPP butterfly), then eight
@@ -250,12 +275,25 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
}
lds_barrier();
#pragma unroll
for (int r = 0; r < VP; ++r) {
const int u = lgi + r * LGRP;
if (NTR % LGRP == 0 || u < NTR) {
const int kg = u % KGRP, dg = u / KGRP;
*(uint4*)&sV[(dg * 8 + vj) * VSTR + kg * 8] = vr[r];
if constexpr (PV8) {
// Lane j holds dims 2 j and 2 j + 1 of the group's eight keys interleaved, a key a
// 16-bit pair: even bytes are one V^T row, odd bytes the next.
const int row = (lgi % DG8) * 16 + 2 * vj, col = (lgi / DG8) * 8;
const uint4 w = vr[0];
*(uint2*)&sV8[row * VSTR8 + col] =
make_uint2(__builtin_amdgcn_perm(w.y, w.x, 0x06040200u),
__builtin_amdgcn_perm(w.w, w.z, 0x06040200u));
*(uint2*)&sV8[(row + 1) * VSTR8 + col] =
make_uint2(__builtin_amdgcn_perm(w.y, w.x, 0x07050301u),
__builtin_amdgcn_perm(w.w, w.z, 0x07050301u));
} else {
#pragma unroll
for (int r = 0; r < VP; ++r) {
const int u = lgi + r * LGRP;
if (NTR % LGRP == 0 || u < NTR) {
const int kg = u % KGRP, dg = u / KGRP;
*(uint4*)&sV[(dg * 8 + vj) * VSTR + kg * 8] = vr[r];
}
}
}
if constexpr (I8) {
@@ -290,6 +328,133 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
}
lds_barrier();
if constexpr (PV8) {
// The whole tile's scores, one exact running max over them, P as E4M3 codes of 448 p,
// then the tile's fp8 WMMAs. The max is kept in the scores' own units (the int8
// form's are unscaled, `qs` being one positive factor a row), so s - max is at most 0
// exactly and x = exp2((s - max) qs + kPsLog448) cannot pass exp2(kPsLog448) < 448,
// where v_cvt_pk_fp8_f32 would give NaN. x is 448 p up to a factor common to every
// key, which the row sum shares.
float sc[MT][8];
#pragma unroll
for (int mt = 0; mt < MT; mt += (I8 ? 2 : 1)) {
if constexpr (I8) {
// Two blocks' int8 chains interleaved: each WMMA waits on the one two back.
v8i_ps s0 = (v8i_ps){0, 0, 0, 0, 0, 0, 0, 0}, s1 = s0;
const int8_t* r0 = &sK8[(mt * 16 + c) * KSTR8] + 8 * h;
const int8_t* r1 = r0 + 16 * KSTR8;
#pragma unroll
for (int t0 = 0; t0 < NKS; t0 += 4) {
v2i_ps k0[4], k1[4];
#pragma unroll
for (int j = 0; j < 4; ++j) {
const uint2 u0 = *(const uint2*)(r0 + 16 * (t0 + j));
const uint2 u1 = *(const uint2*)(r1 + 16 * (t0 + j));
k0[j] = (v2i_ps){ (int)u0.x, (int)u0.y };
k1[j] = (v2i_ps){ (int)u1.x, (int)u1.y };
}
sched_barrier();
#pragma unroll
for (int j = 0; j < 4; ++j) {
s0 = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(
true, k0[j], true, qf[t0 + j], s0, false);
s1 = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(
true, k1[j], true, qf[t0 + j], s1, false);
}
}
#pragma unroll
for (int b = 0; b < 2; ++b) {
const float4 ka = *(const float4*)&sKs[(mt + b) * 16 + 8 * h];
const float4 kb = *(const float4*)&sKs[(mt + b) * 16 + 8 * h + 4];
const float ks[8] = { ka.x, ka.y, ka.z, ka.w, kb.x, kb.y, kb.z, kb.w };
#pragma unroll
for (int e = 0; e < 8; ++e)
sc[mt + b][e] = (float)(b ? s1[e] : s0[e]) * ks[e];
}
} else {
v8f s = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
const uint16_t* kr2 = &sK[(mt * 16 + c) * KSTR] + 8 * h;
#pragma unroll
for (int t0 = 0; t0 < NKS; t0 += 4) {
frag16 kf[4];
#pragma unroll
for (int j = 0; j < 4; ++j) {
const uint4 u = *(const uint4*)(kr2 + 16 * (t0 + j));
kf[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w));
}
sched_barrier();
#pragma unroll
for (int j = 0; j < 4; ++j) s = D::wmma(kf[j], qf[t0 + j], s);
}
#pragma unroll
for (int e = 0; e < 8; ++e) sc[mt][e] = s[e];
}
}
if (mask) {
#pragma unroll
for (int mt = 0; mt < MT; ++mt) {
const int kq0 = k0 + mt * 16 + 8 * h;
#pragma unroll
for (int e = 0; e < 8; ++e) {
const int key = kq0 + e;
const bool ok = key < klim && (!causal || key <= qpos);
sc[mt][e] = ok ? sc[mt][e] : -INFINITY;
}
}
}
float smax = sc[0][0];
#pragma unroll
for (int mt = 0; mt < MT; ++mt)
#pragma unroll
for (int e = 0; e < 8; ++e) smax = fmaxf(smax, sc[mt][e]);
if (wave_any(smax > m_ref)) {
const float rmax = fmaxf(smax, swap16(smax));
const float mnew = fmaxf(fmaxf(m_ref, rmax), -3.0e38f);
const float alpha = ex2(I8 ? (m_ref - mnew) * qs : m_ref - mnew);
#pragma unroll
for (int t = 0; t < NKS; ++t)
#pragma unroll
for (int e = 0; e < 8; ++e) acc[t][e] *= alpha;
l_i *= alpha;
m_ref = mnew;
}
#pragma unroll
for (int mt = 0; mt < MT; ++mt) {
float x[8];
#pragma unroll
for (int e = 0; e < 8; ++e) {
const float d = sc[mt][e] - m_ref;
x[e] = ex2(I8 ? __builtin_fmaf(d, qs, kPsLog448) : d + kPsLog448);
}
l_i += ((x[0] + x[1]) + (x[2] + x[3])) + ((x[4] + x[5]) + (x[6] + x[7]));
// The first conversion's high half is dead (the second writes it), so any live
// register serves as its old value: no zeroing moves.
int w0 = __builtin_amdgcn_cvt_pk_fp8_f32(x[0], x[1], __builtin_bit_cast(int, x[0]),
false);
w0 = __builtin_amdgcn_cvt_pk_fp8_f32(x[2], x[3], w0, true);
int w1 = __builtin_amdgcn_cvt_pk_fp8_f32(x[4], x[5], __builtin_bit_cast(int, x[4]),
false);
w1 = __builtin_amdgcn_cvt_pk_fp8_f32(x[6], x[7], w1, true);
const v2i_ps p8 = (v2i_ps){ w0, w1 };
const uint8_t* vr2 = &sV8[c * VSTR8 + mt * 16 + 8 * h];
#pragma unroll
for (int t0 = 0; t0 < NKS; t0 += 4) {
v2i_ps vf[4];
#pragma unroll
for (int j = 0; j < 4; ++j) {
const uint2 u = *(const uint2*)(vr2 + (t0 + j) * 16 * VSTR8);
vf[j] = (v2i_ps){ (int)u.x, (int)u.y };
}
sched_barrier();
#pragma unroll
for (int j = 0; j < 4; ++j)
acc[t0 + j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(
vf[j], p8, acc[t0 + j]);
}
}
continue;
}
#pragma unroll 1
for (int mt = 0; mt < MT; ++mt) {
// Scores of 16 keys, in log2 units once multiplied by `qs` (int8 only; the bf16 query
@@ -414,6 +579,14 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
#pragma unroll
for (int t = 0; t < NKS; ++t) {
uint32_t tw[4];
if constexpr (PV8) {
// The column scales of the lane's eight dims.
const float4 sa = *(const float4*)(gvs + (long)hq * HD + t * 16 + 8 * h);
const float4 sb = *(const float4*)(gvs + (long)hq * HD + t * 16 + 8 * h + 4);
const float vsc[8] = { sa.x, sa.y, sa.z, sa.w, sb.x, sb.y, sb.z, sb.w };
#pragma unroll
for (int e = 0; e < 8; ++e) acc[t][e] *= vsc[e];
}
#pragma unroll
for (int e = 0; e < 8; e += 2)
tw[e >> 1] = (uint32_t)f32_to_bf16(acc[t][e] * inv)
@@ -422,22 +595,23 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
}
}
template<int HD, int GQA, int NQB, int TILE, bool I8>
template<int HD, int GQA, int NQB, int TILE, bool I8, bool PV8>
static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, const float* ks,
const void* v, void* o, const int* cu,
const int* used, const int* bt, int bt_pitch, const void* kvc,
int num_seqs, int max_q, int n_head_kv, float scale, int causal,
int q_ld, int k_ld, int k8_ld, int ks_ld, int v_ld, int o_ld,
hipStream_t s)
const float* vs, hipStream_t s)
{
constexpr int BQ = NQB * 16;
// At most total / BQ full blocks plus one partial block per sequence.
dim3 grid((max_q + BQ - 1) / BQ + num_seqs, n_head_kv, 1);
hipLaunchKernelGGL((r4d_attn_ps_kernel<HD, GQA, NQB, TILE, I8>), grid, dim3(NQB * GQA * 32), 0, s,
hipLaunchKernelGGL((r4d_attn_ps_kernel<HD, GQA, NQB, TILE, I8, PV8>), grid,
dim3(NQB * GQA * 32), 0, s,
(const uint16_t*)q, (const uint16_t*)k, (const int8_t*)k8, ks,
(const uint16_t*)v, (uint16_t*)o, cu, num_seqs, used, bt, bt_pitch,
(const uint16_t*)kvc, n_head_kv, scale, causal, q_ld, k_ld, k8_ld, ks_ld,
v_ld, o_ld);
v_ld, o_ld, vs);
const hipError_t e = hipGetLastError();
return e == hipSuccess ? 0 : -100 - (int)e;
}
@@ -445,13 +619,14 @@ static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, cons
/* head_dim 128 at gqa 1, 2, 4 and 8. Null `used`/`bt`/`kvc` means no prefix (the dense form).
* `max_q` is the total query rows over all sequences and bounds the flat grid. Non-null `k8`
* selects the int8 Q.K form (own-key codes, `k8_ld` bytes per row; a scale per (row, head) in
* `ks`, `ks_ld` floats per row), gqa 1 only. */
* `ks`, `ks_ld` floats per row), gqa 1 only. Non-null `vs` selects the fp8 P.V form (`v` as E4M3
* codes, `v_ld` bytes per row; `vs` their column scales), gqa 1 and no prefix only. */
static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float* ks,
const void* v, void* o, const int* cu,
const int* used, const int* bt, int bt_pitch, const void* kvc,
int num_seqs, int max_q, int n_head, int n_head_kv, int head_dim,
float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld,
int v_ld, int o_ld, hipStream_t s)
int v_ld, int o_ld, hipStream_t s, const float* vs = nullptr)
{
if (n_head <= 0 || n_head_kv <= 0 || n_head % n_head_kv) return -2;
if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3;
@@ -460,12 +635,23 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float
const int gqa = n_head / n_head_kv;
if (head_dim != 128) return -1;
#define R4D_PS(G, NQB, T, I8) \
return r4d_attn_ps_launch<128, G, NQB, T, I8>(q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, \
num_seqs, max_q, n_head_kv, scale, causal, \
q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, s)
return r4d_attn_ps_launch<128, G, NQB, T, I8, false>(q, k, k8, ks, v, o, cu, used, bt, \
bt_pitch, kvc, num_seqs, max_q, \
n_head_kv, scale, causal, q_ld, k_ld, \
k8_ld, ks_ld, v_ld, o_ld, nullptr, s)
/* Sixteen query tiles per workgroup at gqa 1: a workgroup streams its head's whole K and V
* once, so more rows per workgroup divide that traffic. At 16384 rows a head's K/V (8 MB) do
* not fit L2; 128 rows per workgroup gave 66 TFLOP/s, 256 gave 111, 512 gave 102. */
if (vs) {
if (gqa != 1 || used || bt || kvc || (v_ld & 15) || ((uintptr_t)v & 15)) return -1;
if (k8)
return r4d_attn_ps_launch<128, 1, 16, 64, true, true>(
q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv,
scale, causal, q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, vs, s);
return r4d_attn_ps_launch<128, 1, 16, 64, false, true>(
q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, scale,
causal, q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, vs, s);
}
if (k8) {
if (gqa != 1) return -1;
R4D_PS(1, 16, 64, true);
@@ -482,7 +668,7 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float
// ============================================================== the plugin ABI entry points
enum { PS_Q = 0, PS_K, PS_V, PS_KV, PS_BT, PS_USED, PS_CU, PS_KDES, PS_VDES, PS_K8, PS_KS,
PS_OUT };
PS_OUT, PS_VS };
extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) {
const RadTensor* q = r4d_opt(a, PS_Q);
@@ -493,16 +679,32 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) {
const RadTensor* su = r4d_opt(a, PS_USED);
const RadTensor* cu = r4d_opt(a, PS_CU);
const RadTensor* o = r4d_opt(a, PS_OUT);
if (!q || !k || !v || !kv || !bt || !su || !cu || !o) return R4D_NO(RAD_E_INVAL);
if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL);
/* The paged prefix is the cache, its block table and the per-sequence prefix lengths, all
* three or none: without them the op is self attention over each sequence's rows. */
const bool pre = kv != nullptr;
if (pre != (bt != nullptr) || pre != (su != nullptr)) return R4D_NO(RAD_E_INVAL);
if (r4d_opt(a, PS_KDES) || r4d_opt(a, PS_VDES)) return R4D_NO(RAD_E_UNSUPPORTED);
if (kv->dtype != RAD_BF16 || q->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if ((pre && kv->dtype != RAD_BF16) || q->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
/* The fp8 P.V form (`pv` "fp8"): `v` as E4M3 codes [tokens, kv_heads * head_dim] and their
* column scales `v_scale` [kv_heads * head_dim], as quant_cols_fp8 writes them; prefix-free,
* one query head a KV head. */
const RadTensor* vs = r4d_opt(a, PS_VS);
const char* pvs = r4d_gets(a, "pv");
const bool pv8 = pvs && !std::strcmp(pvs, "fp8");
if (pvs && !pv8 && std::strcmp(pvs, "bf16")) return R4D_NO(RAD_E_INVAL);
if (pv8 != (vs != nullptr)) return R4D_NO(RAD_E_INVAL);
if (pv8 && pre) return R4D_NO(RAD_E_UNSUPPORTED);
if (pv8 && (v->dtype != RAD_F8E4M3 || vs->dtype != RAD_F32)) return R4D_NO(RAD_E_DTYPE);
if (pv8 && r4d_geti_or(a, "gqa", 1) != 1) return R4D_NO(RAD_E_UNSUPPORTED);
const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1);
if (hd != 128 || gqa <= 0) return R4D_NO(RAD_E_SHAPE);
if (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != 2 * hd) return R4D_NO(RAD_E_SHAPE);
if (!r4d_contig(cu) || !r4d_contig(su) || cu->rank != 1 || cu->shape[0] < 2)
if (pre && (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != 2 * hd))
return R4D_NO(RAD_E_SHAPE);
if (!r4d_contig(cu) || (pre && !r4d_contig(su)) || cu->rank != 1 || cu->shape[0] < 2)
return R4D_NO(RAD_E_SHAPE);
const int num_seqs = (int)(cu->shape[0] - 1);
if (r4d_numel(su) < num_seqs) return R4D_NO(RAD_E_SHAPE);
if (pre && r4d_numel(su) < num_seqs) return R4D_NO(RAD_E_SHAPE);
long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0;
long long to = 0, ho = 0, o_ld = 0;
if (!r4d_head_rows(q, hd, &total, &nh, &q_ld) ||
@@ -510,10 +712,11 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) {
!r4d_head_rows(v, hd, &tv, &hv, &v_ld) ||
!r4d_head_rows(o, hd, &to, &ho, &o_ld))
return R4D_NO(RAD_E_STRIDE);
if (hk != hv || ho != nh || hk * gqa != nh || hk != kv->shape[1]) return R4D_NO(RAD_E_SHAPE);
if (hk != hv || ho != nh || hk * gqa != nh || (pre && hk != kv->shape[1]))
return R4D_NO(RAD_E_SHAPE);
if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE);
const long long bt_pitch = bt->rank >= 2 ? bt->shape[1] : r4d_numel(bt) / num_seqs;
if (bt->rank >= 2 && bt->stride[1] != 1) return R4D_NO(RAD_E_STRIDE);
const long long bt_pitch = !pre ? 0 : bt->rank >= 2 ? bt->shape[1] : r4d_numel(bt) / num_seqs;
if (pre && bt->rank >= 2 && bt->stride[1] != 1) return R4D_NO(RAD_E_STRIDE);
const long long mq = total;
/* Int8 Q.K form (`qk` "i8"): own-key codes [tokens, kv_heads * head_dim] and scales
* [tokens, kv_heads], as quant_act_i8g writes them at group head_dim. */
@@ -532,13 +735,21 @@ extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) {
if (ks_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (h8 != hk || t8 < total || ts < total) return R4D_NO(RAD_E_SHAPE);
}
if (pv8) {
if (!r4d_contig(vs) || ((uintptr_t)vs->data & 15) || (v_ld & 15) ||
((uintptr_t)v->data & 15))
return R4D_NO(RAD_E_STRIDE);
if (r4d_numel(vs) < hk * hd) return R4D_NO(RAD_E_SHAPE);
}
const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd));
const int e = r4d_attn_ps(q->data, k->data, k8 ? k8->data : nullptr,
ks ? (const float*)ks->data : nullptr, v->data, o->data,
(const int*)cu->data, (const int*)su->data, (const int*)bt->data,
(int)bt_pitch, kv->data, num_seqs, (int)mq, (int)nh, (int)hk, (int)hd,
(const int*)cu->data, pre ? (const int*)su->data : nullptr,
pre ? (const int*)bt->data : nullptr, (int)bt_pitch,
pre ? kv->data : nullptr, num_seqs, (int)mq, (int)nh, (int)hk, (int)hd,
scale, (int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld,
(int)k8_ld, (int)ks_ld, (int)v_ld, (int)o_ld, (hipStream_t)s);
(int)k8_ld, (int)ks_ld, (int)v_ld, (int)o_ld, (hipStream_t)s,
pv8 ? (const float*)vs->data : nullptr);
if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE);
if (e == 0) return RAD_OK;
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
+1610
View File
File diff suppressed because it is too large. Load diff
+243 -48
View File
@@ -7,6 +7,7 @@
#include "r4d_args.h"
#include "r4d_common.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
@@ -98,14 +99,26 @@ struct QkBlocks {
int comp[8] = {};
};
// A norm gain element, the gains bf16 or (w_f32) f32; an absent gain is one, without `wadd`.
__device__ __forceinline__ float qk_gain(const void* w, uint32_t e, int w_f32, float wadd) {
if (!w) return 1.0f;
return (w_f32 ? ((const float*)w)[e] : bf2f(((const uint16_t*)w)[e])) + wadd;
}
// Element `i` of the positions: an i32 value, or with `pos_f32` an f32 one read as the value it
// holds (a fractional coordinate, such as a video decoder's normalised grid times 2 pi).
__device__ __forceinline__ float qk_pos(const void* pos, int pos_f32, size_t i) {
return pos_f32 ? ((const float*)pos)[i] : (float)((const int*)pos)[i];
}
// MODE: 0 neox, 1 gptj, 2 blocks. Positions are [M] for the first two and [C, M] (plane stride
// `pplane`) for blocks.
template <int MODE>
__global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel(
uint16_t* __restrict__ qkv, const int* __restrict__ pos, const uint16_t* __restrict__ qw,
const uint16_t* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv,
uint16_t* __restrict__ qkv, const void* __restrict__ pos, const void* __restrict__ qw,
const void* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv,
uint32_t rot, int v_norm, float theta, float eps, float rscale, float wadd, uint32_t ld,
QkBlocks blk, uint32_t pplane) {
QkBlocks blk, uint32_t pplane, int w_f32, int pos_f32) {
__shared__ float cs_s[kQkMaxHalf], sn_s[kQkMaxHalf];
const uint32_t m = blockIdx.x;
const uint32_t n_rope = n_head + n_head_kv;
@@ -119,12 +132,12 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel(
for (uint32_t i = threadIdx.x; i < half; i += kQkThreads) {
int c = 0, s0 = 0;
while (c + 1 < blk.n && (int)i >= s0 + blk.sec[c]) { s0 += blk.sec[c]; ++c; }
const float p = (float)pos[(size_t)blk.comp[c] * pplane + m] / div;
const float p = qk_pos(pos, pos_f32, (size_t)blk.comp[c] * pplane + m) / div;
const float inv = 1.0f / powf(theta, (float)((int)i - s0) / (float)blk.sec[c]);
sincosf(p * inv, &sn_s[i], &cs_s[i]);
}
} else {
const float p = (float)pos[m] / div;
const float p = qk_pos(pos, pos_f32, m) / div;
for (uint32_t i = threadIdx.x; i < half; i += kQkThreads) {
const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot);
sincosf(p * inv, &sn_s[i], &cs_s[i]);
@@ -148,11 +161,11 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel(
ss = r4d_wave_sum(ss);
const float sc = 1.0f / sqrtf(ss / (float)head_dim + eps);
const bool is_v = hh >= n_rope;
const uint16_t* w = hh < n_head ? qw : kw;
const void* w = hh < n_head ? qw : kw;
#pragma unroll
for (int j = 0; j < kQkMaxE; ++j)
if (j < E) {
const float g = is_v ? 1.0f : bf2f(w[at(j)]) + wadd;
const float g = is_v ? 1.0f : qk_gain(w, at(j), w_f32, wadd);
x[j] = bf2f(f32_to_bf16(x[j] * sc * g));
}
if (!is_v) {
@@ -226,11 +239,17 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel(
// 2 imrope NeoX pairs (i, i + rot/2) on one ladder theta^(-2i/rot), the position
// component interleaved: 1 where i % 3 == 1 and i < 3 * sec[1], 2 where
// i % 3 == 2 and i < 3 * sec[2], 0 elsewhere (Qwen3-VL's text attention)
// 3 axial NeoX pairs (i, i + rot/2), the rot/2 frequencies in contiguous sections,
// section c on its own ladder theta^(-2j/(2 sec[c])) and turned by component c
// (a video transformer's or decoder's (t, h, w) rotary). With rank-1 positions
// (`pplane` 0) every component is the one position.
//
// `rot` 0 is the norm alone and reads no positions.
__global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel(
uint16_t* __restrict__ qkv, const int* __restrict__ pos, const uint16_t* __restrict__ qw,
const uint16_t* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv,
uint16_t* __restrict__ qkv, const void* __restrict__ pos, const void* __restrict__ qw,
const void* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv,
uint32_t rot, int v_norm, float theta, float eps, float rscale, float wadd, uint32_t ld,
QkBlocks blk, uint32_t pplane, int pm) {
QkBlocks blk, uint32_t pplane, int pm, int w_f32, int pos_f32) {
__shared__ float cs_s[kQkMaxHalf], sn_s[kQkMaxHalf];
__shared__ int pa_s[kQkMaxHalf], pb_s[kQkMaxHalf];
const uint32_t m = blockIdx.x;
@@ -244,7 +263,7 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel(
int c = 0;
if (i % 3 == 1 && (int)i < 3 * blk.sec[1]) c = 1;
else if (i % 3 == 2 && (int)i < 3 * blk.sec[2]) c = 2;
const float p = (float)pos[(size_t)c * pplane + m] / div;
const float p = qk_pos(pos, pos_f32, (size_t)c * pplane + m) / div;
const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot);
sincosf(p * inv, &sn_s[i], &cs_s[i]);
pa_s[i] = (int)i;
@@ -253,7 +272,16 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel(
}
int c = 0, s0 = 0;
while (c + 1 < blk.n && (int)i >= s0 + blk.sec[c]) { s0 += blk.sec[c]; ++c; }
const float p = (float)pos[(size_t)blk.comp[c] * pplane + m] / div;
if (pm == 3) {
const float p = qk_pos(pos, pos_f32, (size_t)c * pplane + m) / div;
const float inv =
1.0f / powf(theta, (float)(2 * ((int)i - s0)) / (float)(2 * blk.sec[c]));
sincosf(p * inv, &sn_s[i], &cs_s[i]);
pa_s[i] = (int)i;
pb_s[i] = (int)(i + half);
continue;
}
const float p = qk_pos(pos, pos_f32, (size_t)blk.comp[c] * pplane + m) / div;
const float inv = 1.0f / powf(theta, (float)((int)i - s0) / (float)blk.sec[c]);
sincosf(p * inv, &sn_s[i], &cs_s[i]);
if (pm == 1) {
@@ -273,9 +301,9 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel(
ss = r4d_wave_sum(ss);
const float sc = 1.0f / sqrtf(ss / (float)head_dim + eps);
const bool is_v = hh >= n_rope;
const uint16_t* w = hh < n_head ? qw : kw;
const void* w = hh < n_head ? qw : kw;
auto nrm = [&](uint32_t e) {
const float g = is_v ? 1.0f : bf2f(w[e]) + wadd;
const float g = is_v ? 1.0f : qk_gain(w, e, w_f32, wadd);
return bf2f(f32_to_bf16(bf2f(h[e]) * sc * g));
};
if (is_v) {
@@ -318,6 +346,19 @@ __global__ __launch_bounds__(kThreads) void widen_kernel(
y[(size_t)m * y_ld + i] = bf2f(x[(size_t)m * x_ld + i]);
}
// ---------------------------------------------------------------------------- cast bf16 -> f16
// ref_cast: the value rounded to nearest even once, so a bf16 value in f16's normal range is kept
// exactly and one past it becomes an infinity (rad_f32_to_f16).
__global__ __launch_bounds__(kThreads) void narrow_f16_kernel(
const uint16_t* __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] =
__builtin_bit_cast(uint16_t, (_Float16)bf2f(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,
@@ -350,6 +391,37 @@ __global__ __launch_bounds__(kThreads) void silu_kernel(
}
}
// The f32 form: f32 in, f32 out or bf16 rounded once (a timestep MLP's activation, rounded where
// the bf16 projection after it reads it). Flat over the extent.
__device__ __forceinline__ void st_act(float* p, float v) { *p = v; }
__device__ __forceinline__ void st_act(uint16_t* p, float v) { *p = f32_to_bf16(v); }
template <typename TY>
__global__ __launch_bounds__(kThreads) void silu_f32_kernel(
const float* __restrict__ x, TY* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld,
uint64_t total) {
for (uint64_t t = (uint64_t)blockIdx.x * kThreads + threadIdx.x; t < total;
t += (uint64_t)gridDim.x * kThreads) {
const uint64_t m = t / n;
const uint32_t i = (uint32_t)(t - m * n);
const float v = x[m * x_ld + i];
st_act(y + m * y_ld + i, v * (1.0f / (1.0f + expf(-v))));
}
}
// ref_gelu: the exact erf form, 0.5 x (1 + erf(x / sqrt 2)) in libref's order, one rounding (a
// ConvNeXt block's feed-forward activation; gated feed-forwards use the tanh form).
__global__ __launch_bounds__(kThreads) void gelu_kernel(
const uint16_t* __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) {
const float v = bf2f(x[(size_t)m * x_ld + i]);
y[(size_t)m * y_ld + i] = f32_to_bf16(0.5f * v * (1.0f + erff(v * 0.70710678118654752f)));
}
}
// ref_clamp: the two bounds are one-element weights, bf16 or f32.
__global__ __launch_bounds__(kThreads) void clamp_kernel(
const uint16_t* __restrict__ x, const void* __restrict__ lo, const void* __restrict__ hi,
@@ -533,10 +605,11 @@ __global__ __launch_bounds__(kThreads) void conv2d_lds_kernel(
}
// ref_conv1d_dw. One thread per (row, channel); the segment is found by a scan over cu_seqlens.
// `b`, when bound, is a bias per channel (bf16, or f32 with b_f32), added before the rounding.
__global__ __launch_bounds__(kThreads) void conv1d_dw_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const int* __restrict__ cu,
uint16_t* __restrict__ y, int C, int K, int cdiv, int S, uint32_t x_ld, uint32_t y_ld,
int rows) {
int rows, const void* __restrict__ b, int b_f32) {
const int c = (int)(blockIdx.x * kThreads + threadIdx.x);
if (c >= C) return;
for (int t = (int)blockIdx.y; t < rows; t += (int)gridDim.y) {
@@ -553,6 +626,7 @@ __global__ __launch_bounds__(kThreads) void conv1d_dw_kernel(
if (tt < t0) continue;
acc += bf2f(x[(size_t)tt * x_ld + c]) * bf2f(w[(size_t)c * K + j]);
}
if (b) acc += b_f32 ? ((const float*)b)[c] : bf2f(((const uint16_t*)b)[c]);
y[(size_t)t * y_ld + c] = f32_to_bf16(acc);
}
}
@@ -682,32 +756,43 @@ extern "C" int r4d_seg_mean_bf16(long x, long cu, long y, int S, int n, int x_ld
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// mode: 0 neox, 1 gptj, 2 blocks, 3 gptj_blocks, 4 imrope (`blk` and the position plane stride
// `pplane` used only by the last three).
// mode: 0 neox, 1 gptj, 2 blocks, 3 gptj_blocks, 4 imrope, 5 axial (`blk` and the position plane
// stride `pplane` used only by the last four). A null gain is a unit gain; `rot` 0 is the norm
// alone, and then `pos` may be null. `pos_f32` reads f32 positions as the values they hold.
extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M, int head_dim,
int n_head, int n_head_kv, int rot, int mode, int v_norm,
float theta, float eps, float rscale, float wadd, int ld,
const QkBlocks* blk, int pplane, long stream) {
if (!qkv || !pos || !qw || !kw) return -1;
if (M <= 0 || head_dim <= 0 || n_head <= 0 || n_head_kv <= 0 || rot <= 0 || rot > head_dim ||
(rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 4)
const QkBlocks* blk, int pplane, long stream, int w_f32,
int pos_f32) {
if (!qkv || (rot > 0 && !pos)) return -1;
if (M <= 0 || head_dim <= 0 || n_head <= 0 || n_head_kv <= 0 || rot < 0 || rot > head_dim ||
(rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 5)
return -2;
if (rot == 0) {
/* The norm alone: no pair is rotated, so no position is read. */
hipLaunchKernelGGL(qk_norm_rope_any_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0,
(hipStream_t)stream, (uint16_t*)qkv, (const void*)nullptr,
(const void*)qw, (const void*)kw, (uint32_t)head_dim,
(uint32_t)n_head, (uint32_t)n_head_kv, 0u, v_norm, theta, eps, rscale,
wadd, (uint32_t)ld, QkBlocks{}, 0u, 0, w_f32, 0);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
if (mode >= 3) {
/* gptj_blocks and imrope: general kernel only (its pair table is built per mode). */
/* gptj_blocks, imrope and axial: general kernel only (its pair table is built per mode). */
if (!blk || blk->n <= 0 || blk->n > 8) return -2;
int total = 0;
for (int c = 0; c < blk->n; ++c) {
if (blk->sec[c] <= 0) return -2;
total += blk->sec[c];
}
if (mode == 3 && 2 * total != rot) return -2;
if ((mode == 3 || mode == 5) && 2 * total != rot) return -2;
if (mode == 4 && (blk->n < 3 || 2 * total != rot)) return -2;
hipLaunchKernelGGL(qk_norm_rope_any_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0,
(hipStream_t)stream, (uint16_t*)qkv, (const int*)pos,
(const uint16_t*)qw, (const uint16_t*)kw, (uint32_t)head_dim,
(hipStream_t)stream, (uint16_t*)qkv, (const void*)pos,
(const void*)qw, (const void*)kw, (uint32_t)head_dim,
(uint32_t)n_head, (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta,
eps, rscale, wadd, (uint32_t)ld, *blk, (uint32_t)pplane,
mode == 3 ? 1 : 2);
mode == 3 ? 1 : mode == 4 ? 2 : 3, w_f32, pos_f32);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
if (mode != 2 && head_dim % 32) return -2;
@@ -729,18 +814,19 @@ extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M
}
if (any) {
hipLaunchKernelGGL(qk_norm_rope_any_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0,
(hipStream_t)stream, (uint16_t*)qkv, (const int*)pos,
(const uint16_t*)qw, (const uint16_t*)kw, (uint32_t)head_dim,
(hipStream_t)stream, (uint16_t*)qkv, (const void*)pos,
(const void*)qw, (const void*)kw, (uint32_t)head_dim,
(uint32_t)n_head, (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta,
eps, rscale, wadd, (uint32_t)ld, b, (uint32_t)pplane, 0);
eps, rscale, wadd, (uint32_t)ld, b, (uint32_t)pplane, 0, w_f32,
pos_f32);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
#define R4D_QN(MD) \
hipLaunchKernelGGL(qk_norm_rope_kernel<MD>, dim3((uint32_t)M), dim3(kQkThreads), 0, \
(hipStream_t)stream, (uint16_t*)qkv, (const int*)pos, (const uint16_t*)qw, \
(const uint16_t*)kw, (uint32_t)head_dim, (uint32_t)n_head, \
(hipStream_t)stream, (uint16_t*)qkv, (const void*)pos, (const void*)qw, \
(const void*)kw, (uint32_t)head_dim, (uint32_t)n_head, \
(uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta, eps, rscale, wadd, \
(uint32_t)ld, b, (uint32_t)pplane)
(uint32_t)ld, b, (uint32_t)pplane, w_f32, pos_f32)
if (mode == 1) R4D_QN(1);
else if (mode == 2) R4D_QN(2);
else R4D_QN(0);
@@ -769,6 +855,17 @@ extern "C" int r4d_widen_bf16_f32(long x, long y, int M, int n, int x_ld, int y_
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_narrow_bf16_f16(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_f16_kernel,
dim3((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M)),
dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)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;
@@ -778,6 +875,15 @@ extern "C" int r4d_relu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, l
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_gelu_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(gelu_kernel, dim3((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M)),
dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)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_silu_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;
@@ -830,14 +936,15 @@ extern "C" int r4d_conv2d_unfold_bf16(long x, long cu, long valid, long y, int r
}
extern "C" int r4d_conv1d_dw_bf16(long x, long w, long cu, long y, int rows, int C, int K,
int cdiv, int S, int x_ld, int y_ld, long stream) {
int cdiv, int S, int x_ld, int y_ld, long stream, long b = 0,
int b_f32 = 0) {
if (!x || !w || !cu || !y) return -1;
if (rows <= 0 || C <= 0 || K <= 0 || cdiv <= 0 || S <= 0) return -2;
hipLaunchKernelGGL(conv1d_dw_kernel,
dim3((uint32_t)((C + kThreads - 1) / kThreads), grid_rows(rows)),
dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)x,
(const uint16_t*)w, (const int*)cu, (uint16_t*)y, C, K, cdiv, S,
(uint32_t)x_ld, (uint32_t)y_ld, rows);
(uint32_t)x_ld, (uint32_t)y_ld, rows, (const void*)b, b_f32);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -958,32 +1065,60 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) {
const RadTensor* pos = r4d_opt(a, QN_POS);
const RadTensor* qw = r4d_opt(a, QN_QW);
const RadTensor* kw = r4d_opt(a, QN_KW);
if (!qkv || !pos || !qw || !kw) return R4D_NO(RAD_E_INVAL);
if (!qkv) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(qkv));
R4D_NEED(dt_bf16(qw));
R4D_NEED(dt_bf16(kw));
if (pos->dtype != RAD_I32 || !r4d_contig(pos)) return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(qw) || !r4d_contig(kw)) return R4D_NO(RAD_E_STRIDE);
/* The gains bf16 or f32, both alike (a model may keep its norms f32, libref reads either); an
* absent gain is a unit gain. */
const RadTensor* w0 = qw ? qw : kw;
if (w0 && ((w0->dtype != RAD_BF16 && w0->dtype != RAD_F32) ||
(qw && kw && kw->dtype != qw->dtype)))
return R4D_NO(RAD_E_DTYPE);
if ((qw && !r4d_contig(qw)) || (kw && !r4d_contig(kw))) return R4D_NO(RAD_E_STRIDE);
const long long hd = r4d_geti_or(a, "head_dim", 0);
const long long nh = r4d_geti_or(a, "n_head", 0);
const long long nkv = r4d_geti_or(a, "n_head_kv", 0);
const long long rot = r4d_geti_or(a, "rotary_dim", hd);
if (hd <= 0 || nh <= 0 || nkv <= 0 || r4d_numel(qw) < hd || r4d_numel(kw) < hd)
if (hd <= 0 || nh <= 0 || nkv <= 0 || (qw && r4d_numel(qw) < hd) ||
(kw && r4d_numel(kw) < hd))
return R4D_NO(RAD_E_SHAPE);
/* The register layout holds head_dim up to 1024 (32 lanes x kQkMaxE). */
if (hd > 1024 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
if (hd > 1024 || rot < 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
/* A rotation needs positions; the norm alone (rotary_dim 0) may go without. Positions are
* i32, or f32 read as the values they hold, M-contiguous ([M], or [C, M] at any plane
* pitch). */
if (rot > 0 && !pos) return R4D_NO(RAD_E_INVAL);
if (pos && pos->dtype != RAD_I32 && pos->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
if (pos && (pos->rank == 2 ? pos->stride[1] != 1 : !r4d_contig(pos)))
return R4D_NO(RAD_E_STRIDE);
const int pos_f32 = pos && pos->dtype == RAD_F32;
const char* mode = r4d_gets(a, "mode");
int md = 0;
if (mode && !std::strcmp(mode, "gptj")) md = 1;
else if (mode && !std::strcmp(mode, "blocks")) md = 2;
else if (mode && !std::strcmp(mode, "gptj_blocks")) md = 3;
else if (mode && !std::strcmp(mode, "imrope")) md = 4;
else if (mode && !std::strcmp(mode, "axial")) md = 5;
else if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED);
/* Any head_dim in the section modes (qk_norm_rope_any_kernel); the others need multiples of 32. */
if (md < 2 && hd % 32) return R4D_NO(RAD_E_SHAPE);
if (rot > 0 && md < 2 && hd % 32) return R4D_NO(RAD_E_SHAPE);
QkBlocks blk{};
long long M = 0, pplane = 0;
if (md == 4) {
if (rot == 0) {
/* Nothing turns: the rows are the positions' when bound, qkv's otherwise. */
M = !pos ? 0 : pos->rank == 2 ? pos->shape[1] : r4d_numel(pos);
} else if (md == 5) {
/* Contiguous sections on their own ladders, one position component each; rank-1
* positions turn every section by the one position. */
blk.n = parse_ints(r4d_gets(a, "sections"), blk.sec, 8);
if (blk.n <= 0) return R4D_NO(RAD_E_SHAPE);
if (pos->rank == 2) {
if (pos->shape[0] < blk.n) return R4D_NO(RAD_E_SHAPE);
M = pos->shape[1];
pplane = pos->stride[0];
} else {
M = r4d_numel(pos);
}
} else if (md == 4) {
/* Interleaved M-RoPE reads three position planes; its sections only bound the
* interleave. */
blk.n = parse_ints(r4d_gets(a, "sections"), blk.sec, 8);
@@ -1002,12 +1137,16 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) {
M = pos->shape[1];
pplane = pos->stride[0];
} else {
/* neox and gptj turn by one position a row. */
if (pos->rank >= 2 && pos->shape[0] != 1 && pos->shape[pos->rank - 1] != 1)
return R4D_NO(RAD_E_SHAPE);
M = r4d_numel(pos);
}
const long long width = (nh + 2 * nkv) * hd;
long long Mq = 0;
const long long ld = r4d_rows_pitch(qkv, width, &Mq);
if (ld < 0) return R4D_NO(RAD_E_STRIDE);
if (rot == 0 && !pos) M = Mq;
if (M <= 0 || Mq < M) return R4D_NO(RAD_E_SHAPE);
const int e = r4d_qk_norm_rope_bf16(r4d_addr(qkv), r4d_addr(pos), r4d_addr(qw), r4d_addr(kw),
(int)M, (int)hd, (int)nh, (int)nkv, (int)rot, md,
@@ -1016,7 +1155,8 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) {
(float)r4d_getf(a, "eps", 1e-6),
(float)r4d_getf(a, "scale", 1.0),
(float)r4d_getf(a, "wadd", 0.0), (int)ld, &blk,
(int)pplane, (long)(uintptr_t)s);
(int)pplane, (long)(uintptr_t)s,
w0 && w0->dtype == RAD_F32 ? 1 : 0, pos_f32);
if (e == -2) return R4D_NO(RAD_E_SHAPE);
return enc_status(e);
}
@@ -1058,6 +1198,24 @@ extern "C" int r4d_rad_cast_widen(const RadArgs* a, RadStream s) {
(int)y_ld, (long)(uintptr_t)s));
}
/* ------------------------------------------------------------------ cast bf16 -> f16 */
extern "C" int r4d_rad_cast_f16(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);
R4D_NEED(dt_bf16(x));
if (y->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE);
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_bf16_f16(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) {
@@ -1077,7 +1235,40 @@ extern "C" int r4d_rad_relu(const RadArgs* a, RadStream s) {
(long)(uintptr_t)s));
}
/* Both rows: silu_bf16 (bf16 in and out) and silu_f32 (f32 in, f32 or bf16 out). */
extern "C" int r4d_rad_silu(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);
const bool x_f32 = X->dtype == RAD_F32;
if (x_f32 ? (Y->dtype != RAD_F32 && Y->dtype != RAD_BF16)
: (X->dtype != RAD_BF16 || Y->dtype != RAD_BF16))
return R4D_NO(RAD_E_DTYPE);
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);
if (x_f32) {
const uint64_t total = (uint64_t)M * (uint64_t)n;
const dim3 grid((uint32_t)std::min<uint64_t>((total + kThreads - 1) / kThreads, 65536u));
if (Y->dtype == RAD_F32)
hipLaunchKernelGGL(silu_f32_kernel<float>, grid, dim3(kThreads), 0, (hipStream_t)s,
(const float*)X->data, (float*)Y->data, (uint32_t)n,
(uint32_t)x_ld, (uint32_t)y_ld, total);
else
hipLaunchKernelGGL(silu_f32_kernel<uint16_t>, grid, dim3(kThreads), 0, (hipStream_t)s,
(const float*)X->data, (uint16_t*)Y->data, (uint32_t)n,
(uint32_t)x_ld, (uint32_t)y_ld, total);
return enc_status(hipGetLastError() == hipSuccess ? 0 : -4);
}
return enc_status(r4d_silu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld,
(long)(uintptr_t)s));
}
extern "C" int r4d_rad_gelu(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);
@@ -1090,7 +1281,7 @@ extern "C" int r4d_rad_silu(const RadArgs* a, RadStream s) {
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_silu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld,
return enc_status(r4d_gelu_bf16(r4d_addr(X), r4d_addr(Y), (int)M, (int)n, (int)x_ld, (int)y_ld,
(long)(uintptr_t)s));
}
@@ -1207,15 +1398,18 @@ extern "C" int r4d_rad_conv1d_dw(const RadArgs* a, RadStream s) {
const RadTensor* Wt = r4d_opt(a, 1);
const RadTensor* cu = r4d_opt(a, 2);
const RadTensor* Y = r4d_opt(a, 3);
const RadTensor* B = r4d_opt(a, 4);
if (!X || !Wt || !cu || !Y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(X));
R4D_NEED(dt_bf16(Wt));
R4D_NEED(dt_bf16(Y));
if (B && B->dtype != RAD_BF16 && B->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
if (cu->dtype != RAD_I32 || !r4d_contig(cu) || r4d_numel(cu) < 2) return R4D_NO(RAD_E_SHAPE);
if (!r4d_contig(Wt)) return R4D_NO(RAD_E_STRIDE);
if (!r4d_contig(Wt) || (B && !r4d_contig(B))) return R4D_NO(RAD_E_STRIDE);
const long long C = r4d_geti_or(a, "n", 0), K = r4d_geti_or(a, "k", 0);
const long long cdiv = r4d_geti_or(a, "cu_div", 1);
if (C <= 0 || K <= 0 || cdiv <= 0 || r4d_numel(Wt) < C * K) return R4D_NO(RAD_E_SHAPE);
if (C <= 0 || K <= 0 || cdiv <= 0 || r4d_numel(Wt) < C * K || (B && r4d_numel(B) < C))
return R4D_NO(RAD_E_SHAPE);
long long Mx = 0, My = 0;
const long long x_ld = r4d_rows_pitch(X, C, &Mx);
const long long y_ld = r4d_rows_pitch(Y, C, &My);
@@ -1224,7 +1418,8 @@ extern "C" int r4d_rad_conv1d_dw(const RadArgs* a, RadStream s) {
return enc_status(r4d_conv1d_dw_bf16(r4d_addr(X), r4d_addr(Wt), r4d_addr(cu), r4d_addr(Y),
(int)My, (int)C, (int)K, (int)cdiv,
(int)(r4d_numel(cu) - 1), (int)x_ld, (int)y_ld,
(long)(uintptr_t)s));
(long)(uintptr_t)s, B ? r4d_addr(B) : 0,
B && B->dtype == RAD_F32 ? 1 : 0));
}
extern "C" int r4d_rad_rel_sinusoid(const RadArgs* a, RadStream s) {
+155
View File
@@ -0,0 +1,155 @@
// r4d_f32_tile.h -- the register-blocked f32 GEMM tile under libr4d's f32 GEMM (gemm_nt_bias at
// f32) and its f32 convolutions (conv1d and conv_t1d as implicit GEMMs, r4d_audio.hip).
//
// One 256-thread workgroup computes a BM x BN block (BM = 16 TM, BN = 16 TN) of C = A . W^T over
// K. Both operands are staged through LDS k-major, sixteen K a slab and two slabs of LDS, so the
// next slab's global loads are in flight under the current slab's FMAs and one barrier a slab
// suffices. A thread owns TM x TN accumulators and reads its operands from LDS as float4 (or
// float2) rows; every product is a fused multiply-add in ascending K, one rounding a product and
// sum, against libref's separate multiply and add in the same order.
//
// The operands come from loader policies: a thread stages rows `r0 + 16 j` of A (j < TM) and of W
// (j < TN) at one K column a slab, `kk = 16 slab + (tid % 16)`, so a GEMM reads rows in place and
// a convolution gathers the input row a tap reads, with its sequence's zero padding, from the same
// slot. A row or column past the operand reads zero. The epilogue is the caller's: it receives
// each run of contiguous columns a thread owns, in registers.
//
// Thread (tx, ty) = (tid % 16, tid / 16) owns rows g 16 RW + ty RW + r and columns
// g 16 CW + tx CW + c, RW = run_of(TM) and CW = run_of(TN): a wave's sixteen tx read 16 CW
// contiguous floats of W's slab row, conflict-free, and the two ty values of a wave read two A
// vectors, each broadcast. The LDS pitch is padded by four floats, which spreads the staging
// stores (a wave's 16 K columns of one row) over distinct banks.
#pragma once
#include <hip/hip_runtime.h>
#include <cstdint>
namespace r4d_f32 {
constexpr int kThr = 256;
constexpr int kBK = 16; // K a staged slab
// The run a thread owns along an axis of `t` values: four where `t` is whole fours, else two (a
// tile of 6 columns is three runs of two, so a 96-wide output fills its tile exactly).
constexpr int run_of(int t) { return t % 4 == 0 ? 4 : 2; }
// A plain row-major f32 operand: row r, column k at p[r * ld + k], zero past `rows` or `K`. Every
// load is issued, at an address clamped into the operand, and the zero selected after it: a load
// guarded by a branch serialises the slab's loads behind one another. Offsets are 32-bit, so the
// operand spans fewer than 2^32 elements (the shims check).
template <int CNT>
struct RowsLoader {
const float* p;
int ld, rows, K;
int k = 0;
uint32_t off[CNT];
bool live[CNT];
__device__ void init(int first_row, int kk) {
k = kk;
#pragma unroll
for (int j = 0; j < CNT; ++j) {
const int r = first_row + 16 * j;
live[j] = r < rows;
off[j] = (uint32_t)(r < rows ? r : rows - 1) * (uint32_t)ld;
}
}
__device__ void fetch(float (&v)[CNT]) const {
const bool kl = k < K;
const uint32_t kc = (uint32_t)(kl ? k : K - 1);
#pragma unroll
for (int j = 0; j < CNT; ++j) {
const float x = p[off[j] + kc];
v[j] = (live[j] && kl) ? x : 0.0f;
}
}
__device__ void advance() { k += kBK; }
};
template <int TM, int TN, class LA, class LW, class EP>
__device__ __forceinline__ void tile(LA& la, LW& lw, int K, EP& ep) {
constexpr int BM = 16 * TM, BN = 16 * TN;
constexpr int AP = BM + 4, WP = BN + 4;
constexpr int RW = run_of(TM), RG = TM / RW;
constexpr int CW = run_of(TN), CG = TN / CW;
static_assert(RW * RG == TM && CW * CG == TN && (RW == 2 || RW == 4) && (CW == 2 || CW == 4),
"a thread's rows and columns are whole runs of two or four");
__shared__ __attribute__((aligned(16))) float sA[2][kBK][AP];
__shared__ __attribute__((aligned(16))) float sW[2][kBK][WP];
const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4;
float acc[TM][TN];
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j) acc[i][j] = 0.0f;
float ra[TM], rw[TN];
la.fetch(ra);
lw.fetch(rw);
const int ns = (K + kBK - 1) / kBK;
for (int s = 0; s < ns; ++s) {
const int b = s & 1;
#pragma unroll
for (int j = 0; j < TM; ++j) sA[b][tx][ty + 16 * j] = ra[j];
#pragma unroll
for (int j = 0; j < TN; ++j) sW[b][tx][ty + 16 * j] = rw[j];
__syncthreads();
if (s + 1 < ns) {
la.advance();
lw.advance();
la.fetch(ra);
lw.fetch(rw);
}
#pragma unroll
for (int k = 0; k < kBK; ++k) {
float a[TM], w[TN];
#pragma unroll
for (int g = 0; g < RG; ++g) {
const float* src = &sA[b][k][g * 16 * RW + ty * RW];
if constexpr (RW == 4) {
const float4 q = *(const float4*)src;
a[g * 4] = q.x; a[g * 4 + 1] = q.y; a[g * 4 + 2] = q.z; a[g * 4 + 3] = q.w;
} else {
const float2 q = *(const float2*)src;
a[g * 2] = q.x; a[g * 2 + 1] = q.y;
}
}
#pragma unroll
for (int g = 0; g < CG; ++g) {
const float* src = &sW[b][k][g * 16 * CW + tx * CW];
if constexpr (CW == 4) {
const float4 q = *(const float4*)src;
w[g * 4] = q.x; w[g * 4 + 1] = q.y; w[g * 4 + 2] = q.z; w[g * 4 + 3] = q.w;
} else {
const float2 q = *(const float2*)src;
w[g * 2] = q.x; w[g * 2 + 1] = q.y;
}
}
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j) acc[i][j] = __builtin_fmaf(a[i], w[j], acc[i][j]);
}
/* One barrier a slab: the next slab goes to the other buffer, which every thread finished
* reading before it passed this slab's barrier. */
}
/* A run of CW columns as one float4 (the last two lanes unused at CW 2), so the accumulators
* stay in registers through the caller's store; `gj` says which of the thread's CG runs it
* is, for state the caller keeps per run. */
#pragma unroll
for (int gi = 0; gi < RG; ++gi)
#pragma unroll
for (int r = 0; r < RW; ++r)
#pragma unroll
for (int gj = 0; gj < CG; ++gj) {
const float* q = acc[gi * RW + r] + gj * CW;
float4 v;
if constexpr (CW == 4) v = make_float4(q[0], q[1], q[2], q[3]);
else v = make_float4(q[0], q[1], 0.0f, 0.0f);
ep(gi * 16 * RW + ty * RW + r, gj * 16 * CW + tx * CW, CW, v, gj);
}
}
} // namespace r4d_f32
+163
View File
@@ -0,0 +1,163 @@
// r4d_gemm_f32_nt_bias.hip -- gemm_nt_bias at f32: C = res + act(A @ W^T + bias) with an f32
// activation and weight, f32 accumulation, and the result f32 or rounded to bf16 at the store.
// The epilogue is libref's: the biased product, the activation of it and the residual sum each
// rounded to C's dtype, as the unfused chain's tensors would be; at an f32 C only the arithmetic
// rounds. A diffusion transformer's patch projections and output heads, its timestep MLP, and a
// video decoder's 1x1 projections run here: K from 24 to a few thousand, N from 24 to 5376, M up
// to a hundred thousand rows.
//
// The tile is r4d_f32_tile.h's at 128 rows: 128 columns where N is wider than 96, 96 where it is
// wider than 64, 64 where it is wider than 32, 32 otherwise, so a narrow head (N 32 or 96) fills
// its tile. No split-K: the narrow-N shapes have hundreds of row tiles.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include "r4d_f32_tile.h"
#include <cmath>
#include <cstring>
namespace {
constexpr int kTM = 8, kBM = 16 * kTM;
__device__ __forceinline__ float gelu_erf(float x) {
return 0.5f * x * (1.0f + erff(x * 0.70710678118654752f));
}
__device__ __forceinline__ float gelu_tanh(float x) {
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
return 0.5f * x * (1.0f + tanhf(k0 * (x + k1 * x * x * x)));
}
// C's element: f32 as it is, or bf16 rounded to nearest even.
__device__ __forceinline__ float rd(const float*, float v) { return v; }
__device__ __forceinline__ float rd(const uint16_t*, float v) { return bf16_to_f32(f32_to_bf16(v)); }
__device__ __forceinline__ float ld1(const float* p) { return *p; }
__device__ __forceinline__ float ld1(const uint16_t* p) { return bf16_to_f32(*p); }
__device__ __forceinline__ void st1(float* p, float v) { *p = v; }
__device__ __forceinline__ void st1(uint16_t* p, float v) { *p = f32_to_bf16(v); }
// Four (or two) adjacent elements in one store: 16 (8) bytes at f32, 8 (4) at bf16.
__device__ __forceinline__ void stv(float* p, int cnt, const float* v) {
if (cnt == 4) *(float4*)p = make_float4(v[0], v[1], v[2], v[3]);
else *(float2*)p = make_float2(v[0], v[1]);
}
__device__ __forceinline__ void stv(uint16_t* p, int cnt, const float* v) {
if (cnt == 4) *(uint2*)p = make_uint2(bf16x2_rne(v[0], v[1]), bf16x2_rne(v[2], v[3]));
else *(uint32_t*)p = bf16x2_rne(v[0], v[1]);
}
// `act` 0 none, 1 exact GELU, 2 tanh GELU. `R` may be `C` itself (a residual updated in place):
// each element is read by the thread that stores it, before the store. `vec` says C's rows take
// whole-run stores (a pitch of whole runs at an aligned base).
template <int TN, typename TY>
__global__ __launch_bounds__(r4d_f32::kThr) void gemm_f32_bias_kernel(
const float* __restrict__ A, int lda, const float* __restrict__ W, int K,
const void* __restrict__ bias, int bias_f32, const TY* R, int ldr, TY* C, int ldc, int M,
int N, int act, int vec) {
constexpr int BN = 16 * TN, CW = r4d_f32::run_of(TN);
const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4;
const int m0 = blockIdx.y * kBM, n0 = blockIdx.x * BN;
r4d_f32::RowsLoader<kTM> la{ A, lda, M, K };
r4d_f32::RowsLoader<TN> lw{ W, K, N, K };
la.init(m0 + ty, tx);
lw.init(n0 + ty, tx);
/* The bias of this thread's TN columns (runs of CW, 16 CW apart), read once. */
float bc[TN];
#pragma unroll
for (int j = 0; j < TN; ++j) {
const int n = n0 + (j / CW) * 16 * CW + tx * CW + j % CW;
const int nc = n < N ? n : N - 1;
bc[j] = bias_f32 ? ((const float*)bias)[nc] : bf16_to_f32(((const uint16_t*)bias)[nc]);
}
auto ep = [&](int r, int c, int cnt, float4 q, int g) {
const int m = m0 + r, n = n0 + c;
if (m >= M || n >= N) return;
float v[4] = { q.x, q.y, q.z, q.w };
#pragma unroll
for (int e = 0; e < CW; ++e) {
float t = rd(C, v[e] + bc[g * CW + e]);
if (act == 1) t = rd(C, gelu_erf(t));
else if (act == 2) t = rd(C, gelu_tanh(t));
if (R && n + e < N) t = ld1(R + (size_t)m * ldr + n + e) + t;
v[e] = t;
}
TY* dst = C + (size_t)m * ldc + n;
if (vec && n + cnt <= N) {
stv(dst, cnt, v);
} else {
#pragma unroll
for (int e = 0; e < 4; ++e)
if (e < cnt && n + e < N) st1(dst + e, v[e]);
}
};
r4d_f32::tile<kTM, TN>(la, lw, K, ep);
}
} // namespace
// ============================================================== the plugin ABI entry point
enum { GF_A = 0, GF_W, GF_BIAS, GF_RES, GF_Y };
extern "C" int r4d_rad_gemm_f32_nt_bias(const RadArgs* a, RadStream stream) {
const RadTensor* A = r4d_opt(a, GF_A);
const RadTensor* W = r4d_opt(a, GF_W);
const RadTensor* B = r4d_opt(a, GF_BIAS);
const RadTensor* R = r4d_opt(a, GF_RES);
const RadTensor* Y = r4d_opt(a, GF_Y);
if (!A || !W || !B || !Y) return R4D_NO(RAD_E_INVAL);
/* f32 A and W; C f32 or bf16, the residual C's dtype; the bias f32 or bf16. */
if (A->dtype != RAD_F32 || W->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
if (Y->dtype != RAD_F32 && Y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if (B->dtype != RAD_F32 && B->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if (R && R->dtype != Y->dtype) return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(W) || !r4d_contig(B)) return R4D_NO(RAD_E_STRIDE);
const long long K = r4d_geti_or(a, "K", r4d_dim(W, (int)W->rank - 1));
const long long N = r4d_geti_or(a, "N", r4d_numel(W) / (K > 0 ? K : 1));
if (K <= 0 || N <= 0 || r4d_numel(W) < N * K || r4d_numel(B) < N) return R4D_NO(RAD_E_SHAPE);
long long M = 0, Ma = 0, Mr = 0;
const long long ldc = r4d_rows_pitch(Y, N, &M);
const long long lda = r4d_rows_pitch(A, K, &Ma);
const long long ldr = R ? r4d_rows_pitch(R, N, &Mr) : 0;
if (ldc < 0 || lda < 0 || ldr < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || Ma < M || (R && Mr < M)) return R4D_NO(RAD_E_SHAPE);
/* The tile's loaders index A and W with 32-bit element offsets. */
if (M > 0x7fffffffll || N > 0x7fffffffll || K > 0x7fffffffll || lda > 0x7fffffffll ||
ldc > 0x7fffffffll || ldr > 0x7fffffffll || (M + kBM - 1) / kBM > 65535 ||
M * lda >= (1ll << 32) || N * K >= (1ll << 32))
return R4D_NO(RAD_E_SHAPE);
const char* act_s = r4d_gets(a, "act");
int act = 0;
if (act_s && *act_s) {
if (!std::strcmp(act_s, "gelu")) act = 1;
else if (!std::strcmp(act_s, "gelu_tanh")) act = 2;
else if (std::strcmp(act_s, "none")) return R4D_NO(RAD_E_SCHEMA);
}
const int bias_f32 = B->dtype == RAD_F32;
const bool f32 = Y->dtype == RAD_F32;
/* Whole-run stores where every row starts aligned to a run of four. */
const unsigned run_bytes = f32 ? 16u : 8u;
const int vec = (ldc % 4) == 0 && r4d_aligned(r4d_p(Y), run_bytes);
const int tn = N > 96 ? 8 : N > 64 ? 6 : N > 32 ? 4 : 2;
const dim3 grid((unsigned)((N + 16 * tn - 1) / (16 * tn)), (unsigned)((M + kBM - 1) / kBM));
const dim3 block(r4d_f32::kThr);
#define GF_L(TN, TY) \
return R4D_EMIT(stream, (gemm_f32_bias_kernel<TN, TY>), grid, block, 0, \
(const float*)r4d_p(A), (int)lda, (const float*)r4d_p(W), (int)K, r4d_p(B), \
bias_f32, (const TY*)r4d_p(R), (int)ldr, (TY*)r4d_wp(Y), (int)ldc, (int)M, \
(int)N, act, vec)
if (f32) {
if (tn == 8) GF_L(8, float);
if (tn == 6) GF_L(6, float);
if (tn == 4) GF_L(4, float);
GF_L(2, float);
}
if (tn == 8) GF_L(8, uint16_t);
if (tn == 6) GF_L(6, uint16_t);
if (tn == 4) GF_L(4, uint16_t);
GF_L(2, uint16_t);
#undef GF_L
}
+461 -374
View File
File diff suppressed because it is too large. Load diff
+91 -36
View File
@@ -99,9 +99,10 @@ __global__ __launch_bounds__(kT) void ln_mod_kernel(
}
// ---------------------------------------------------------------------------- gate_add
// `act` 0 gates through bf16(tanh(g)), 1 through g as it is (a gate with no tanh).
__global__ __launch_bounds__(kT) void gate_add_kernel(
const uint16_t* __restrict__ y, const uint16_t* __restrict__ g, const int* __restrict__ cu,
uint16_t* __restrict__ x, int n, int n_seq, int y_ld, int g_ld, int x_ld) {
uint16_t* __restrict__ x, int n, int n_seq, int y_ld, int g_ld, int x_ld, int act) {
const int r = blockIdx.x;
const uint16_t* gr = g + (size_t)seq_of(cu, n_seq, r) * g_ld;
for (int i = threadIdx.x * 8; i < n; i += kT * 8) {
@@ -110,7 +111,7 @@ __global__ __launch_bounds__(kT) void gate_add_kernel(
ld8(gr + i, b);
ld8(x + (size_t)r * x_ld + i, c);
#pragma unroll
for (int j = 0; j < 8; ++j) c[j] = c[j] + bfr(bfr(tanhf(b[j])) * a[j]);
for (int j = 0; j < 8; ++j) c[j] = c[j] + bfr((act ? b[j] : bfr(tanhf(b[j]))) * a[j]);
st8(x + (size_t)r * x_ld + i, c);
}
}
@@ -196,8 +197,13 @@ __global__ __launch_bounds__(kT) void ln_mod_quant_kernel(
}
// ---------------------------------------------------------------------------- timestep_embed
// An output element, bf16 rounded once or f32 as it is.
__device__ __forceinline__ void st1(uint16_t* p, float v) { *p = f32_to_bf16(v); }
__device__ __forceinline__ void st1(float* p, float v) { *p = v; }
template <typename TY>
__global__ __launch_bounds__(kT) void timestep_kernel(
const float* __restrict__ t, uint16_t* __restrict__ y, int h, float scale, float coef,
const float* __restrict__ t, TY* __restrict__ y, int h, float scale, float coef,
int round, int y_ld) {
const int m = blockIdx.x;
const float tv = t[m];
@@ -205,8 +211,8 @@ __global__ __launch_bounds__(kT) void timestep_kernel(
for (int i = threadIdx.x; i < h; i += kT) {
const float f = expf(coef * (float)i / (float)h);
const float arg = tt * f;
y[(size_t)m * y_ld + i] = f32_to_bf16(cosf(arg));
y[(size_t)m * y_ld + h + i] = f32_to_bf16(sinf(arg));
st1(y + (size_t)m * y_ld + i, cosf(arg));
st1(y + (size_t)m * y_ld + h + i, sinf(arg));
}
}
@@ -268,17 +274,19 @@ __device__ __forceinline__ uint64_t seed_of(const uint32_t* seed, int e) {
return (uint64_t)seed[2 * e] | ((uint64_t)seed[2 * e + 1] << 32);
}
// `TD` is the lane's element: bf16 latents, or f32 ones the sampler keeps in f32.
template <typename TD>
__global__ __launch_bounds__(kT) void randn_lanes_kernel(
const int* __restrict__ flags, const uint32_t* __restrict__ seed, const int* __restrict__ lane,
const int* __restrict__ cu, uint16_t* __restrict__ dst, int n, int stride, int d_ld) {
const int* __restrict__ cu, TD* __restrict__ dst, int n, int stride, int d_ld) {
const int e = blockIdx.y;
if (!(flags[e] & 1)) return;
const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x;
const int64_t len = cu[e + 1] - cu[e];
if (i >= len * n) return;
const int64_t k = i / n, c = i % n;
dst[((size_t)lane[e] * stride + k) * d_ld + c] =
f32_to_bf16(rad_philox_normal(seed_of(seed, e), (uint64_t)i));
st1(dst + ((size_t)lane[e] * stride + k) * d_ld + c,
rad_philox_normal(seed_of(seed, e), (uint64_t)i));
}
__global__ __launch_bounds__(kT) void flow_euler_kernel(
@@ -321,14 +329,27 @@ __global__ __launch_bounds__(kT) void flow_euler_kernel(
constexpr int kChanMax = 64;
struct ChanLists { float mul[kChanMax], add[kChanMax]; };
// `T` is x's and y's element, bf16 or f32. With `rnd` the inner product or difference rounds to
// y's dtype (and the lists were rounded to bf16 by the shim); without it the arithmetic stays f32
// and rounds once into y.
__device__ __forceinline__ float ca_ld(const uint16_t* p, size_t i) { return bf2f(p[i]); }
__device__ __forceinline__ float ca_ld(const float* p, size_t i) { return p[i]; }
__device__ __forceinline__ float ca_rd(const uint16_t*, float v) { return bfr(v); }
__device__ __forceinline__ float ca_rd(const float*, float v) { return v; }
__device__ __forceinline__ void ca_st(uint16_t* p, int64_t i, float v) { p[i] = f32_to_bf16(v); }
__device__ __forceinline__ void ca_st(float* p, int64_t i, float v) { p[i] = v; }
template <typename T>
__global__ __launch_bounds__(kT) void chan_affine_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, int64_t total, int n, int x_ld,
int inv, ChanLists l) {
const T* __restrict__ x, T* __restrict__ y, int64_t total, int n, int x_ld, int inv, int rnd,
ChanLists l) {
const int64_t i = (int64_t)blockIdx.x * kT + threadIdx.x;
if (i >= total) return;
const int c = (int)(i % n);
const float v = bf2f(x[(size_t)(i / n) * x_ld + c]);
y[i] = f32_to_bf16(inv ? bfr(v - l.add[c]) / l.mul[c] : bfr(v * l.mul[c]) + l.add[c]);
const float v = ca_ld(x, (size_t)(i / n) * x_ld + c);
const float t = inv ? v - l.add[c] : v * l.mul[c];
const float r = rnd ? ca_rd(y, t) : t;
ca_st(y, i, inv ? r / l.mul[c] : r + l.add[c]);
}
// A wave a pixel: the sum of squares over its channels, then the three roundings.
@@ -625,18 +646,21 @@ inline bool image_of(const RadTensor* t, long long c, long long* H, long long* W
return true;
}
// A parameter list of floats, each rounded to bf16 as the reference's bf16 tensor of it.
int parse_bf16_list(const char* s, float* out, int max) {
// A parameter list of floats, each rounded to bf16 as the reference's bf16 tensor of it, or kept
// in f32 with `bf16` false.
int parse_bf16_list(const char* s, float* out, int max, bool bf16 = true) {
int n = 0;
while (s && *s && n < max) {
char* end = nullptr;
const double v = std::strtod(s, &end);
if (end == s) break;
float f = (float)v;
uint32_t u;
std::memcpy(&u, &f, 4);
u = (u + 0x7FFFu + ((u >> 16) & 1u)) & 0xFFFF0000u;
std::memcpy(&f, &u, 4);
if (bf16) {
uint32_t u;
std::memcpy(&u, &f, 4);
u = (u + 0x7FFFu + ((u >> 16) & 1u)) & 0xFFFF0000u;
std::memcpy(&f, &u, 4);
}
out[n++] = f;
s = end;
}
@@ -718,16 +742,23 @@ extern "C" int r4d_rad_gate_add(const RadArgs* a, RadStream s) {
if (gl < 0 || (gl & 7) || ((uintptr_t)g->data & 15)) return R4D_NO(RAD_E_STRIDE);
const long long n_seq = r4d_numel(cu) - 1;
if (ry <= 0 || rx < ry || n_seq <= 0 || rg < n_seq) return R4D_NO(RAD_E_SHAPE);
/* The gate's activation: tanh (the default) or none. */
const char* act = r4d_gets(a, "act");
const int none = act && !std::strcmp(act, "none");
if (!none && act && std::strcmp(act, "tanh")) return R4D_NO(RAD_E_INVAL);
hipLaunchKernelGGL(gate_add_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s,
(const uint16_t*)y->data, (const uint16_t*)g->data, (const int*)cu->data,
(uint16_t*)x->data, (int)n, (int)n_seq, (int)yl, (int)gl, (int)xl);
(uint16_t*)x->data, (int)n, (int)n_seq, (int)yl, (int)gl, (int)xl, none);
return st_of(hipGetLastError());
}
/* Both rows: a bf16 embedding (timestep_embed_bf16) or an f32 one (timestep_embed_f32, a timestep
* MLP kept in f32). */
extern "C" int r4d_rad_timestep_embed(const RadArgs* a, RadStream s) {
const RadTensor *t = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!t || !y) return R4D_NO(RAD_E_INVAL);
if (t->dtype != RAD_F32 || !r4d_contig(t) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE);
if (t->dtype != RAD_F32 || !r4d_contig(t) || (!is_bf16(y) && y->dtype != RAD_F32))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
if (n <= 0 || (n & 1)) return R4D_NO(RAD_E_SHAPE);
long long ry = 0;
@@ -736,10 +767,16 @@ extern "C" int r4d_rad_timestep_embed(const RadArgs* a, RadStream s) {
if (ry <= 0 || r4d_numel(t) < ry) return R4D_NO(RAD_E_SHAPE);
const float mp = (float)r4d_getf(a, "max_period", 10000.0);
const float coef = (float)(-std::log((double)mp));
hipLaunchKernelGGL(timestep_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s,
(const float*)t->data, (uint16_t*)y->data, (int)(n / 2),
(float)r4d_getf(a, "scale", 1000.0), coef,
(int)r4d_geti_or(a, "round", 0), (int)yl);
const float scale = (float)r4d_getf(a, "scale", 1000.0);
const int round = (int)r4d_geti_or(a, "round", 0);
if (y->dtype == RAD_F32)
hipLaunchKernelGGL(timestep_kernel<float>, dim3((unsigned)ry), dim3(kT), 0,
(hipStream_t)s, (const float*)t->data, (float*)y->data, (int)(n / 2),
scale, coef, round, (int)yl);
else
hipLaunchKernelGGL(timestep_kernel<uint16_t>, dim3((unsigned)ry), dim3(kT), 0,
(hipStream_t)s, (const float*)t->data, (uint16_t*)y->data, (int)(n / 2),
scale, coef, round, (int)yl);
return st_of(hipGetLastError());
}
@@ -817,7 +854,8 @@ extern "C" int r4d_rad_randn_lanes(const RadArgs* a, RadStream s) {
const RadTensor *fl = r4d_opt(a, 0), *seed = r4d_opt(a, 1), *lane = r4d_opt(a, 2);
const RadTensor *cu = r4d_opt(a, 3), *dst = r4d_opt(a, 4);
if (!fl || !seed || !lane || !cu || !dst) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(dst)) return R4D_NO(RAD_E_DTYPE);
/* bf16 lanes (randn_lanes_bf16) or f32 ones (randn_lanes_f32). */
if (!is_bf16(dst) && dst->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), stride = r4d_geti_or(a, "stride", 0);
long long rd = 0;
const long long dl = r4d_rows_pitch(dst, n, &rd);
@@ -827,10 +865,17 @@ extern "C" int r4d_rad_randn_lanes(const RadArgs* a, RadStream s) {
/* One flag and lane an entry, two seed words. A lane's rows (device data) are not checked. */
if (r4d_numel(fl) < n_seq || r4d_numel(lane) < n_seq || r4d_numel(seed) < 2 * n_seq)
return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(randn_lanes_kernel, dim3(blocks_for(stride * n), (unsigned)n_seq), dim3(kT),
0, (hipStream_t)s, (const int*)fl->data, (const uint32_t*)seed->data,
(const int*)lane->data, (const int*)cu->data, (uint16_t*)dst->data, (int)n,
(int)stride, (int)dl);
const dim3 grid(blocks_for(stride * n), (unsigned)n_seq);
if (dst->dtype == RAD_F32)
hipLaunchKernelGGL(randn_lanes_kernel<float>, grid, dim3(kT), 0, (hipStream_t)s,
(const int*)fl->data, (const uint32_t*)seed->data,
(const int*)lane->data, (const int*)cu->data, (float*)dst->data, (int)n,
(int)stride, (int)dl);
else
hipLaunchKernelGGL(randn_lanes_kernel<uint16_t>, grid, dim3(kT), 0, (hipStream_t)s,
(const int*)fl->data, (const uint32_t*)seed->data,
(const int*)lane->data, (const int*)cu->data, (uint16_t*)dst->data,
(int)n, (int)stride, (int)dl);
return st_of(hipGetLastError());
}
@@ -870,26 +915,36 @@ extern "C" int r4d_rad_flow_euler(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
/* Both rows: x and y bf16 (chan_affine_bf16) or both f32 (chan_affine_f32). `round` 0 keeps the
* lists and the arithmetic in f32. */
extern "C" int r4d_rad_chan_affine(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
const bool f32 = y->dtype == RAD_F32;
if (x->dtype != y->dtype || (!f32 && !is_bf16(y))) return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), rnd = r4d_geti_or(a, "round", 1);
if (rnd < 0 || rnd > 1) return R4D_NO(RAD_E_INVAL);
long long rx = 0;
const long long xl = n > 0 ? r4d_rows_pitch(x, n, &rx) : -1;
if (xl < 0 || !r4d_contig(y)) return R4D_NO(RAD_E_STRIDE);
ChanLists l{};
if (n <= 0 || n > kChanMax || parse_bf16_list(r4d_gets(a, "mul"), l.mul, kChanMax) != n ||
parse_bf16_list(r4d_gets(a, "add"), l.add, kChanMax) != n)
if (n <= 0 || n > kChanMax ||
parse_bf16_list(r4d_gets(a, "mul"), l.mul, kChanMax, rnd != 0) != n ||
parse_bf16_list(r4d_gets(a, "add"), l.add, kChanMax, rnd != 0) != n)
return R4D_NO(RAD_E_SHAPE);
const char* mode = r4d_gets(a, "mode");
const int inv = mode && !std::strcmp(mode, "inv");
if (!inv && mode && std::strcmp(mode, "fma")) return R4D_NO(RAD_E_INVAL);
const long long total = r4d_numel(y);
if (total <= 0 || total % n || rx * n < total) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(chan_affine_kernel, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s,
(const uint16_t*)x->data, (uint16_t*)y->data, (int64_t)total, (int)n,
(int)xl, inv, l);
if (f32)
hipLaunchKernelGGL(chan_affine_kernel<float>, dim3(blocks_for(total)), dim3(kT), 0,
(hipStream_t)s, (const float*)x->data, (float*)y->data, (int64_t)total,
(int)n, (int)xl, inv, (int)rnd, l);
else
hipLaunchKernelGGL(chan_affine_kernel<uint16_t>, dim3(blocks_for(total)), dim3(kT), 0,
(hipStream_t)s, (const uint16_t*)x->data, (uint16_t*)y->data,
(int64_t)total, (int)n, (int)xl, inv, (int)rnd, l);
return st_of(hipGetLastError());
}
+296 -9
View File
@@ -275,8 +275,14 @@ const uint8_t* pdata(const RadTensor& t) { return (const uint8_t*)t.data; }
/* The f16 scale of a canonical plane as f32; scale_zero_dword narrows it back exactly. */
float f16_at(const RadTensor& t, long long i) { return f16_to_f32(((const uint16_t*)t.data)[i]); }
/* An integer zero point from a u4 or u8 plane. */
int zero_at(const RadTensor& t, long long i) { return (int)rad_load_f32(t.data, t.dtype, i); }
/* Zero point `gi` of row `n` of a [N, nsz] u4 or u8 plane. Rows start on a byte (rad_encoding.h),
* so a u4 row of an odd number of groups ends in a pad nibble and the next row starts after it. */
uint8_t* zero_row(const RadTensor& t, long long n, long long nsz) {
return (uint8_t*)t.data + n * rad_enc_row_bytes(t.dtype, nsz);
}
int zero_at(const RadTensor& t, long long n, long long nsz, long long gi) {
return (int)rad_load_f32(zero_row(t, n, nsz), t.dtype, gi);
}
/* The dense w4/w8/w2 families' scale operand: (scale) for a symmetric grid, (scale, zero) for an
* asymmetric one, tile-major [N/16][(K/group)*16] in dwords or, for w8a8, halves. */
@@ -298,7 +304,7 @@ void sz_write(const WGeom& g, const RadTensor* pl, int zfixed, uint32_t* sz) {
for (long long r = 0; r < R4D_NTILE; ++r)
for (long long gi = 0; gi < nsz; ++gi) {
const long long n = t * R4D_NTILE + r;
const int z = zfixed >= 0 ? zfixed : zero_at(pl[1], n * nsz + gi);
const int z = zfixed >= 0 ? zfixed : zero_at(pl[1], n, nsz, gi);
const float sc = f16_at(pl[0], n * nsz + gi);
sz[(t * nsz + gi) * R4D_NTILE + r] = scale_zero_dword(sc, z);
}
@@ -308,11 +314,12 @@ void sz_write(const WGeom& g, const RadTensor* pl, int zfixed, uint32_t* sz) {
* reads five bits of the zero out of the scale dword where the f16 kernel reads the whole value,
* so a larger zero would make the two disagree. */
bool sz_zeros_fit(const WGeom& g, const RadTensor& zp, int bits) {
const long long nz = g.N * (g.K / g.group);
for (long long i = 0; i < nz; ++i) {
const int z = zero_at(zp, i);
if (z < 0 || z >= (1 << bits)) return false;
}
const long long nsz = g.K / g.group;
for (long long n = 0; n < g.N; ++n)
for (long long gi = 0; gi < nsz; ++gi) {
const int z = zero_at(zp, n, nsz, gi);
if (z < 0 || z >= (1 << bits)) return false;
}
return true;
}
@@ -326,7 +333,7 @@ void sz_read(const WGeom& g, const uint32_t* sz, const RadTensor* pl, bool asym)
((uint16_t*)pl[0].data)[n * nsz + gi] = (uint16_t)(d & 0xFFFFu);
if (asym) {
const int z = (int)(-f16_to_f32((uint16_t)(d >> 16)) - 1024.0f + 0.5f);
rad_store_code(pl[1].data, pl[1].dtype, n * nsz + gi, z);
rad_store_code(zero_row(pl[1], n, nsz), pl[1].dtype, gi, z);
}
}
}
@@ -1282,3 +1289,283 @@ extern "C" int r4d_rad_unrelayout_conv_tap(const RadParam* p, int n_p, int opera
d[(o * ci + c) * kk + t] = s[(o * kk + 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.
*
* conv1d PyTorch's Conv1d [cout][cin][k] stored [cout][k][cin]
* conv_t1d PyTorch's ConvTranspose1d [cin][cout][2s] stored [s][cout][2][cin], phase r's
* taps (r, r + s) one [cout][2 cin] GEMM operand
*/
namespace {
int conv1d_geom(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout,
long long* cin, long long* k) {
*cout = r4d_pgeti_or(p, n_p, "cout", 0);
*cin = r4d_pgeti_or(p, n_p, "cin", 0);
*k = r4d_pgeti_or(p, n_p, "k", 0);
if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || *k <= 0) return RAD_E_SHAPE;
if (pl[0].dtype != RAD_BF16 || rad_tensor_numel(&pl[0]) != *cout * *cin * *k) return RAD_E_SHAPE;
return RAD_OK;
}
/* The transposed convolution's kernel is `k` = 2 stride (the default) or stride: `taps` = k /
* stride input rows feed each output row. */
int convt_geom(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout,
long long* cin, long long* s, long long* taps) {
*cout = r4d_pgeti_or(p, n_p, "cout", 0);
*cin = r4d_pgeti_or(p, n_p, "cin", 0);
*s = r4d_pgeti_or(p, n_p, "stride", 0);
const long long k = r4d_pgeti_or(p, n_p, "k", 2 * *s);
if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || *s <= 0 || (k != *s && k != 2 * *s))
return RAD_E_SHAPE;
*taps = k / *s;
if (pl[0].dtype != RAD_BF16 || rad_tensor_numel(&pl[0]) != *cin * *cout * k)
return RAD_E_SHAPE;
return RAD_OK;
}
} /* namespace */
extern "C" int r4d_rad_layout_conv1d_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, k;
const int rc = conv1d_geom(p, n_p, pl, n, &co, &ci, &k);
if (rc != RAD_OK) return rc;
fill(out, "r4d.conv1d.tap_major", RAD_BF16, co, k * ci, co * k * ci * 2);
return RAD_OK;
}
extern "C" int r4d_rad_relayout_conv1d_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_conv1d_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, k;
conv1d_geom(p, n_p, pl, n, &co, &ci, &k);
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 < k; ++t) d[(o * k + t) * ci + c] = s[(o * ci + c) * k + t];
return RAD_OK;
}
extern "C" int r4d_rad_unrelayout_conv1d_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_conv1d_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, k;
conv1d_geom(p, n_p, pl, n, &co, &ci, &k);
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 < k; ++t) d[(o * ci + c) * k + t] = s[(o * k + t) * ci + c];
return RAD_OK;
}
extern "C" int r4d_rad_layout_convt_phase(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, st, tp;
const int rc = convt_geom(p, n_p, pl, n, &co, &ci, &st, &tp);
if (rc != RAD_OK) return rc;
fill(out, "r4d.convt1d.phase_major", RAD_BF16, st * co, tp * ci, st * co * tp * ci * 2);
return RAD_OK;
}
extern "C" int r4d_rad_relayout_convt_phase(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_convt_phase(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, st, tp;
convt_geom(p, n_p, pl, n, &co, &ci, &st, &tp);
const uint16_t* s = (const uint16_t*)pl[0].data;
uint16_t* d = (uint16_t*)dst;
const long long K = tp * st;
for (long long r = 0; r < st; ++r)
for (long long o = 0; o < co; ++o)
for (long long t = 0; t < tp; ++t)
for (long long c = 0; c < ci; ++c)
d[((r * co + o) * tp + t) * ci + c] = s[(c * co + o) * K + r + t * st];
return RAD_OK;
}
extern "C" int r4d_rad_unrelayout_convt_phase(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_convt_phase(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, st, tp;
convt_geom(p, n_p, pl, n, &co, &ci, &st, &tp);
const uint16_t* s = (const uint16_t*)src;
uint16_t* d = (uint16_t*)pl[0].data;
const long long K = tp * st;
for (long long r = 0; r < st; ++r)
for (long long o = 0; o < co; ++o)
for (long long t = 0; t < tp; ++t)
for (long long c = 0; c < ci; ++c)
d[(c * co + o) * K + r + t * st] = s[((r * co + o) * tp + t) * ci + c];
return RAD_OK;
}
/* ---- the f32 rows of conv1d and conv_t1d (r4d_audio.hip's f32 implicit GEMMs), a vocoder kept
* in f32 throughout:
*
* conv1d PyTorch's Conv1d [cout][cin][k] stored [cout][k][cin], as bf16's
* conv_t1d PyTorch's ConvTranspose1d [cin][cout][k] stored [s][cout][taps][cin],
* taps = ceil(k / s): phase r's taps r, r + s, .. below k, the rest zeros, so any
* k of at least a stride is one [cout][taps cin] GEMM operand a phase
*/
namespace {
int conv1d_geom_f32(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout,
long long* cin, long long* k) {
*cout = r4d_pgeti_or(p, n_p, "cout", 0);
*cin = r4d_pgeti_or(p, n_p, "cin", 0);
*k = r4d_pgeti_or(p, n_p, "k", 0);
if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || *k <= 0) return RAD_E_SHAPE;
if (pl[0].dtype != RAD_F32 || rad_tensor_numel(&pl[0]) != *cout * *cin * *k) return RAD_E_SHAPE;
return RAD_OK;
}
int convt_geom_f32(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout,
long long* cin, long long* s, long long* k, long long* taps) {
*cout = r4d_pgeti_or(p, n_p, "cout", 0);
*cin = r4d_pgeti_or(p, n_p, "cin", 0);
*s = r4d_pgeti_or(p, n_p, "stride", 0);
*k = r4d_pgeti_or(p, n_p, "k", 2 * *s);
if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || *s <= 0 || *k < *s) return RAD_E_SHAPE;
*taps = (*k + *s - 1) / *s;
if (pl[0].dtype != RAD_F32 || rad_tensor_numel(&pl[0]) != *cin * *cout * *k)
return RAD_E_SHAPE;
return RAD_OK;
}
} /* namespace */
extern "C" int r4d_rad_layout_conv1d_tap_f32(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, k;
const int rc = conv1d_geom_f32(p, n_p, pl, n, &co, &ci, &k);
if (rc != RAD_OK) return rc;
fill(out, "r4d.conv1d.tap_major.f32", RAD_F32, co, k * ci, co * k * ci * 4);
return RAD_OK;
}
extern "C" int r4d_rad_relayout_conv1d_tap_f32(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_conv1d_tap_f32(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, k;
conv1d_geom_f32(p, n_p, pl, n, &co, &ci, &k);
const float* s = (const float*)pl[0].data;
float* d = (float*)dst;
for (long long o = 0; o < co; ++o)
for (long long c = 0; c < ci; ++c)
for (long long t = 0; t < k; ++t) d[(o * k + t) * ci + c] = s[(o * ci + c) * k + t];
return RAD_OK;
}
extern "C" int r4d_rad_unrelayout_conv1d_tap_f32(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_conv1d_tap_f32(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, k;
conv1d_geom_f32(p, n_p, pl, n, &co, &ci, &k);
const float* s = (const float*)src;
float* d = (float*)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 < k; ++t) d[(o * ci + c) * k + t] = s[(o * k + t) * ci + c];
return RAD_OK;
}
extern "C" int r4d_rad_layout_convt_phase_f32(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, st, k, tp;
const int rc = convt_geom_f32(p, n_p, pl, n, &co, &ci, &st, &k, &tp);
if (rc != RAD_OK) return rc;
fill(out, "r4d.convt1d.phase_major.f32", RAD_F32, st * co, tp * ci, st * co * tp * ci * 4);
return RAD_OK;
}
extern "C" int r4d_rad_relayout_convt_phase_f32(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_convt_phase_f32(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, st, k, tp;
convt_geom_f32(p, n_p, pl, n, &co, &ci, &st, &k, &tp);
const float* s = (const float*)pl[0].data;
float* d = (float*)dst;
for (long long r = 0; r < st; ++r)
for (long long o = 0; o < co; ++o)
for (long long t = 0; t < tp; ++t)
for (long long c = 0; c < ci; ++c) {
const long long tap = r + t * st;
d[((r * co + o) * tp + t) * ci + c] = tap < k ? s[(c * co + o) * k + tap] : 0.0f;
}
return RAD_OK;
}
extern "C" int r4d_rad_unrelayout_convt_phase_f32(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_convt_phase_f32(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, st, k, tp;
convt_geom_f32(p, n_p, pl, n, &co, &ci, &st, &k, &tp);
const float* s = (const float*)src;
float* d = (float*)pl[0].data;
for (long long r = 0; r < st; ++r)
for (long long o = 0; o < co; ++o)
for (long long t = 0; t < tp; ++t)
for (long long c = 0; c < ci; ++c) {
const long long tap = r + t * st;
if (tap < k) d[(c * co + o) * k + tap] = s[((r * co + o) * tp + t) * ci + c];
}
return RAD_OK;
}
+61 -79
View File
@@ -5,62 +5,45 @@
*
* The core issues the pair right after a targeted trunk GEMM, in the GEMM's own row slice, with
* `a`/`a_scale` the GEMM's activation operands and `y` its output (docs/OPS.md). A row whose slot
* is outside [0, S) is a BASE row and both kernels leave it before touching anything: shrink
* writes no `t`, expand neither reads nor writes `y` -- `y + 0` would already turn a -0 into +0,
* and the engine's promise is that a base row is bit for bit what the GEMM wrote.
* is outside [0, S) is a base row and both kernels leave it before touching anything: shrink
* writes no `t`, expand neither reads nor writes `y` (`y + 0` would turn -0 into +0), so a base
* row stays bit for bit what the GEMM wrote.
*
* V1, SCALAR f32 AND CORRECT FIRST. The adapter term is a rank-R correction (R <= 64 a module)
* next to an N x K GEMM, so it is small whatever it costs per FLOP; the WMMA form -- a 16-row tile
* per distinct slot, other slots' rows masked out of the fragment -- is a later speed pass. What
* this form already guarantees, and the later one must keep:
* Invariants every row here keeps:
* - No split that moves with M: a row's arithmetic does not depend on the batch it arrives in,
* so a request alone and the same request in a mixed batch get the same bytes.
* - The grid is M and the declared parameters. Which adapters are active is read on the device
* from `slot` and the pools, so a recorded pass replays the same packets whatever they hold.
* - x(m, k) is gemm_nt_q's activation value: a code times its group's scale (one f32 product),
* or a bf16/f16/f32 element as it stands, the scale stream's grid read as libref's make_scales
* reads it. The decodes below are the ABI's conversions (rad_plugin.h) restated for the device
* bit for bit; gfx1201 has no bf16 convert, so the narrowing is the ABI's RTNE with its
* quiet-NaN rule. Every multiply-add rounds twice (-ffp-contract=off, RadAddPlugin.cmake).
*
* * NO SPLIT THAT MOVES WITH M. A row's shrink is one wave per column j, lane l summing the k
* that are l mod 32 in ascending order, then a fixed xor butterfly; expand is one thread per
* (m, n) summing j ascending. Neither depends on the batch a row arrives in, which is what
* lets the engine claim "a request alone == the same request in a mixed batch" for the LoRA
* term.
* * THE GRID IS M AND THE DECLARED PARAMETERS. Which adapters are active is read on the device,
* from `slot` and the pools, so a recorded pass replays the same packets whatever the slots
* hold.
* * NO HOST READS, NO SCRATCH, NO LDS: the reduction is cross-lane only, so a block never waits
* on another wave and a base row leaves before any cross-lane op.
* The scalar rows (lora_shrink_scalar, lora_expand_scalar): shrink is one block a row, one wave a
* column j, lane l summing the k that are l mod 32 in ascending order, then a fixed xor butterfly;
* expand is one thread an (m, n), j ascending, so its bytes are libref's. No scratch and no LDS. They
* serve every dtype, and are the only rows for f16 and f32 activations.
*
* x(m, k) IS gemm_nt_q's ACTIVATION VALUE: a code times its group's scale (one f32 product), or a
* bf16/f16/f32 element as it stands, with the scale stream's grid read the way libref's
* make_scales reads it. The decodes below are the ABI's conversions (rad_plugin.h) restated for
* the device, bit for bit, so a code decodes here exactly as it does in the oracle. gfx1201 has no
* bf16 convert; the narrowing is the ABI's RTNE with its quiet-NaN rule. Every multiply-add rounds
* twice (-ffp-contract=off, RadAddPlugin.cmake), so expand computes libref's bytes and shrink
* differs from them only by its summation order.
*
* V2, THE TILED ROWS (lora_shrink_wmma, lora_shrink_wmma_q, lora_expand_tiled), below the v1
* kernels. v1's grid is a ROW: shrink is one block a row walking K serially, expand one block a
* (row, 256 columns) re-reading all of B[s] for every row, and a chunk of base rows still launches
* M * ceil(N/256) blocks that read a slot and leave. On the card that is a prefill at a third of
* the base speed and base requests 7-8 % slower. The tiled rows keep every promise above and
* change only who computes what:
*
* * THE GRID'S UNIT IS A ROW TILE (16 rows shrink, 32 expand). Every wave reads the tile's slots
* and a ballot decides; a tile of base rows leaves before any barrier or operand load, so a
* base step costs one small block a tile. A tile holding rows of several adapters runs ONE
* PASS PER DISTINCT SLOT, ascending, each pass with its own slot's pools; a row's value comes
* out of its own slot's pass alone and other rows' results are never stored. The passes of a
* tile may be spread over blockIdx.z when the grid is small (decode with several adapters);
* that decides which block runs a pass, never the pass's arithmetic.
* * SHRINK IS WMMA bf16 (16 x 16 x 16), with the pool fragment as the A operand and the x
* fragment as B, so a lane's accumulator is one row. Its order is fixed by K and R alone: K
* in 32-wide steps, a block's run of steps split over its 4 waves (wave w takes every 4th),
* the waves summed 0..3 in LDS, and -- for a K long enough that one tile would leave the card
* idle at decode -- the run split over KS blocks whose f32 partials the LAST to arrive sums
* 0..KS-1 (sh_plan). bf16 activations feed the WMMA as they are; fp8 and i8 codes are exact
* in bf16 and feed it as codes, and each step's partial is scaled by its group's f32 scale,
* which needs the group to be whole steps (a multiple of 32, or one group across K) and is
* otherwise the v1 kernel. Every one of those roundings is a sum or product of the terms the
* contract names, so the result is inside v1's (K + 2) 2^-24 sum|terms| bound; no code times
* scale is ever rounded on its own. f16 and f32 activations have no exact WMMA and stay v1.
* * EXPAND IS v1's ARITHMETIC IN A TILE. B[s]'s [128 columns, 32 j] slab is staged in LDS as f32
* (exact) and reused by the tile's 32 rows; each output keeps v1's sequence (acc = 0, j
* ascending acc = acc + t*B, d = scale*acc, one rounding into y), so its bytes are libref's.
* The tiled rows (lora_shrink_wmma, lora_shrink_wmma_q, lora_expand_tiled), preferred:
* - The grid's unit is a row tile (16 rows shrink, 32 expand). Every wave reads the tile's slots
* and a ballot decides; a tile of base rows leaves before any barrier or operand load. A tile
* holding rows of several adapters runs one pass per distinct slot, ascending, each with its
* own slot's pools; a row's value comes from its own slot's pass alone. The passes may be
* spread over blockIdx.z when the grid is small, which decides which block runs a pass, never
* its arithmetic.
* - Shrink is WMMA bf16 (16 x 16 x 16) with the pool fragment as the A operand and x as B, so a
* lane's accumulator is one row. Its order is fixed by K and R alone: K in 32-wide steps, a
* block's steps split over its 4 waves (wave w takes every 4th), the waves summed 0..3 in LDS,
* and for a long K the steps split over KS blocks whose f32 partials the last to arrive sums
* 0..KS-1 (sh_plan). fp8 and i8 codes are exact in bf16 and feed the WMMA as codes; each step's
* partial is scaled by its group's f32 scale, which needs the group to be whole steps (a
* multiple of 32, or one group across K). Every rounding is a sum or product of the contract's
* terms, so the result is inside the scalar row's (K + 2) 2^-24 sum|terms| bound.
* - Expand is the scalar arithmetic in a tile: B[s]'s [128 columns, 32 j] slab is staged in LDS
* as f32 (exact) and reused by the tile's 32 rows; each output keeps the scalar sequence (acc =
* 0, j ascending acc = acc + t*B, d = scale*acc, one rounding into y), so its bytes are
* libref's.
*
* Kernels are written against r4d_launch.h so tests/r4d_emu runs this source on the host.
*/
@@ -248,7 +231,7 @@ __global__ __launch_bounds__(256) void lora_expand_kernel(ExpandArgs A) {
}
}
/* ================================================================ v2: the tiled rows */
/* ================================================================ the tiled rows */
typedef short lr_v8s __attribute__((ext_vector_type(8))); /* 8 bf16, as the WMMA takes them */
typedef float lr_v8f __attribute__((ext_vector_type(8)));
@@ -368,7 +351,7 @@ __device__ __forceinline__ lr_v8f wmma_bf16(lr_v8s a, lr_v8s b, lr_v8f c) {
return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c);
}
/* SHRINK, one block a (j tile x K split, row tile, z), 4 waves. The pool fragment is the WMMA's A
/* Shrink, one block a (j tile x K split, row tile, z), 4 waves. The pool fragment is the WMMA's A
* operand (16 j x 16 k) and the x fragment its B (16 k x 16 rows), so lane l's eight outputs are
* row l % 16 at j = 8 (l / 16) .. +7: one row, one group scale a lane. A lane holds 16 contiguous
* k of its row in both operands, the first 8 in the step's first WMMA and the next 8 in its
@@ -464,9 +447,9 @@ __global__ __launch_bounds__(kShThreads) void lora_shrink_wmma_kernel(ShrinkTArg
}
if (T.ks == 1) return;
/* THE K SPLIT'S SUM, in the last block to arrive. Every thread's partial stores are fenced
* before the arrival, and the counter is left zero for the next launch (they are ordered: the
* lora rows are not concurrent, and each lane's `t` keys its own counter block). */
/* The K split's sum, in the last block to arrive. Every thread's partial stores are fenced
* before the arrival, and the counter is left zero for the next launch (launches are ordered:
* the lora rows are not concurrent, and each lane's `t` keys its own counter block). */
__threadfence();
__syncthreads();
const int cidx = ((int)blockIdx.y * T.jt + jt) * kZMax + z;
@@ -491,10 +474,10 @@ __global__ __launch_bounds__(kShThreads) void lora_shrink_wmma_kernel(ShrinkTArg
}
}
/* EXPAND, one block a (128 columns, 32 rows, z), 8 waves: wave w owns rows 4w..4w+3 and lane l
/* Expand, one block a (128 columns, 32 rows, z), 8 waves: wave w owns rows 4w..4w+3 and lane l
* columns 4l..4l+3, sixteen outputs a thread. B[s]'s slab [128 columns][32 j] is staged as f32
* (a bf16 widens exactly) and t's [32 rows][32 j] beside it; then every output runs v1's sequence
* over the slab and the next, so the bytes are v1's and libref's. A pass's accumulators start at
* (a bf16 widens exactly) and t's [32 rows][32 j] beside it; every output runs the scalar row's
* sequence over the slab and the next, so the bytes are libref's. A pass's accumulators start at
* zero and only its own rows are written back: a row of another slot accumulates against zeros it
* never stores. V: B is dense, 16-byte aligned and R a multiple of 8, so 16-byte loads. */
template <int YDT, bool V>
@@ -667,8 +650,8 @@ static bool dtype_agrees(const RadArgs* a, uint32_t dt) {
return !d || rad_dtype_parse(d) == dt;
}
/* The launches, one per dtype instantiation: the v1 grid is M blocks for shrink and M strips of
* 256 columns for expand, 256 threads each, whatever the slots hold. */
/* The scalar rows' launches, one per dtype instantiation: M blocks for shrink and M strips of 256
* columns for expand, 256 threads each, whatever the slots hold. */
template <int ADT>
static void launch_shrink(const ShrinkArgs& P, int64_t blocks, RadStream stream) {
(void)stream; /* the host emulator's launch takes none */
@@ -819,12 +802,11 @@ static int shrink_scalar(const ShrinkArgs& P, int adt, int64_t M, RadStream stre
/* ---------------------------------------------------------------- the tiled rows' plans (host) */
/* THE SHRINK SPLIT, from K and R alone -- never M, because it is the summation order. A row tile
/* The shrink split, from K and R alone and never M, because it is the summation order. A row tile
* covers ceil(R / 16) j tiles; at decode that tile is the whole grid, so K is split until j tiles
* times splits reach kShFill blocks, but never below 16 steps (512 k) a block, past which the
* split's partial traffic and its arrival outweigh what the extra blocks read. The split is then
* rounded so no block is left without a step. MiniCPM5-2B's four sites at TP1, for scale: K 2048
* R 48 -> 3 x 4 blocks; K 2048 R 32 -> 2 x 4; K 2048 R 16 -> 1 x 4; K 6144 R 16 -> 1 x 12. */
* partials' traffic and the arrival outweigh what the extra blocks read. The split is rounded so
* no block is left without a step. E.g. K 2048 R 48 -> 3 x 4 blocks; K 6144 R 16 -> 1 x 12. */
struct ShPlan { int jt, ks, spb, nsteps; };
static ShPlan sh_plan(int64_t K, int64_t R) {
ShPlan p;
@@ -842,11 +824,11 @@ static int64_t sh_part_bytes(int64_t M, int64_t R, const ShPlan& p) {
return p.ks > 1 ? (int64_t)p.ks * M * R * (int64_t)sizeof(float) : 0;
}
/* HOW MANY BLOCKS ONE TILE'S PASSES SPREAD OVER. Decode with several adapters is a handful of
* blocks a pass, run one after another inside a block they would add up; spread over blockIdx.z
* they run at once. Only while the grid is small -- every z block of a tile that has fewer passes
* leaves after reading the slots, and on a prefill grid those would be thousands -- and never more
* than the passes a tile can have. Which block runs a pass is all this decides. */
/* How many blocks one tile's passes spread over. Decode with several adapters is a handful of
* blocks a pass; run one after another inside a block they would add up, spread over blockIdx.z
* they run at once. Only while the grid is small (every z block of a tile with fewer passes leaves
* after reading the slots, and a prefill grid would have thousands), and never more than the
* passes a tile can have. Which block runs a pass is all this decides. */
static int z_fan(int64_t base, int64_t S, int64_t M, int64_t tile) {
int64_t z = base >= kZGrid ? 1 : kZGrid / base;
if (z > S) z = S;
@@ -856,12 +838,12 @@ static int z_fan(int64_t base, int64_t S, int64_t M, int64_t tile) {
return z < 1 ? 1 : (int)z;
}
/* THE SPLIT'S ARRIVAL COUNTERS, one block a (device, `t`). They cannot live in the scratch: other
/* The split's arrival counters, one block a (device, `t`). They cannot live in the scratch: other
* ops write the arena between two of ours and the counters must be zero at entry. Each lane's `t`
* is its own buffer and the lora rows are ordered on their lane (not concurrent), so two launches
* that could overlap never share a block; the reducer leaves every counter zero. A block too
* small for a launch is replaced by a larger one and the old one is kept -- a recorded pass may
* still name it, and its own launches still fit it. */
* that could overlap never share a block; the reducer leaves every counter zero. A block too small
* for a launch is replaced by a larger one and the old one is kept, since a recorded pass may
* still name it. */
static unsigned* shrink_ctr(const void* t, int64_t n, RadStream stream) {
static std::mutex mu;
static std::map<std::pair<int, const void*>, std::pair<unsigned*, int64_t>> blocks;
@@ -936,8 +918,8 @@ int r4d_rad_lora_expand(const RadArgs* a, RadStream stream) {
}
/* The tiled shrink: lora_shrink_wmma (bf16 a) and lora_shrink_wmma_q (fp8 / i8 codes whose group
* is whole 32-wide steps) share this entry point. What the WMMA cannot hold exactly -- f16 and f32
* activations, a scale group that ends inside a step -- goes to the v1 kernel, decided by the
* is whole 32-wide steps) share this entry point. What the WMMA cannot hold exactly (f16 and f32
* activations, a scale group that ends inside a step) goes to the scalar kernel, decided by the
* dtype and the stream's grid and never by M; the rows' bands do not send either here, and a
* direct caller still gets the exact answer. */
int r4d_rad_lora_shrink_wmma(const RadArgs* a, RadStream stream) {
@@ -982,7 +964,7 @@ int r4d_rad_lora_shrink_wmma(const RadArgs* a, RadStream stream) {
}
/* The K split's partials, sized at declare for the band's widest M (the core calls this with it).
* f16 / f32 activations run the v1 kernel and need none. */
* f16 / f32 activations run the scalar kernel and need none. */
int64_t r4d_rad_lora_shrink_wmma_scratch(const RadArgs* a) {
using namespace r4d_lora;
const int64_t M = rad_args_geti_or(a, "M", 0), K = rad_args_geti_or(a, "K", 0);
+163 -22
View File
@@ -29,6 +29,8 @@
#include "rad_yarn.h"
#include "r4d_fp8_wmma.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
@@ -198,22 +200,28 @@ __global__ __launch_bounds__(kThreads) void scatter_rows_u8_kernel(
//
// Two passes over the row: n is 256 (a QK-norm head) or 5120 (the hidden state), so the row is in
// L1 for the second pass, and one-pass Welford would only change the rounding.
template <bool WF32, uint32_t THR>
//
// `TX` is the row's element: bf16, or f32 for a residual stream kept in f32 (a video decoder's),
// read as it is; the output is bf16 either way.
__device__ __forceinline__ float act_f32(uint16_t v) { return bf16_to_f32(v); }
__device__ __forceinline__ float act_f32(float v) { return v; }
template <bool WF32, uint32_t THR, typename TX = uint16_t>
__global__ __launch_bounds__(THR) void rmsnorm_kernel(
const uint16_t* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y,
const TX* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y,
uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld) {
__shared__ float lds[THR / kWave];
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
const TX* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = bf16_to_f32(xr[i]); ss += v * v; }
for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = act_f32(xr[i]); ss += v * v; }
ss = block_sum<THR / kWave>(ss, lds);
const float s = rsqrtf(ss / (float)n + eps);
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf16_to_f32(((const uint16_t*)w)[i]);
yr[i] = f32_to_bf16(bf16_to_f32(xr[i]) * s * (g + wadd) * mult);
yr[i] = f32_to_bf16(act_f32(xr[i]) * s * (g + wadd) * mult);
}
}
@@ -239,17 +247,67 @@ __global__ __launch_bounds__(kThreads) void rmsnorm_p_kernel(
// ---------------------------------------------------------------------------- add / mul
// ref_add / ref_mul with one broadcast rule: an operand of exactly n elements against an output of
// rows*n broadcasts along rows; nothing else broadcasts, so shape bugs are not hidden.
// `b_step` 0 reads one element per row; with b_ld 0 too, a scalar for the whole op.
// `b_step` 0 reads one element per row; with b_ld 0 too, a scalar for the whole op. `div` (add
// only) divides the sum after its rounding and rounds again, the last step of a mean summed
// pairwise; 1 is the plain sum.
__global__ __launch_bounds__(kThreads) void binary_kernel(
const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, uint16_t* __restrict__ y,
uint32_t n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul, uint32_t b_step) {
uint32_t n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul, uint32_t b_step,
float div) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ ar = a + (size_t)m * a_ld;
const uint16_t* __restrict__ br = b + (size_t)m * b_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) {
const float u = bf16_to_f32(ar[i]), v = bf16_to_f32(br[i * b_step]);
yr[i] = f32_to_bf16(mul ? u * v : u + v);
float r = mul ? u * v : u + v;
if (div != 1.0f) r = bf16_to_f32(f32_to_bf16(r)) / div;
yr[i] = f32_to_bf16(r);
}
}
// The f32 form (a video decoder's residual stream, a vocoder's branch mean), with the same
// broadcast rule and `div`. Flat over the M x n extent: a vocoder's last stages are a few channels
// over a million rows, which a workgroup a row would leave mostly idle. `y` may be `a` (an
// in-place residual): each element is read before it is written, by the same thread.
__global__ __launch_bounds__(kThreads) void binary_f32_kernel(
const float* __restrict__ a, const float* __restrict__ b, float* y, uint32_t n,
uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul, uint32_t b_step, float div,
uint64_t total) {
for (uint64_t t = (uint64_t)blockIdx.x * kThreads + threadIdx.x; t < total;
t += (uint64_t)gridDim.x * kThreads) {
const uint64_t m = t / n;
const uint32_t i = (uint32_t)(t - m * n);
const float u = a[m * a_ld + i], v = b[m * b_ld + (size_t)i * b_step];
float r = mul ? u * v : u + v;
if (div != 1.0f) r = r / div;
y[m * y_ld + i] = r;
}
}
// ref_mul_weight over an f32 weight (a layer scale kept f32): y = x * w, one row of n elements
// broadcast down the rows, or with `w_step` 0 one element for the whole op.
__global__ __launch_bounds__(kThreads) void mul_wf32_kernel(
const uint16_t* __restrict__ x, const float* __restrict__ w, uint16_t* __restrict__ y,
uint32_t n, uint32_t x_ld, uint32_t y_ld, uint32_t w_step) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
yr[i] = f32_to_bf16(bf16_to_f32(xr[i]) * w[i * w_step]);
}
// ref_mul_weight into an f32 output (a layer scale on a branch about to join an f32 residual):
// x bf16 or f32, the weight bf16 or f32, the product rounded once to f32. Flat, as the f32 binary.
template <typename TX, typename TW>
__global__ __launch_bounds__(kThreads) void mul_weight_f32_kernel(
const TX* __restrict__ x, const TW* __restrict__ w, float* __restrict__ y, uint32_t n,
uint32_t x_ld, uint32_t y_ld, uint32_t w_step, uint64_t total) {
for (uint64_t t = (uint64_t)blockIdx.x * kThreads + threadIdx.x; t < total;
t += (uint64_t)gridDim.x * kThreads) {
const uint64_t m = t / n;
const uint32_t i = (uint32_t)(t - m * n);
y[m * y_ld + i] = act_f32(x[m * x_ld + i]) * act_f32(w[(size_t)i * w_step]);
}
}
@@ -400,7 +458,7 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos,
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, uint32_t nfreq, int den, int gptj,
float theta, float rscale, uint32_t row_pitch,
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn) {
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn, RadLlama3 l3) {
const uint32_t m = blockIdx.x;
const uint32_t half = rot / 2;
const float div = rscale != 0.0f ? rscale : 1.0f;
@@ -421,6 +479,7 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
inv = 1.0f / powf(theta, (float)(2 * j) / (float)(2 * sec[c]));
}
inv = yarn.frequency(inv, (int)i);
inv = l3.frequency(inv);
/* The proportional ladder rotates the whole head with every frequency past nfreq zero
* (HF's _compute_proportional_rope_parameters): pair i is (i, i + head_dim/2), and pairs
* past nfreq turn by 0 (cos 1, sin 0), returning the value exactly. */
@@ -679,7 +738,7 @@ extern "C" int r4d_binary_bf16(long a, long b, long y, int M, int n, int op,
if (b_ld < 0) b_ld = 0;
hipLaunchKernelGGL(binary_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)a, (const uint16_t*)b, (uint16_t*)y, (uint32_t)n,
(uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, op, b_step);
(uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, op, b_step, 1.0f);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -799,12 +858,13 @@ extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope
}
// The single launch of rope_kernel. `yarn` with factor 0 is the plain rotary (the YaRN blend
// returns the frequency unchanged and no magnitude is applied). `den` is the ladder width (`rot`
// returns the frequency unchanged and no magnitude is applied), and so is `l3` with factor 0 (Llama
// 3's scaling, after YaRN's, which no caller combines with it). `den` is the ladder width (`rot`
// for `rotary`, `head_dim` for `head`); the plain entry passes `rot`.
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den,
int gptj, float theta, float rscale, int row_pitch, int mode,
const int* sec, int n_sec, int plane, RadYarn yarn, long stream,
int nfreq = -1) {
int nfreq = -1, RadLlama3 l3 = RadLlama3{}) {
if (!qkv || !pos) return -1;
if (M <= 0 || head_dim <= 0 || n_rope_heads <= 0) return -2;
if (rot <= 0 || rot > head_dim || (rot & 1)) return -3;
@@ -818,7 +878,7 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads
(uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim,
(uint32_t)n_rope_heads, (uint32_t)rot, (uint32_t)nfreq, (int)den, gptj, theta,
rscale,
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn);
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn, l3);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -1187,16 +1247,39 @@ extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) {
enum { RN_X = 0, RN_W, RN_Y };
/* The norm over f32 rows into bf16 (a video decoder's f32 residual stream), at the bf16 form's
* width so the two fold a row's sum of squares alike. */
static int rmsnorm_x_f32(const float* x, const void* w, uint16_t* y, int M, int n, float eps,
float wadd, float mult, int w_f32, int x_ld, int y_ld, RadStream stream) {
const int thr = r4d_act_threads(M, n);
#define R4D_RNF_T(wf, T) \
hipLaunchKernelGGL((rmsnorm_kernel<wf, T, float>), dim3((uint32_t)M), dim3(T), 0, \
(hipStream_t)stream, x, w, y, (uint32_t)n, eps, wadd, mult, \
(uint32_t)x_ld, (uint32_t)y_ld)
#define R4D_RNF(wf) \
do { if (thr == 1024) R4D_RNF_T(wf, 1024); \
else if (thr == 512) R4D_RNF_T(wf, 512); \
else R4D_RNF_T(wf, 256); } while (0)
if (w_f32) R4D_RNF(true);
else R4D_RNF(false);
#undef R4D_RNF
#undef R4D_RNF_T
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, RN_X);
const RadTensor* w = r4d_opt(a, RN_W);
const RadTensor* y = r4d_opt(a, RN_Y);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(x));
/* The row bf16, or f32 (read as it is); the output bf16. */
if (x->dtype != RAD_BF16 && x->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
R4D_NEED(dt_bf16(y));
const bool x_f32 = x->dtype == RAD_F32;
/* An absent gain is one (Gemma 4's value norm, its multimodal embedder's pre-projection norm).
* `wadd` without a gain is refused. */
if (!w) {
if (x_f32) return R4D_NO(RAD_E_DTYPE);
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);
if (r4d_getf(a, "wadd", 0.0) != 0.0) return R4D_NO(RAD_E_INVAL);
@@ -1226,6 +1309,10 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
if (x_f32)
return rmsnorm_x_f32((const float*)x->data, w->data, (uint16_t*)y->data, (int)M, (int)n,
eps, wadd, (float)r4d_getf(a, "mult", 1.0), w_f32, (int)x_ld,
(int)y_ld, s);
return r4d_rmsnorm_mult_bf16(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd,
(float)r4d_getf(a, "mult", 1.0),
w_f32, (int)x_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK
@@ -1259,14 +1346,19 @@ extern "C" int r4d_rad_rmsnorm_p(const RadArgs* a, RadStream s) {
enum { BI_A = 0, BI_B, BI_Y };
/* Both rows of each op share this: every operand bf16, or (add_f32) every operand f32. */
static int binary(const RadArgs* a, int mul, RadStream s) {
const RadTensor* A = r4d_opt(a, BI_A);
const RadTensor* B = r4d_opt(a, BI_B);
const RadTensor* Y = r4d_opt(a, BI_Y);
if (!A || !B || !Y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(A));
R4D_NEED(dt_bf16(B));
R4D_NEED(dt_bf16(Y));
const bool f32 = Y->dtype == RAD_F32;
const uint32_t dt = f32 ? (uint32_t)RAD_F32 : (uint32_t)RAD_BF16;
if (A->dtype != dt || B->dtype != dt || Y->dtype != dt) return R4D_NO(RAD_E_DTYPE);
/* `div` is add's alone (mul's schema has none); 0 and non-finite values are refused, as libref
* refuses them. */
const double div = mul ? 1.0 : r4d_getf(a, "div", 1.0);
if (!(div != 0.0) || !std::isfinite(div)) return R4D_NO(RAD_E_INVAL);
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);
@@ -1289,6 +1381,22 @@ static int binary(const RadArgs* a, int mul, RadStream s) {
if (b_ld == 0) return R4D_NO(RAD_E_STRIDE); /* 0 means broadcast; a real pitch cannot be 0 */
}
if (f32) {
const uint64_t total = (uint64_t)M * (uint64_t)n;
const uint64_t blocks = std::min<uint64_t>((total + kThreads - 1) / kThreads, 65536u);
hipLaunchKernelGGL(binary_f32_kernel, dim3((uint32_t)blocks), dim3(kThreads), 0,
(hipStream_t)s, (const float*)A->data, (const float*)B->data,
(float*)Y->data, (uint32_t)n, (uint32_t)a_ld, (uint32_t)b_ld,
(uint32_t)y_ld, mul, 1u, (float)div, total);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
if (div != 1.0) {
hipLaunchKernelGGL(binary_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)s,
(const uint16_t*)A->data, (const uint16_t*)B->data, (uint16_t*)Y->data,
(uint32_t)n, (uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, mul, 1u,
(float)div);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
return r4d_binary_bf16(r4d_addr(A), r4d_addr(B), r4d_addr(Y), (int)M, (int)n, mul,
(int)a_ld, (int)b_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
@@ -1298,15 +1406,19 @@ extern "C" int r4d_rad_add(const RadArgs* a, RadStream s) { return binary(a, 0,
extern "C" int r4d_rad_mul(const RadArgs* a, RadStream s) { return binary(a, 1, s); }
/* mul_weight: y = x * w, `w` a bf16 weight of one element (pitch -1, a scalar) or one row (pitch
* 0, broadcast down the rows). */
* 0, broadcast down the rows). The f32 row (mul_weight_f32) writes an f32 `y` from a bf16 or f32
* `x`; the bf16 row a bf16 `y` from a bf16 `x`. */
extern "C" int r4d_rad_mul_weight(const RadArgs* a, RadStream s) {
const RadTensor* X = r4d_opt(a, 0);
const RadTensor* W = r4d_opt(a, 1);
const RadTensor* Y = r4d_opt(a, 2);
if (!X || !W || !Y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(X));
R4D_NEED(dt_bf16(W));
R4D_NEED(dt_bf16(Y));
const bool y_f32 = Y->dtype == RAD_F32;
if (y_f32 ? (X->dtype != RAD_BF16 && X->dtype != RAD_F32) : X->dtype != RAD_BF16)
return R4D_NO(RAD_E_DTYPE);
/* The weight bf16 or f32 (a layer scale a model keeps f32; libref reads either). */
if (W->dtype != RAD_BF16 && W->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
if (!y_f32 && Y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
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;
@@ -1318,6 +1430,29 @@ extern "C" int r4d_rad_mul_weight(const RadArgs* a, RadStream s) {
if (r4d_numel(W) == 1) w_ld = -1;
else if (r4d_numel(W) == n && r4d_contig(W)) w_ld = 0;
else return R4D_NO(RAD_E_SHAPE);
if (y_f32) {
const uint64_t total = (uint64_t)M * (uint64_t)n;
const dim3 grid((uint32_t)std::min<uint64_t>((total + kThreads - 1) / kThreads, 65536u));
const uint32_t ws = w_ld < 0 ? 0u : 1u;
const bool xf = X->dtype == RAD_F32, wf = W->dtype == RAD_F32;
#define R4D_MWF(TX, TW) \
hipLaunchKernelGGL((mul_weight_f32_kernel<TX, TW>), grid, dim3(kThreads), 0, \
(hipStream_t)s, (const TX*)X->data, (const TW*)W->data, \
(float*)Y->data, (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld, ws, \
total)
if (xf && wf) R4D_MWF(float, float);
else if (xf) R4D_MWF(float, uint16_t);
else if (wf) R4D_MWF(uint16_t, float);
else R4D_MWF(uint16_t, uint16_t);
#undef R4D_MWF
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
if (W->dtype == RAD_F32) {
hipLaunchKernelGGL(mul_wf32_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)s,
(const uint16_t*)X->data, (const float*)W->data, (uint16_t*)Y->data,
(uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld, w_ld < 0 ? 0u : 1u);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
return r4d_binary_bf16(r4d_addr(X), r4d_addr(W), r4d_addr(Y), (int)M, (int)n, 1,
(int)x_ld, (int)w_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
@@ -1546,13 +1681,19 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
if (!rad_yarn_valid(yarn)) return R4D_NO(RAD_E_INVAL);
/* No model uses YaRN with the axial vision rotary or a linear position divide. */
if (yarn.factor != 0.0f && (mc == 4 || rscale != 1.0f)) return R4D_NO(RAD_E_UNSUPPORTED);
/* Llama 3's scaling: one-component positions only, and never beside YaRN (libref refuses
* both alike). */
const RadLlama3 l3 = rad_llama3_args(a);
if (!rad_llama3_valid(l3) || (l3.factor != 0.0f && yarn.factor != 0.0f))
return R4D_NO(RAD_E_INVAL);
if (l3.factor != 0.0f && (mc == 4 || multi)) return R4D_NO(RAD_E_UNSUPPORTED);
/* The Q and K heads rotate; the trailing V heads do not. */
long long rot_l = rot, nfreq = rot / 2;
if (den == head_dim && rot < head_dim && !multi && !gptj && mc == 0) rot_l = head_dim;
return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
(int)(n_head + n_head_kv), (int)rot_l, (int)den, gptj, theta, rscale,
(int)pitch, mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s,
(int)nfreq) == 0
(int)nfreq, l3) == 0
? RAD_OK
: RAD_E_DEVICE;
}
+74 -3
View File
@@ -135,9 +135,9 @@ int r4d_rad_norm_add_norm_bf16 (const RadArgs*, RadStream);
int r4d_rad_norm_add_norm_route_bf16(const RadArgs*, RadStream);
int r4d_rad_join_add_scale_bf16 (const RadArgs*, RadStream);
int r4d_rad_expert_scale_bf16 (const RadArgs*, RadStream);
/* Runtime LoRA's two halves, each row's adapter named by its slot (r4d_lora_bf16.hip): the v1
* scalar rows, and the tiled rows -- WMMA shrink over row tiles with a K split fixed by K and R
* (its partials in the op's scratch), and an expand that stages B[s] in LDS for a tile of rows. */
/* Runtime LoRA's two halves, each row's adapter named by its slot (r4d_lora_bf16.hip): the scalar
* rows, and the tiled rows (a WMMA shrink over row tiles with a K split fixed by K and R, its
* partials in the op's scratch, and an expand that stages B[s] in LDS for a tile of rows). */
int r4d_rad_lora_shrink (const RadArgs*, RadStream);
int r4d_rad_lora_expand (const RadArgs*, RadStream);
int r4d_rad_lora_shrink_wmma (const RadArgs*, RadStream);
@@ -170,6 +170,43 @@ int r4d_rad_s2d_avg_add (const RadArgs*, RadStream);
int r4d_rad_to_rgba8 (const RadArgs*, RadStream);
int r4d_rad_gelu_tanh (const RadArgs*, RadStream);
int r4d_rad_scatter_add_rows (const RadArgs*, RadStream);
/* r4d_audio.hip */
int r4d_rad_conv1d (const RadArgs*, RadStream);
int r4d_rad_conv_t1d (const RadArgs*, RadStream);
int r4d_rad_conv1d_f32 (const RadArgs*, RadStream);
int r4d_rad_conv_t1d_f32 (const RadArgs*, RadStream);
int r4d_rad_snake (const RadArgs*, RadStream);
int r4d_rad_cfg_topk_sample (const RadArgs*, RadStream);
int r4d_rad_rvq_embed (const RadArgs*, RadStream);
int r4d_rad_frame_mix_store (const RadArgs*, RadStream);
int r4d_rad_end_status (const RadArgs*, RadStream);
int r4d_rad_frame_store (const RadArgs*, RadStream);
int r4d_rad_resample_nearest (const RadArgs*, RadStream);
int r4d_rad_fourier_embed (const RadArgs*, RadStream);
int r4d_rad_win_input (const RadArgs*, RadStream);
int r4d_rad_win_prep (const RadArgs*, RadStream);
int r4d_rad_win_finish (const RadArgs*, RadStream);
int r4d_rad_chan_split (const RadArgs*, RadStream);
int r4d_rad_interleave2 (const RadArgs*, RadStream);
int r4d_rad_attn_dense_small_h256 (const RadArgs*, RadStream);
int r4d_rad_iota (const RadArgs*, RadStream);
int r4d_rad_cu_repeat (const RadArgs*, RadStream);
/* r4d_video.hip */
int r4d_rad_rms_mod (const RadArgs*, RadStream);
int r4d_rad_rms_mod_quant_fp8 (const RadArgs*, RadStream);
int r4d_rad_flow_x0_step (const RadArgs*, RadStream);
int r4d_rad_patch_unfold (const RadArgs*, RadStream);
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_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*);
int r4d_rad_attn_vsa (const RadArgs*, RadStream);
/* r4d_quant_act_fp8.hip: E4M3 codes with a scale per column over every row (an attention's V). */
int r4d_rad_quant_cols_fp8 (const RadArgs*, RadStream);
int64_t r4d_rad_quant_cols_fp8_scratch(const RadArgs*);
/* Eight queries per KV head (r4d_attn_paged_gqa8.hip): the routed 35B-A3B at head_dim 256 and
* MiniCPM5-2B at 128. A decode workgroup holds 64 rows of q_len*gqa, so the verify width (the
* row's constraint value) is 8, against the gqa6 leg's 10. */
@@ -367,6 +404,7 @@ int r4d_rad_rope_table (const RadArgs*, RadStream);
int r4d_rad_gemm_fp8a16_m1 (const RadArgs*, RadStream);
int r4d_rad_gemm_fp8a8_m16 (const RadArgs*, RadStream);
int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs*, RadStream);
int r4d_rad_gemm_fp8a8_bias_m16(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_fp8a8_m16_scratch(const RadArgs*);
int r4d_rad_gemm_fp8a8_tiled(const RadArgs*, RadStream);
int r4d_rad_gemm_i8a8_m16 (const RadArgs*, RadStream);
@@ -453,6 +491,34 @@ 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);
/* 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*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_conv1d_tap(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_unrelayout_conv1d_tap(const RadParam*, int, int, const RadEncoding*, const int*,
const void*, int64_t, const RadTensor*, int);
int r4d_rad_layout_convt_phase(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_convt_phase(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_unrelayout_convt_phase(const RadParam*, int, int, const RadEncoding*, const int*,
const void*, int64_t, const RadTensor*, int);
/* The f32 rows' weights: conv1d's stored as bf16's, conv_t1d's [s][cout][ceil(k/s)][cin] with the
* taps past k zero (r4d_layout.cpp). */
int r4d_rad_layout_conv1d_tap_f32(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_conv1d_tap_f32(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_unrelayout_conv1d_tap_f32(const RadParam*, int, int, const RadEncoding*, const int*,
const void*, int64_t, const RadTensor*, int);
int r4d_rad_layout_convt_phase_f32(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_convt_phase_f32(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_unrelayout_convt_phase_f32(const RadParam*, int, int, const RadEncoding*, const int*,
const void*, int64_t, const RadTensor*, int);
int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
@@ -490,9 +556,11 @@ int r4d_rad_act_mul (const RadArgs*, RadStream);
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_pool_rows (const RadArgs*, RadStream);
int r4d_rad_relu (const RadArgs*, RadStream);
int r4d_rad_silu (const RadArgs*, RadStream);
int r4d_rad_gelu (const RadArgs*, RadStream);
int r4d_rad_clamp (const RadArgs*, RadStream);
int r4d_rad_conv2d (const RadArgs*, RadStream);
int r4d_rad_conv1d_dw (const RadArgs*, RadStream);
@@ -511,6 +579,8 @@ int r4d_rad_layernorm (const RadArgs*, RadStream);
int r4d_rad_grid_embed (const RadArgs*, RadStream);
int r4d_rad_grid_embed_aa (const RadArgs*, RadStream);
int r4d_rad_gemm_nt_bias (const RadArgs*, RadStream);
/* gemm_nt_bias at f32 (r4d_gemm_f32_nt_bias.hip). */
int r4d_rad_gemm_f32_nt_bias(const RadArgs*, RadStream);
int r4d_rad_kv_store (const RadArgs*, RadStream);
int r4d_rad_kv_store_fp8 (const RadArgs*, RadStream);
int r4d_rad_logits_gemm (const RadArgs*, RadStream);
@@ -595,6 +665,7 @@ int r4d_shape_ar_gather_hc_write (const RadParam*, int, int operand, RadOpdDes
int r4d_shape_gemm_nt (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_gemm_nt_q (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_gemm_nt_q_bias (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_gemm_nt_q_gated(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_dequant_w4 (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_row_topk (const RadParam*, int, int operand, RadOpdDesc*);
+145
View File
@@ -188,3 +188,148 @@ extern "C" int r4d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) {
extern "C" int r4d_rad_had_quant_act_i8g(const RadArgs* a, RadStream stream) {
return rad_quant_act_fp8(a, stream, true, true);
}
// ============================================================== quant_cols_fp8
// E4M3 codes with one scale per column over every row: an attention's V for its fp8 P.V. The
// formula is quant_act_fp8's (scale amax / 448, 1 for an all-zero column, codes of x / scale
// clamped to +-448) with the group running down a column. A column's scale needs every row, so
// two passes over the rows, split into kColChunks chunks:
// 1. column amax partials, a workgroup a block of columns and a chunk of rows, the bf16
// magnitudes compared as integers (their order is the values');
// 2. a workgroup the same block and chunk: the scales from the chunks' partials, then the codes,
// the chunk's rows walked from its end, which the first pass read last and the last-level
// cache still holds.
// A thread owns eight columns: one 16-byte load and one 8-byte store a row.
namespace {
constexpr int kColChunks = 32;
constexpr int kColThreads = 128;
typedef unsigned short r4d_u16x2 __attribute__((ext_vector_type(2)));
__device__ __forceinline__ r4d_u16x2 col_mag(uint32_t w) {
return __builtin_bit_cast(r4d_u16x2, w & 0x7fff7fffu);
}
__global__ __launch_bounds__(kColThreads) void quant_cols_amax_kernel(
const uint16_t* __restrict__ x, int M, int n, int x_ld, float* __restrict__ part) {
const int c8 = blockIdx.x * kColThreads + threadIdx.x;
if (c8 * 8 >= n) return;
const int r0 = (int)((long)M * blockIdx.y / kColChunks);
const int r1 = (int)((long)M * (blockIdx.y + 1) / kColChunks);
const uint16_t* p = x + (long)c8 * 8;
r4d_u16x2 m[4] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
int r = r0;
for (; r + 8 <= r1; r += 8) {
uint4 u[8];
#pragma unroll
for (int k = 0; k < 8; ++k) u[k] = *(const uint4*)(p + (long)(r + k) * x_ld);
#pragma unroll
for (int k = 0; k < 8; ++k) {
m[0] = __builtin_elementwise_max(m[0], col_mag(u[k].x));
m[1] = __builtin_elementwise_max(m[1], col_mag(u[k].y));
m[2] = __builtin_elementwise_max(m[2], col_mag(u[k].z));
m[3] = __builtin_elementwise_max(m[3], col_mag(u[k].w));
}
}
for (; r < r1; ++r) {
const uint4 u = *(const uint4*)(p + (long)r * x_ld);
m[0] = __builtin_elementwise_max(m[0], col_mag(u.x));
m[1] = __builtin_elementwise_max(m[1], col_mag(u.y));
m[2] = __builtin_elementwise_max(m[2], col_mag(u.z));
m[3] = __builtin_elementwise_max(m[3], col_mag(u.w));
}
float* d = part + (long)blockIdx.y * n + c8 * 8;
*(float4*)d = make_float4(bf16_to_f32(m[0].x), bf16_to_f32(m[0].y), bf16_to_f32(m[1].x),
bf16_to_f32(m[1].y));
*(float4*)(d + 4) = make_float4(bf16_to_f32(m[2].x), bf16_to_f32(m[2].y),
bf16_to_f32(m[3].x), bf16_to_f32(m[3].y));
}
template <bool HI>
__device__ __forceinline__ int col_code2(float a, float b, float ia, float ib, int old) {
return __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(a * ia, -448.0f), 448.0f),
fminf(fmaxf(b * ib, -448.0f), 448.0f), old, HI);
}
__global__ __launch_bounds__(kColThreads) void quant_cols_code_kernel(
const uint16_t* __restrict__ x, int M, int n, int x_ld, const float* __restrict__ part,
uint8_t* __restrict__ y, int y_ld, float* __restrict__ scale) {
const int c8 = blockIdx.x * kColThreads + threadIdx.x;
if (c8 * 8 >= n) return;
float am[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
for (int ch = 0; ch < kColChunks; ++ch) {
const float4 a = *(const float4*)(part + (long)ch * n + c8 * 8);
const float4 b = *(const float4*)(part + (long)ch * n + c8 * 8 + 4);
am[0] = fmaxf(am[0], a.x); am[1] = fmaxf(am[1], a.y);
am[2] = fmaxf(am[2], a.z); am[3] = fmaxf(am[3], a.w);
am[4] = fmaxf(am[4], b.x); am[5] = fmaxf(am[5], b.y);
am[6] = fmaxf(am[6], b.z); am[7] = fmaxf(am[7], b.w);
}
float sc[8], inv[8];
#pragma unroll
for (int e = 0; e < 8; ++e) {
sc[e] = am[e] > 0.0f ? am[e] * (1.0f / 448.0f) : 1.0f;
inv[e] = 1.0f / sc[e];
}
if (blockIdx.y == 0) {
*(float4*)(scale + c8 * 8) = make_float4(sc[0], sc[1], sc[2], sc[3]);
*(float4*)(scale + c8 * 8 + 4) = make_float4(sc[4], sc[5], sc[6], sc[7]);
}
const int r0 = (int)((long)M * blockIdx.y / kColChunks);
const int r1 = (int)((long)M * (blockIdx.y + 1) / kColChunks);
const uint16_t* p = x + (long)c8 * 8;
uint8_t* q = y + (long)c8 * 8;
auto code = [&](uint4 u) {
int lo = col_code2<false>(bf16w_lo(u.x), bf16w_hi(u.x), inv[0], inv[1], 0);
lo = col_code2<true>(bf16w_lo(u.y), bf16w_hi(u.y), inv[2], inv[3], lo);
int hi = col_code2<false>(bf16w_lo(u.z), bf16w_hi(u.z), inv[4], inv[5], 0);
hi = col_code2<true>(bf16w_lo(u.w), bf16w_hi(u.w), inv[6], inv[7], hi);
return make_uint2((uint32_t)lo, (uint32_t)hi);
};
int r = r1;
for (; r - 8 >= r0; r -= 8) {
uint4 u[8];
#pragma unroll
for (int k = 0; k < 8; ++k) u[k] = *(const uint4*)(p + (long)(r - 1 - k) * x_ld);
#pragma unroll
for (int k = 0; k < 8; ++k) *(uint2*)(q + (long)(r - 1 - k) * y_ld) = code(u[k]);
}
for (; r > r0; --r)
*(uint2*)(q + (long)(r - 1) * y_ld) = code(*(const uint4*)(p + (long)(r - 1) * x_ld));
}
} // namespace
/* The partial maxima of every chunk, kColChunks rows of n floats. */
extern "C" int64_t r4d_rad_quant_cols_fp8_scratch(const RadArgs* a) {
const long long n = r4d_geti_or(a, "n", 0);
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
return (int64_t)kColChunks * n * (int64_t)sizeof(float);
}
extern "C" int r4d_rad_quant_cols_fp8(const RadArgs* a, RadStream stream) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1), *sc = r4d_opt(a, 2);
if (!x || !y || !sc) return R4D_NO(RAD_E_INVAL);
if (x->dtype != RAD_BF16 || y->dtype != RAD_F8E4M3 || sc->dtype != RAD_F32)
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
if (n <= 0 || n % 8) return R4D_NO(RAD_E_SHAPE);
long long M = 0, my = 0;
const long long xl = r4d_rows_pitch(x, n, &M), yl = r4d_rows_pitch(y, n, &my);
if (xl < 0 || yl < 0 || (xl & 7) || (yl & 7) || ((uintptr_t)x->data & 15) ||
((uintptr_t)y->data & 7) || !r4d_contig(sc) || ((uintptr_t)sc->data & 15))
return R4D_NO(RAD_E_STRIDE);
if (my < M || r4d_numel(sc) < n || M > 0x7fffffffLL || n > 0x7fffffffLL)
return R4D_NO(RAD_E_SHAPE);
if (!a->scratch || ((uintptr_t)a->scratch & 15) ||
a->scratch_bytes < (int64_t)kColChunks * n * (int64_t)sizeof(float))
return R4D_NO(RAD_E_SCRATCH);
const dim3 grid((unsigned)((n / 8 + kColThreads - 1) / kColThreads), (unsigned)kColChunks);
hipLaunchKernelGGL(quant_cols_amax_kernel, grid, dim3(kColThreads), 0, (hipStream_t)stream,
(const uint16_t*)x->data, (int)M, (int)n, (int)xl, (float*)a->scratch);
hipLaunchKernelGGL(quant_cols_code_kernel, grid, dim3(kColThreads), 0, (hipStream_t)stream,
(const uint16_t*)x->data, (int)M, (int)n, (int)xl,
(const float*)a->scratch, (uint8_t*)y->data, (int)yl, (float*)sc->data);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
+737 -53
View File
File diff suppressed because it is too large. Load diff
+4111 -56
View File
File diff suppressed because it is too large. Load diff
+27 -3
View File
@@ -315,10 +315,11 @@ extern "C" int r4d_shape_cast(const RadParam* p, int n_p, int operand,
const int64_t M = pi(p, n_p, "M");
const int64_t n = pi(p, n_p, "n");
/* Two rows serve the op, bf16 -> bf16 (a strided row copy) and bf16 -> f32, and the shims
* refuse any other pair, so another pair is declined here. */
/* Three rows serve the op, bf16 -> bf16 (a strided row copy), bf16 -> f32 and bf16 -> f16,
* and the shims refuse any other pair, so another pair is declined here. */
const uint32_t f = dt_par(p, n_p, "from"), t = dt_par(p, n_p, "to");
if (f != (uint32_t)RAD_BF16 || (t != (uint32_t)RAD_BF16 && t != (uint32_t)RAD_F32))
if (f != (uint32_t)RAD_BF16 ||
(t != (uint32_t)RAD_BF16 && t != (uint32_t)RAD_F32 && t != (uint32_t)RAD_F16))
return RAD_E_UNSUPPORTED;
const RadOpdDesc l[] = { opd(f, M, n), opd(t, M, n) };
R4D_PICK(l);
@@ -1061,6 +1062,29 @@ extern "C" int r4d_shape_gemm_nt_q(const RadParam* p, int n_p, int operand,
R4D_PICK(l);
}
/* gemm_nt_q_bias at fp8a8: gemm_nt_q's fp8 operands, a bf16 bias per output column, then y. The
* libref description matches it (ref_gemm_nt_q_bias_shape). */
extern "C" int r4d_shape_gemm_nt_q_bias(const RadParam* p, int n_p, int operand,
RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t N = pi(p, n_p, "N");
const int64_t K = pi(p, n_p, "K");
const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK);
const char* q = r4d_pgets(p, n_p, "dtype");
if (!q || std::strcmp(q, "fp8a8") || g != R4D_FP8_BLOCK || K <= 0 || N <= 0)
return RAD_E_UNSUPPORTED;
const int64_t kb = (K + g - 1) / g, nb = (N + g - 1) / g;
const RadOpdDesc l[] = {
opd((uint32_t)RAD_F8E4M3, M, K),
opd((uint32_t)RAD_F32, M, kb),
opd((uint32_t)RAD_F8E4M3, N, K),
opd((uint32_t)RAD_BF16, nb, kb),
opd((uint32_t)RAD_BF16, N),
opd((uint32_t)RAD_BF16, M, N),
};
R4D_PICK(l);
}
/* The same GEMM with the SwiGLU and the quantiser in its epilogue. `N` is the weight's rows, gate
* then up, so the quantiser's outputs are N/2 wide (hence a schema of its own). */
extern "C" int r4d_shape_gemm_nt_q_gated(const RadParam* p, int n_p, int operand,
+654
View File
@@ -0,0 +1,654 @@
// R4D -- the video generator's ops (docs/OPS.md, "Video generation"): a diffusion transformer's
// modulated RMS norm and its sampler step, the video decoder's patch unfold, the tiles it runs
// over, their stitch back into frames and their rotary positions; and its soundtrack decoder's
// alias-free SnakeBeta (docs/OPS.md, "Audio generation").
//
// Each kernel rounds where its libref function does (libref/ref_gen.cpp, libref/ref_video.cpp,
// libref/ref_audio.cpp), under the library's -ffp-contract=off. The norm's sum of squares is a
// block sum here and a sequential one there, so a norm output can land one bf16 step apart, and
// sin and exp are the device's; every other value is the reference's arithmetic in its order.
//
// A request's latent geometry is a device operand (`geom`), never a parameter, so the decoder's
// kernels read it on the device and recompute an axis's tile layout from its length there. Rows
// past what the geometry writes are left alone.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_gdn_wmma.h"
#include "r4d_q8.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
namespace {
constexpr int kT = 256;
__device__ __forceinline__ float bfr(float v) { return bf2f(f32_to_bf16(v)); }
__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 st8(uint16_t* p, const float* f) {
uint4 u;
u.x = (uint32_t)f32_to_bf16(f[0]) | ((uint32_t)f32_to_bf16(f[1]) << 16);
u.y = (uint32_t)f32_to_bf16(f[2]) | ((uint32_t)f32_to_bf16(f[3]) << 16);
u.z = (uint32_t)f32_to_bf16(f[4]) | ((uint32_t)f32_to_bf16(f[5]) << 16);
u.w = (uint32_t)f32_to_bf16(f[6]) | ((uint32_t)f32_to_bf16(f[7]) << 16);
*(uint4*)p = u;
}
// The entry that owns row r of a cu_seqlens partition: linear, because a step has three
// segments and a vocoder pass two channels.
__device__ __forceinline__ int seq_of(const int* cu, int n_seq, int r) {
int s = 0;
while (s + 1 < n_seq && cu[s + 1] <= r) ++s;
return s;
}
// A sum over the 256 threads, every thread receiving it. `sh` is 8 floats of LDS.
__device__ __forceinline__ float block_sum(float v, float* sh) {
v = r4d_wave_sum(v);
__syncthreads();
if ((threadIdx.x & 31) == 0) sh[threadIdx.x >> 5] = v;
__syncthreads();
float t = 0.0f;
#pragma unroll
for (int i = 0; i < kT / 32; ++i) t += sh[i];
return t;
}
// A value of a bf16 or f32 operand, and a store rounded to it.
__device__ __forceinline__ float ldv(const uint16_t* p, int64_t i) { return bf2f(p[i]); }
__device__ __forceinline__ float ldv(const float* p, int64_t i) { return p[i]; }
__device__ __forceinline__ void stv(uint16_t* p, int64_t i, float v) { p[i] = f32_to_bf16(v); }
__device__ __forceinline__ void stv(float* p, int64_t i, float v) { p[i] = v; }
__device__ __forceinline__ float rdv(const uint16_t*, float v) { return bfr(v); }
__device__ __forceinline__ float rdv(const float*, float v) { return v; }
// ---------------------------------------------------------------------------- rms_mod
// The gated residual of the branch before, then the RMS norm with a gain and the entry's shift and
// scale, a workgroup a row: libref's rms_mod_row with the residual and the chain rounded to bf16.
// With QUANT the chain feeds quant_act_fp8 as ln_mod_quant_fp8 does (r4d_gen.hip): a 128-column
// group is sixteen consecutive lanes, so its amax is a half-wave reduction, and the codes are
// r4d_q8.h's. `s` is a column slice of the modulation table, [shift | scale] in each entry's row.
constexpr int kRmChunks = 4; // 8-wide chunks a thread keeps: n <= kT * 8 * 4 = 8192
template <bool GATED, bool QUANT>
__global__ __launch_bounds__(kT) void rms_mod_kernel(
const uint16_t* __restrict__ yd, const uint16_t* __restrict__ g, const uint16_t* __restrict__ s,
const uint16_t* __restrict__ w, const int* __restrict__ cu, uint16_t* __restrict__ x,
uint8_t* __restrict__ q, float* __restrict__ qs, uint16_t* __restrict__ z, int n, int n_seq,
float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld) {
__shared__ float sh[kT / 32];
const int r = blockIdx.x;
const int e = seq_of(cu, n_seq, r);
uint16_t* xr = x + (size_t)r * x_ld;
float v[kRmChunks][8];
float ss = 0.0f;
#pragma unroll
for (int k = 0; k < kRmChunks; ++k) {
const int i = ((int)threadIdx.x + k * kT) * 8;
if (i < n) {
float f[8];
ld8(xr + i, f);
if (GATED) {
float a[8], b[8];
ld8(yd + (size_t)r * y_ld + i, a);
ld8(g + (size_t)e * g_ld + i, b);
#pragma unroll
for (int j = 0; j < 8; ++j) f[j] = f[j] + bfr(b[j] * a[j]);
st8(xr + i, f);
#pragma unroll
for (int j = 0; j < 8; ++j) f[j] = bfr(f[j]);
}
#pragma unroll
for (int j = 0; j < 8; ++j) { v[k][j] = f[j]; ss += f[j] * f[j]; }
}
}
const float rs = 1.0f / sqrtf(block_sum(ss, sh) / (float)n + eps);
const uint16_t* sr = s + (size_t)e * s_ld;
#pragma unroll
for (int k = 0; k < kRmChunks; ++k) {
const int i = ((int)threadIdx.x + k * kT) * 8;
if (i >= n) break;
float shf[8], scf[8], wf[8], o[8];
ld8(sr + i, shf);
ld8(sr + n + i, scf);
ld8(w + i, wf);
#pragma unroll
for (int j = 0; j < 8; ++j) {
const float n2 = bfr(bfr(v[k][j] * rs) * wf[j]);
o[j] = bfr(bfr(n2 * bfr(1.0f + scf[j])) + shf[j]);
}
if (z) st8(z + (size_t)r * z_ld + i, o);
if (QUANT) {
float m = 0.0f;
#pragma unroll
for (int j = 0; j < 8; ++j) m = fmaxf(m, fabsf(o[j]));
m = fmaxf(m, r4d_xor_lane<8>(m));
m = fmaxf(m, r4d_xor_lane<4>(m));
m = fmaxf(m, r4d_xor_lane<2>(m));
m = fmaxf(m, r4d_xor_lane<1>(m));
const float sc = m > 0.0f ? m * (1.0f / q8_top<false>()) : 1.0f;
const float inv = 1.0f / sc;
if ((threadIdx.x & 15) == 0) qs[(size_t)r * qs_ld + i / 128] = sc;
*(uint2*)(q + (size_t)r * q_ld + i) =
make_uint2(q8_pack4<false>(o[0], o[1], o[2], o[3], inv),
q8_pack4<false>(o[4], o[5], o[6], o[7], inv));
}
}
}
// ---------------------------------------------------------------------------- flow_x0_step
// One sampler step a lane value: the clean estimate d = x + (1 - t) v, then x' = r x + (1 - r) d
// with r = sigma_next / sigma, every product and sum one f32 rounding.
template <typename TV>
__global__ __launch_bounds__(kT) void flow_x0_kernel(
const TV* __restrict__ v, const float* __restrict__ t, const float* __restrict__ sg,
const float* __restrict__ sgn, float* __restrict__ x, int n, int v_ld, int x_ld, int64_t total) {
const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x;
if (id >= total) return;
const int64_t r = id / n;
const int c = (int)(id % n);
const float st = 1.0f - t[0];
const float ra = sgn[0] / sg[0];
const float omr = 1.0f - ra;
float* xp = x + r * x_ld + c;
const float xv = *xp;
const float d = xv + st * ldv(v, r * v_ld + c);
*xp = ra * xv + omr * d;
}
// ---------------------------------------------------------------------------- patch_unfold
// The two parameter lists of the latent's statistics, f32 kernel arguments.
constexpr int kMaxChan = 64;
struct ChanList { float v[kMaxChan]; };
// A thread a voxel channel: y[(t, yy, xx), c] = f32(f32(x[patch, (c, sub)] * mul[c]) + add[c]).
__global__ __launch_bounds__(kT) void patch_unfold_kernel(
const float* __restrict__ x, const int* __restrict__ geom, float* __restrict__ y, ChanList mul,
ChanList add, int C, int pt, int ph, int pw, int x_ld, int y_ld, int64_t cap, int64_t x_rows) {
const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x;
const int F = geom[0], Hp = geom[1], Wp = geom[2];
const int64_t Hv = (int64_t)Hp * ph, Wv = (int64_t)Wp * pw;
const int64_t rows = (int64_t)F * pt * Hv * Wv;
if (id >= cap || id >= rows * C || (int64_t)F * Hp * Wp > x_rows) return;
const int64_t r = id / C;
const int c = (int)(id % C);
const int64_t tt = r / (Hv * Wv), yy = (r / Wv) % Hv, xx = r % Wv;
const int64_t patch = ((tt / pt) * Hp + yy / ph) * Wp + xx / pw;
const int64_t sub = ((tt % pt) * ph + yy % ph) * pw + xx % pw;
y[r * y_ld + c] = x[patch * x_ld + c * pt * ph * pw + sub] * mul.v[c] + add.v[c];
}
// ---------------------------------------------------------------------------- the tile layout
// diffusers' _split_tiles in latent units (libref's split_tiles), in closed form: the tile count
// is the fewest whose overlaps are all at least `overlap`; the slack tile n - overlap (n - 1) - len
// goes to the overlaps one unit at a time from the first, so overlap i is overlap + q + (i < rr)
// with q, rr the slack's quotient and remainder by n - 1. A tile at least as long as the axis is
// one tile, a layout only when it is exactly as long.
struct Tiles {
int n = 0, q = 0, rr = 0, tile = 0, overlap = 0;
__device__ int ov(int i) const { return overlap + q + (i < rr ? 1 : 0); }
__device__ int start(int i) const { return i * (tile - overlap - q) - min(i, rr); }
};
__device__ __forceinline__ Tiles split_tiles(int len, int tile, int overlap) {
Tiles t;
t.tile = tile;
t.overlap = overlap;
if (len <= 0 || tile <= 0 || overlap < 0 || overlap >= tile) return t;
if (tile >= len) {
t.n = len == tile ? 1 : 0;
return t;
}
int n = (len + tile - 1) / tile;
while (tile * n - overlap * (n - 1) < len) ++n;
const int rem = tile * n - overlap * (n - 1) - len;
t.n = n;
t.q = rem / (n - 1);
t.rr = rem % (n - 1);
return t;
}
// ---------------------------------------------------------------------------- vtile_gather
// A workgroup a tile row: its voxel from x, a register token from `reg`, or zeros.
template <typename TX, typename TR, typename TY>
__global__ __launch_bounds__(kT) void vtile_gather_kernel(
const TX* __restrict__ x, const TR* __restrict__ reg, const int* __restrict__ geom,
TY* __restrict__ y, int n, int tile, int overlap, int frames, int period, int n_reg, int x_ld,
int reg_ld, int y_ld, int64_t x_rows) {
const int row = blockIdx.x;
const int H = geom[1], W = geom[2];
if (geom[0] != frames || (int64_t)frames * H * W > x_rows) return;
const Tiles ty = split_tiles(H, tile, overlap), tx = split_tiles(W, tile, overlap);
if (ty.n == 0 || tx.n == 0 || row >= ty.n * tx.n * period) return;
const int k = row / period, p = row % period;
const int vox = frames * tile * tile;
TY* yr = y + (size_t)row * y_ld;
if (p < vox) {
const int t = p / (tile * tile), iy = (p / tile) % tile, ix = p % tile;
const int64_t src = ((int64_t)t * H + ty.start(k / tx.n) + iy) * W + tx.start(k % tx.n) + ix;
const TX* xr = x + src * x_ld;
for (int c = threadIdx.x; c < n; c += kT) stv(yr, c, ldv(xr, c));
} else if (p < vox + n_reg) {
const TR* rr = reg + (size_t)(p - vox) * reg_ld;
for (int c = threadIdx.x; c < n; c += kT) stv(yr, c, ldv(rr, c));
} else {
for (int c = threadIdx.x; c < n; c += kT) stv(yr, c, 0.0f);
}
}
// ---------------------------------------------------------------------------- vtile_stitch
// A thread a (pixel, colour) over every frame the chunk writes, so a pixel's reads of `prev`
// precede its writes of it in one thread: the kept frames, blended with the previous chunk's
// tail unless first, then the tail handed on (and written when last). The blends round to x's
// dtype and the tail is stored at prev's, as libref's ref_vtile_stitch.
struct PixList { float mean[3], stdv[3]; };
template <typename TX, typename TP>
__global__ __launch_bounds__(kT) void vtile_stitch_kernel(
const TX* __restrict__ x, const int* __restrict__ geom, TP* __restrict__ prev,
uint8_t* __restrict__ y, PixList pl, int tile, int overlap, int S, int pt, int skip, int keep,
int blend, int period, int x_ld, int p_ld, int y_ld, int64_t cap, int64_t x_rows,
int64_t p_rows) {
const int frames = geom[0], H = geom[1], W = geom[2];
const bool first = geom[3] != 0, last = geom[4] != 0;
const int64_t Hp = (int64_t)H * S, Wp = (int64_t)W * S, npx = Hp * Wp;
const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x;
if (id >= npx * 3 || 2 * skip + keep + blend > frames * pt || period < frames * tile * tile)
return;
const int64_t fout = keep + (last ? blend : 0);
if (fout * npx > cap) return;
const Tiles ty = split_tiles(H, tile, overlap), tx = split_tiles(W, tile, overlap);
if (ty.n == 0 || tx.n == 0 || (int64_t)ty.n * tx.n * period > x_rows ||
(int64_t)blend * npx > p_rows)
return;
const int c = (int)(id / npx);
const int64_t px = id % npx;
const int Y = (int)(px / Wp), X = (int)(px % Wp);
// The owner tile of the pixel's row and column, and its offset in it.
int i = 0, j = 0;
while (i + 1 < ty.n && Y >= ty.start(i + 1) * S) ++i;
while (j + 1 < tx.n && X >= tx.start(j + 1) * S) ++j;
const int ly = Y - ty.start(i) * S, lx = X - tx.start(j) * S;
const int ev = i > 0 ? ty.ov(i - 1) * S : 0, eh = j > 0 ? tx.ov(j - 1) * S : 0;
auto rd = [&](float v) { return rdv(x, v); };
auto wb = [&](int p, int e) { return rd((float)p / (float)e); };
auto wa = [&](int p, int e) { return rd(1.0f - rd((float)p / (float)e)); };
auto T = [&](int ti, int tj, int ay, int ax, int fc) {
const int64_t row = (int64_t)(ti * tx.n + tj) * period +
((fc / pt) * tile + ay / S) * tile + ax / S;
const int col = ((c * pt + fc % pt) * S + ay % S) * S + ax % S;
return ldv(x, row * x_ld + col);
};
auto stitch = [&](int fc) {
float v = T(i, j, ly, lx, fc);
if (ly < ev) {
const float up = T(i - 1, j, ly + tile * S - ev, lx, fc);
v = rd(rd(up * wa(ly, ev)) + rd(v * wb(ly, ev)));
}
if (lx < eh) {
const float left = T(i, j - 1, ly, lx + tile * S - eh, fc);
v = rd(rd(left * wa(lx, eh)) + rd(v * wb(lx, eh)));
}
return v;
};
auto byte = [&](int f, float v) {
float p = v * pl.stdv[c] + pl.mean[c];
p = p < 0.0f ? 0.0f : (p > 1.0f ? 1.0f : p);
p = p * 255.0f;
float r = p != p ? 0.0f : rintf(p);
r = r < 0.0f ? 0.0f : (r > 255.0f ? 255.0f : r);
y[(f * npx + px) * y_ld + c] = (uint8_t)r;
};
for (int k = 0; k < keep; ++k) {
float v = stitch(skip + k);
if (!first && k < blend) {
const float pv = ldv(prev, (k * npx + px) * p_ld + c);
v = rd(rd(pv * wa(k, blend)) + rd(v * wb(k, blend)));
}
byte(k, v);
}
for (int k = 0; k < blend; ++k) {
const float v = stitch(2 * skip + keep + k);
if (last) byte(keep + k, v);
stv(prev, (k * npx + px) * p_ld + c, v);
}
}
// ---------------------------------------------------------------------------- grid_pos3
// A thread a row: its token's three centred, scaled coordinates, or zeros past the tile's tokens.
__global__ __launch_bounds__(kT) void grid_pos3_kernel(
float* __restrict__ y, int T, int H, int W, int period, float scale, int M, int rs, int cs) {
const int m = blockIdx.x * kT + threadIdx.x;
if (m >= M) return;
const int k = m % period;
float p[3] = { 0.0f, 0.0f, 0.0f };
if (k < T * H * W) {
const int cc[3] = { k / (H * W), (k / W) % H, k % W }, nn[3] = { T, H, W };
#pragma unroll
for (int a = 0; a < 3; ++a) {
const float qq = ((float)cc[a] + 0.5f) / (float)nn[a];
p[a] = scale * (2.0f * qq - 1.0f);
}
}
#pragma unroll
for (int a = 0; a < 3; ++a) y[(size_t)a * rs + (size_t)m * cs] = p[a];
}
// ---------------------------------------------------------------------------- snake_aa
// A thread an output (row, channel) of a sequence: the `k` activations its low-pass filter reads,
// each the upsampled value at that position through SnakeBeta, recomputed per output rather than
// staged (an activation is read by k / ratio outputs). Indices and orders are libref's
// ref_snake_aa: the replicate pad P = k / ratio - 1, the upsampler's crop, the low-pass's left pad
// k / 2 (one less for an even k), each sum in ascending tap.
constexpr int kMaxTaps = 32;
__global__ __launch_bounds__(kT) void snake_aa_kernel(
const float* __restrict__ x, const float* __restrict__ al, const float* __restrict__ be,
const float* __restrict__ fu, const float* __restrict__ fd, const int* __restrict__ cu,
float* __restrict__ y, int n, int R, int k, int lg, int n_seq, int x_ld, int y_ld,
int64_t cap) {
__shared__ float sfu[kMaxTaps], sfd[kMaxTaps];
if ((int)threadIdx.x < k) {
sfu[threadIdx.x] = fu[threadIdx.x];
sfd[threadIdx.x] = fd[threadIdx.x];
}
__syncthreads();
const int64_t id = (int64_t)blockIdx.x * kT + threadIdx.x;
const int r0 = cu[0], r1 = cu[n_seq];
if (id >= cap || id >= (int64_t)(r1 - r0) * n) return;
const int row = r0 + (int)(id / n), c = (int)(id % n);
const int e = seq_of(cu, n_seq, row);
const int s0 = cu[e], L = cu[e + 1] - s0, o = row - s0;
const int P = k / R - 1, crop = P * R + (k - R) / 2, pad = k / 2 - (k % 2 == 0 ? 1 : 0);
const float A = lg ? expf(al[c]) : al[c];
const float B = lg ? expf(be[c]) : be[c];
const float ib = 1.0f / (B + 1e-9f);
const int LR = L * R;
float acc = 0.0f;
for (int jt = 0; jt < k; ++jt) {
const int m = min(max(o * R + jt - pad, 0), LR - 1);
const int oo = crop + m;
const int i_lo = oo < k ? 0 : (oo - k) / R + 1;
const int i_hi = min(oo / R, L + 2 * P - 1);
float u = 0.0f;
for (int ii = i_lo; ii <= i_hi; ++ii) {
const int qrow = min(max(ii - P, 0), L - 1);
u += sfu[oo - ii * R] * x[(size_t)(s0 + qrow) * x_ld + c];
}
u = (float)R * u;
const float sn = sinf(u * A);
acc += sfd[jt] * (u + ib * (sn * sn));
}
y[(size_t)row * y_ld + c] = acc;
}
inline int st_of(hipError_t e) { return e == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); }
inline unsigned blocks_for(int64_t n) { return (unsigned)((n + kT - 1) / kT); }
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, with the pitch a multiple of eight elements so a row
// is read 16 bytes at a time.
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;
}
} // namespace
// ============================================================== the plugin ABI entry points
// rms_mod (QUANT false: y, g, s, w, cu, x, z) and rms_mod_quant_fp8 (y, g, s, w, cu, x, q, scale,
// z), one shim.
static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) {
const RadTensor *y = r4d_opt(a, 0), *g = r4d_opt(a, 1), *sc = r4d_opt(a, 2);
const RadTensor *w = r4d_opt(a, 3), *cu = r4d_opt(a, 4), *x = r4d_opt(a, 5);
const RadTensor* q = quant ? r4d_opt(a, 6) : nullptr;
const RadTensor* qs = quant ? r4d_opt(a, 7) : nullptr;
const RadTensor* z = r4d_opt(a, quant ? 8 : 6);
if (!sc || !w || !cu || !x || (quant ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL);
const bool gated = r4d_geti_or(a, "gated", 0) != 0;
if (gated && (!y || !g)) return R4D_NO(RAD_E_INVAL);
if (!is_bf16(x) || !is_bf16(sc) || !is_bf16(w) || !is_i32(cu) ||
(gated && (!is_bf16(y) || !is_bf16(g))) || (z && !is_bf16(z)) ||
(quant && (q->dtype != RAD_F8E4M3 || qs->dtype != RAD_F32)))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
if (n <= 0 || (n & 7) || n > (long long)kT * 8 * kRmChunks ||
(quant && (n % 128 || r4d_geti_or(a, "group", 0) != 128)))
return R4D_NO(RAD_E_SHAPE);
long long rx = 0, xl = 0, ry = 0, yl = 0, rg = 0, gl = 0, rs = 0, sl = 0, rz = 0, zl = 0;
long long rq = 0, rqs = 0, ql = 0, qsl = 0;
if (!rows8(x, n, &rx, &xl) || !rows8(sc, 2 * n, &rs, &sl) || !r4d_contig(cu) ||
!r4d_contig(w) || ((uintptr_t)w->data & 15) ||
(gated && (!rows8(y, n, &ry, &yl) || !rows8(g, n, &rg, &gl))) ||
(z && !rows8(z, n, &rz, &zl)))
return R4D_NO(RAD_E_STRIDE);
if (quant) {
ql = r4d_rows_pitch(q, n, &rq);
qsl = r4d_rows_pitch(qs, n / 128, &rqs);
if (ql < 0 || (ql & 7) || ((uintptr_t)q->data & 7) || qsl < 0) return R4D_NO(RAD_E_STRIDE);
}
const long long n_seq = r4d_numel(cu) - 1, rows = quant ? rq : rz;
if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || r4d_numel(w) < n ||
(quant && rqs < rows) || (gated && (ry < rows || rg < n_seq)) || (z && rz < rows))
return R4D_NO(RAD_E_SHAPE);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
#define R4D_RMQ(G, Q) \
hipLaunchKernelGGL((rms_mod_kernel<G, Q>), dim3((unsigned)rows), dim3(kT), 0, \
(hipStream_t)st, G ? (const uint16_t*)y->data : nullptr, \
G ? (const uint16_t*)g->data : nullptr, (const uint16_t*)sc->data, \
(const uint16_t*)w->data, (const int*)cu->data, (uint16_t*)x->data, \
Q ? (uint8_t*)q->data : nullptr, Q ? (float*)qs->data : nullptr, \
z ? (uint16_t*)z->data : nullptr, (int)n, (int)n_seq, eps, (int)yl, \
(int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl)
if (quant) {
if (gated) R4D_RMQ(true, true);
else R4D_RMQ(false, true);
} else {
if (gated) R4D_RMQ(true, false);
else R4D_RMQ(false, false);
}
#undef R4D_RMQ
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_rms_mod(const RadArgs* a, RadStream s) { return rms_mod_launch(a, s, false); }
extern "C" int r4d_rad_rms_mod_quant_fp8(const RadArgs* a, RadStream s) {
return rms_mod_launch(a, s, true);
}
extern "C" int r4d_rad_flow_x0_step(const RadArgs* a, RadStream s) {
const RadTensor *v = r4d_opt(a, 0), *t = r4d_opt(a, 1), *sg = r4d_opt(a, 2);
const RadTensor *sgn = r4d_opt(a, 3), *x = r4d_opt(a, 4);
if (!v || !t || !sg || !sgn || !x) return R4D_NO(RAD_E_INVAL);
if (!is_f32(x) || !is_f32(t) || !is_f32(sg) || !is_f32(sgn) || (!is_f32(v) && !is_bf16(v)))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0);
long long rx = 0, rv = 0;
const long long xl = n > 0 ? r4d_rows_pitch(x, n, &rx) : -1;
const long long vl = n > 0 ? r4d_rows_pitch(v, n, &rv) : -1;
if (xl < 0 || vl < 0) return R4D_NO(RAD_E_STRIDE);
if (rx <= 0 || rv < rx || r4d_numel(t) < 1 || r4d_numel(sg) < 1 || r4d_numel(sgn) < 1)
return R4D_NO(RAD_E_SHAPE);
const int64_t total = (int64_t)rx * n;
#define R4D_FX0(TV) \
hipLaunchKernelGGL(flow_x0_kernel<TV>, dim3(blocks_for(total)), dim3(kT), 0, (hipStream_t)s, \
(const TV*)v->data, (const float*)t->data, (const float*)sg->data, \
(const float*)sgn->data, (float*)x->data, (int)n, (int)vl, (int)xl, total)
if (is_f32(v)) R4D_FX0(float);
else R4D_FX0(uint16_t);
#undef R4D_FX0
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_patch_unfold(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *geom = r4d_opt(a, 1), *y = r4d_opt(a, 2);
if (!x || !geom || !y) return R4D_NO(RAD_E_INVAL);
if (!is_f32(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);
long long rx = 0, ry = 0;
const long long xl = r4d_rows_pitch(x, C * pt * ph * pw, &rx), yl = r4d_rows_pitch(y, C, &ry);
if (xl < 0 || yl < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE);
if (ry <= 0 || rx <= 0) return R4D_NO(RAD_E_SHAPE);
const int64_t cap = (int64_t)ry * C;
hipLaunchKernelGGL(patch_unfold_kernel, dim3(blocks_for(cap)), dim3(kT), 0, (hipStream_t)s,
(const float*)x->data, (const int*)geom->data, (float*)y->data, mul, add,
(int)C, (int)pt, (int)ph, (int)pw, (int)xl, (int)yl, cap, (int64_t)rx);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_vtile_gather(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *reg = r4d_opt(a, 1), *geom = r4d_opt(a, 2);
const RadTensor* y = r4d_opt(a, 3);
if (!x || !reg || !geom || !y) return R4D_NO(RAD_E_INVAL);
if ((!is_f32(x) && !is_bf16(x)) || (!is_f32(reg) && !is_bf16(reg)) ||
(!is_f32(y) && !is_bf16(y)) || !is_i32(geom))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), tile = r4d_geti_or(a, "tile", 0);
const long long overlap = r4d_geti_or(a, "overlap", 0), frames = r4d_geti_or(a, "frames", 0);
const long long period = r4d_geti_or(a, "period", 0), n_reg = r4d_geti_or(a, "n_reg", 0);
if (n <= 0 || tile <= 0 || frames <= 0 || n_reg < 0 || overlap < 0 || overlap >= tile ||
period < frames * tile * tile + n_reg || r4d_numel(geom) < 3)
return R4D_NO(RAD_E_SHAPE);
long long rx = 0, rr = 0, ry = 0;
const long long xl = r4d_rows_pitch(x, n, &rx), rl = r4d_rows_pitch(reg, n, &rr);
const long long yl = r4d_rows_pitch(y, n, &ry);
if (xl < 0 || rl < 0 || yl < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE);
if (ry <= 0 || rr < n_reg) return R4D_NO(RAD_E_SHAPE);
#define R4D_VTG(TX, TR, TY) \
hipLaunchKernelGGL((vtile_gather_kernel<TX, TR, TY>), dim3((unsigned)ry), dim3(kT), 0, \
(hipStream_t)s, (const TX*)x->data, (const TR*)reg->data, \
(const int*)geom->data, (TY*)y->data, (int)n, (int)tile, (int)overlap, \
(int)frames, (int)period, (int)n_reg, (int)xl, (int)rl, (int)yl, \
(int64_t)rx)
#define R4D_VTG_Y(TX, TR) \
do { if (is_f32(y)) R4D_VTG(TX, TR, float); else R4D_VTG(TX, TR, uint16_t); } while (0)
#define R4D_VTG_R(TX) \
do { if (is_f32(reg)) R4D_VTG_Y(TX, float); else R4D_VTG_Y(TX, uint16_t); } while (0)
if (is_f32(x)) R4D_VTG_R(float);
else R4D_VTG_R(uint16_t);
#undef R4D_VTG_R
#undef R4D_VTG_Y
#undef R4D_VTG
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_vtile_stitch(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *geom = r4d_opt(a, 1), *prev = r4d_opt(a, 2);
const RadTensor* y = r4d_opt(a, 3);
if (!x || !geom || !prev || !y) return R4D_NO(RAD_E_INVAL);
if ((!is_f32(x) && !is_bf16(x)) || (!is_f32(prev) && !is_bf16(prev)) || y->dtype != RAD_U8 ||
!is_i32(geom))
return R4D_NO(RAD_E_DTYPE);
const long long tile = r4d_geti_or(a, "tile", 0), overlap = r4d_geti_or(a, "overlap", 0);
const long long S = r4d_geti_or(a, "scale", 0), pt = r4d_geti_or(a, "pt", 0);
const long long skip = r4d_geti_or(a, "skip", 0), keep = r4d_geti_or(a, "keep", 0);
const long long blend = r4d_geti_or(a, "blend", 0), period = r4d_geti_or(a, "period", 0);
PixList pl{};
if (tile <= 0 || overlap < 0 || overlap >= tile || S <= 0 || pt <= 0 || skip < 0 ||
keep <= 0 || blend < 0 || blend > keep || period <= 0 ||
parse_f32_list(r4d_gets(a, "mean"), pl.mean, 3) != 3 ||
parse_f32_list(r4d_gets(a, "std"), pl.stdv, 3) != 3 || r4d_numel(geom) < 5)
return R4D_NO(RAD_E_SHAPE);
const long long cols = 3 * pt * S * S;
long long rx = 0, rp = 0, ry = 0;
const long long xl = r4d_rows_pitch(x, cols, &rx), pl_ld = r4d_rows_pitch(prev, 3, &rp);
const long long yl = r4d_rows_pitch(y, 3, &ry);
if (xl < 0 || pl_ld < 0 || yl < 0 || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE);
if (ry <= 0 || rx < period) return R4D_NO(RAD_E_SHAPE);
// A thread a (pixel, colour) of the largest frame the output holds; the kernel bounds the rest
// by the device geometry.
const int64_t npx_cap = ry / keep, total = npx_cap * 3;
#define R4D_VTS(TX, TP) \
hipLaunchKernelGGL((vtile_stitch_kernel<TX, TP>), dim3(blocks_for(total)), dim3(kT), 0, \
(hipStream_t)s, (const TX*)x->data, (const int*)geom->data, \
(TP*)prev->data, (uint8_t*)y->data, pl, (int)tile, (int)overlap, (int)S, \
(int)pt, (int)skip, (int)keep, (int)blend, (int)period, (int)xl, \
(int)pl_ld, (int)yl, (int64_t)ry, (int64_t)rx, (int64_t)rp)
#define R4D_VTS_P(TX) \
do { if (is_f32(prev)) R4D_VTS(TX, float); else R4D_VTS(TX, uint16_t); } while (0)
if (is_f32(x)) R4D_VTS_P(float);
else R4D_VTS_P(uint16_t);
#undef R4D_VTS_P
#undef R4D_VTS
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_grid_pos3(const RadArgs* a, RadStream s) {
const RadTensor* y = r4d_opt(a, 0);
if (!y) return R4D_NO(RAD_E_INVAL);
if (!is_f32(y)) return R4D_NO(RAD_E_DTYPE);
const long long T = r4d_geti_or(a, "T", 0), H = r4d_geti_or(a, "H", 0);
const long long W = r4d_geti_or(a, "W", 0), period = r4d_geti_or(a, "period", 0);
if (T <= 0 || H <= 0 || W <= 0 || period < T * H * W || y->rank != 2 || y->shape[0] < 3)
return R4D_NO(RAD_E_SHAPE);
const long long M = y->shape[1];
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(grid_pos3_kernel, dim3(blocks_for(M)), dim3(kT), 0, (hipStream_t)s,
(float*)y->data, (int)T, (int)H, (int)W, (int)period,
(float)r4d_getf(a, "scale", 1.0), (int)M, (int)y->stride[0],
(int)y->stride[1]);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_snake_aa(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *al = r4d_opt(a, 1), *be = r4d_opt(a, 2);
const RadTensor *fu = r4d_opt(a, 3), *fd = r4d_opt(a, 4), *cu = r4d_opt(a, 5);
const RadTensor* y = r4d_opt(a, 6);
if (!x || !al || !be || !fu || !fd || !cu || !y) return R4D_NO(RAD_E_INVAL);
if (!is_f32(x) || !is_f32(y) || !is_f32(al) || !is_f32(be) || !is_f32(fu) || !is_f32(fd) ||
!is_i32(cu))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), R = r4d_geti_or(a, "ratio", 0);
const long long k = r4d_geti_or(a, "k", 0), lg = r4d_geti_or(a, "log", 0);
if (n <= 0 || R <= 0 || k < R || k > kMaxTaps || lg < 0 || lg > 1 || r4d_numel(al) < n ||
r4d_numel(be) < n || r4d_numel(fu) < k || r4d_numel(fd) < k)
return R4D_NO(RAD_E_SHAPE);
if (!r4d_contig(al) || !r4d_contig(be) || !r4d_contig(fu) || !r4d_contig(fd) || !r4d_contig(cu))
return R4D_NO(RAD_E_STRIDE);
long long rx = 0, ry = 0;
const long long xl = r4d_rows_pitch(x, n, &rx), yl = r4d_rows_pitch(y, n, &ry);
if (xl < 0 || yl < 0) return R4D_NO(RAD_E_STRIDE);
const long long n_seq = r4d_numel(cu) - 1;
if (n_seq <= 0 || ry <= 0 || rx < ry) return R4D_NO(RAD_E_SHAPE);
const int64_t cap = (int64_t)ry * n;
hipLaunchKernelGGL(snake_aa_kernel, dim3(blocks_for(cap)), dim3(kT), 0, (hipStream_t)s,
(const float*)x->data, (const float*)al->data, (const float*)be->data,
(const float*)fu->data, (const float*)fd->data, (const int*)cu->data,
(float*)y->data, (int)n, (int)R, (int)k, (int)lg, (int)n_seq, (int)xl,
(int)yl, cap);
return st_of(hipGetLastError());
}
+298 -36
View File
@@ -6,9 +6,10 @@
// activation and after the residual, as the unfused chain would.
//
// Not gemm_bf16_nt_tiled: that kernel needs K in whole 64-element tiles (a tower MLP's 4304 is 16
// past one) and has no bias. This uses the same block shape (eight waves over an LDS-staged 64-deep
// K tile, next tile prefetched into registers) with a zero-staged K tail, no split-K, and the
// epilogue in the store. Meant for tall activations (thousands of patches).
// past one) and has no bias. Two kernels, both with a zero-staged K tail, no split-K, and the
// epilogue in the store: a 64 x 64 tile with both operands staged through LDS for small grids, and
// for large ones (tall activations, thousands of patches) a 128 x 128 tile that reads the weight
// straight into registers and stages only the activation.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
@@ -50,26 +51,30 @@ __device__ __forceinline__ float ldw(const void* p, uint32_t i) {
// ---------------------------------------------------------------------------- layernorm
// ref_layernorm: y = (x - mean) * rsqrt(var + eps) * w + b, biased variance, two passes (mean, then
// squared deviations); one-pass E[x^2] - E[x]^2 cancels badly when the mean is large relative to
// the spread. One block per row.
template <bool WF32>
// the spread. One block per row. `TX` is the row's element: bf16, or f32 for a residual stream kept
// in f32 (a video decoder's), read as it is; the output is bf16 either way.
__device__ __forceinline__ float ldx(const unsigned short* p, uint32_t i) { return bf2f(p[i]); }
__device__ __forceinline__ float ldx(const float* p, uint32_t i) { return p[i]; }
template <bool WF32, typename TX>
__global__ __launch_bounds__(kThr) void layernorm_kernel(
const unsigned short* __restrict__ x, const void* __restrict__ w, const void* __restrict__ b,
const TX* __restrict__ x, const void* __restrict__ w, const void* __restrict__ b,
unsigned short* __restrict__ y, uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld) {
__shared__ float lds[kThr / 32];
const uint32_t m = blockIdx.x;
const unsigned short* __restrict__ xr = x + (size_t)m * x_ld;
const TX* __restrict__ xr = x + (size_t)m * x_ld;
unsigned short* __restrict__ yr = y + (size_t)m * y_ld;
float s = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += kThr) s += bf2f(xr[i]);
for (uint32_t i = threadIdx.x; i < n; i += kThr) s += ldx(xr, i);
const float mean = block_sum<kThr / 32>(s, lds) / (float)n;
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += kThr) {
const float d = bf2f(xr[i]) - mean;
const float d = ldx(xr, i) - mean;
ss += d * d;
}
const float r = rsqrtf(block_sum<kThr / 32>(ss, lds) / (float)n + eps);
for (uint32_t i = threadIdx.x; i < n; i += kThr) {
float v = (bf2f(xr[i]) - mean) * r * ldw<WF32>(w, i);
float v = (ldx(xr, i) - mean) * r * ldw<WF32>(w, i);
if (b) v += ldw<WF32>(b, i);
yr[i] = f32_to_bf16(v);
}
@@ -170,7 +175,8 @@ __global__ __launch_bounds__(kThr) void grid_embed_aa_kernel(
#define VB_PITCH (VB_BK + 8) // 144-byte LDS rows, as in gemm_bf16_nt_tiled (bank spread)
// TM x TN WMMA tiles per wave, eight waves as 2 x 4: BM = 2*TM*16, BN = 4*TN*16. ACT: 0 none,
// 1 exact GELU, 2 tanh GELU.
// 1 exact GELU, 2 tanh GELU. Serves grids under 32 blocks of 128 x 128 at TM 2, TN 1 (64 x 64);
// larger grids take vit_gemm_wa_kernel below.
template <int TM, int TN, int ACT, bool RES, bool BF32>
__global__ __launch_bounds__(256) void vit_gemm_kernel(
const unsigned short* __restrict__ A, unsigned lda, const unsigned short* __restrict__ W,
@@ -282,6 +288,236 @@ __global__ __launch_bounds__(256) void vit_gemm_kernel(
}
}
// ---------------------------------------------------------------------------- gemm_nt_bias, large grids
//
// 128 weight rows x 128 activation rows a block, eight waves as kVWW (weight) x kVWA
// (activation), a wave kVTW weight tiles x kVTA activation tiles. The weight is the WMMA A operand,
// read from global straight into registers; the activation is the B operand, staged through LDS
// and read by the four waves that share its rows. A lane's accumulator is then eight consecutive
// weight rows of one activation row, so the bias is eight consecutive values and the store (with
// its residual read) is one 16-byte access.
//
// Staging both operands through LDS with a 4 x 2 tile a wave (the kernel above at 128 x 128, which
// this replaces) costs 384 bytes of fragment reads and 128 of stores per bf16 WMMA: all of gfx1201's
// LDS bandwidth, 64 bytes a clock per CU against one bf16 WMMA every 16 clocks per SIMD
// (libr4d/isa/wmmamix.hip). Here it is 256 and 64, and the weight's 128 bytes come through the
// vector cache.
//
// K is relabelled inside a staged tile so that a lane's operand bytes are contiguous: lane half h,
// k step s and element e hold k = 32h + 8s + e of the tile, for both operands alike. That is a
// permutation of K applied to A and B together, so the product is the same sum; its rounding inside
// the WMMA differs from the canonical order in the last bit (rel_l2 ~4e-5 against it, well inside a
// bf16 output). It makes a lane's weight fragments for the tile one 64-byte run of its row, four
// 16-byte loads, and its activation fragment one 16-byte LDS read.
//
// A weight row stride that is a multiple of 8 KiB (K = 4096 or 8192) puts all sixteen rows a
// fragment load touches in one vector-cache set, and every load refetches them. The block's first K
// tile is therefore rotated by its grid position, which spreads the blocks resident at once over
// the K columns: +5% at K 8192, -1% at K 2048 (noise-level), the summation order changing with it.
// The real fix is a weight layout without the stride (a padded row reached 139 TFLOP/s at K 8192
// against 115 here), which needs a layout hook.
//
// Measured at the video decoder's shapes (M 25158, 300 W; the kernel above 93-98 TFLOP/s): this
// tile 133-137 at K 2048, 115 at K 8192. Rejected: 2 x 4 waves of 4 weight x 2 activation tiles
// (spills, -20%); 2 x 2 waves of 4 x 4 tiles at a 32-wide K tile (-22%: half-line weight loads,
// twice the barriers); 4 x 1 waves of 2 x 8 at a 32-wide K tile (-8%); eight waves a SIMD at a
// 32-wide K tile (-4%). kVGroup 1, 2, 4 and 16 are within 2% of 8 except at N 16384 (-9, -5, -3
// and -3%); 32 is 5-15% slower. The kernel above with the grouped raster: +3% at N 16384, -2% at
// K 8192. A uniform block base and 32-bit lane offsets for the loads: neutral. The weight through
// raw buffer loads: +1% at K 2048 and +4% at K 8192, but the same loads cost the fp8 prefill tile
// 20%, so neither tile uses them. The weight's loads nontemporal: -25..-50%.
constexpr uint32_t kVTW = 2, kVTA = 4, kVWW = 4, kVWA = 2;
constexpr uint32_t kVBN = kVWW * kVTW * 16, kVBM = kVWA * kVTA * 16; // weight x activation rows
constexpr uint32_t kVThreads = kVWW * kVWA * 32;
constexpr uint32_t kVFK = 64; // K elements a staged tile
constexpr uint32_t kVPB = kVFK * 2 + 16; // LDS row pitch, bytes
constexpr uint32_t kVCPR = kVFK * 2 / 16; // 16-byte chunks a row
constexpr uint32_t kVSPT = kVBM * kVCPR / kVThreads; // chunks a thread stages
constexpr uint32_t kVWC = kVFK / 16; // a lane's weight chunks a tile
// Activation bands per raster group; see gemm_8a8_prefill_kernel (r4d_gemm_fp8a8.hip).
constexpr uint32_t kVGroup = 8;
static_assert(kVBM * kVCPR % kVThreads == 0, "whole chunks a thread");
// The store's three roundings, libref's order: the biased product, the activation, the residual.
template <int ACT, bool RES>
__device__ __forceinline__ unsigned short vit_finish(float acc, float bv, unsigned short r) {
unsigned short t = f32_to_bf16(acc + bv);
if constexpr (ACT == 1) t = f32_to_bf16(gelu_erf(bf2f(t)));
if constexpr (ACT == 2) t = f32_to_bf16(gelu_tanh(bf2f(t)));
if constexpr (RES) t = f32_to_bf16(bf2f(r) + bf2f(t));
return t;
}
/* `vec` (host-checked): C, R and the bias take 16-byte accesses at every eight-column boundary. */
template <int ACT, bool RES, bool BF32>
__global__ __launch_bounds__(kVThreads) R4D_WAVES(6) void vit_gemm_wa_kernel(
const unsigned short* __restrict__ A, unsigned lda, const unsigned short* __restrict__ W,
unsigned ldw_, const void* __restrict__ bias, const unsigned short* R, unsigned ldr,
unsigned short* C, unsigned ldc, int M, int K, int N, unsigned vec) {
typedef r4d_u32x4 U4;
// Double-buffered: one barrier a staged tile, which publishes it.
__shared__ __attribute__((aligned(16))) unsigned char s_a[2][kVBM * kVPB];
const uint32_t tid = threadIdx.x, lane = tid & 31u;
// Uniform per wave, and through readfirstlane known so, so what derives from it stays scalar.
const uint32_t wave = __builtin_amdgcn_readfirstlane(tid >> 5);
const uint32_t ww = wave % kVWW, wa = wave / kVWW;
// Grouped raster, as in gemm_8a8_prefill_kernel: kVGroup activation bands sweep N together.
uint32_t bm = blockIdx.x, bn = blockIdx.y;
if (gridDim.x > kVGroup) {
const uint32_t per = kVGroup * gridDim.y;
const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x;
const uint32_t first = (lin / per) * kVGroup, r = lin % per;
const uint32_t gm = min(gridDim.x - first, kVGroup);
bm = first + r % gm;
bn = r / gm;
}
const uint32_t m0 = bm * kVBM, n0 = bn * kVBN;
// Staging: eight consecutive threads cover a row's 128 bytes, so a load is whole cachelines.
// Rows past M re-read row M-1; nothing past M is stored.
const unsigned char* asrc[kVSPT];
uint32_t adst[kVSPT], aoff[kVSPT];
#pragma unroll
for (uint32_t i = 0; i < kVSPT; ++i) {
const uint32_t c = tid + kVThreads * i, r = c / kVCPR, ch = c % kVCPR;
asrc[i] = (const unsigned char*)(A + (size_t)min(m0 + r, (uint32_t)M - 1u) * lda);
aoff[i] = ch * 8u; // elements into the tile
adst[i] = r * kVPB + ch * 16u;
}
// Weight: lane row (l & 15) of each tile, elements [32h, 32h + 32) of the staged tile. Rows past
// N re-read row N-1; nothing past N is stored.
const unsigned short* wsrc[kVTW];
#pragma unroll
for (uint32_t i = 0; i < kVTW; ++i)
wsrc[i] = W + (size_t)min(n0 + (ww * kVTW + i) * 16u + (lane & 15u), (uint32_t)N - 1u) * ldw_ +
(lane >> 4) * (kVFK / 2u);
// This lane's activation fragment row and half in the staged tile.
const uint32_t frow = (wa * kVTA * 16u + (lane & 15u)) * kVPB + (lane >> 4) * kVFK;
v8f acc[kVTW][kVTA];
#pragma unroll
for (uint32_t i = 0; i < kVTW; ++i)
#pragma unroll
for (uint32_t j = 0; j < kVTA; ++j) acc[i][j] = (v8f)(0.f);
/* Four k steps of one staged tile: the weight from `cur`, the activation from LDS. */
auto mma_tile = [&](const unsigned char* sa, const U4 (&cur)[kVTW][kVWC]) {
#pragma unroll
for (uint32_t s = 0; s < kVWC; ++s) {
v8bf bfr[kVTA];
#pragma unroll
for (uint32_t j = 0; j < kVTA; ++j)
bfr[j] = __builtin_bit_cast(v8bf, *(const U4*)(sa + frow + j * 16u * kVPB + s * 16u));
#pragma unroll
for (uint32_t i = 0; i < kVTW; ++i) {
const v8bf af = __builtin_bit_cast(v8bf, cur[i][s]);
#pragma unroll
for (uint32_t j = 0; j < kVTA; ++j) acc[i][j] = mma(af, bfr[j], acc[i][j]);
}
}
};
// Whole tiles in a rotated order, then the K tail (K is a multiple of 8, so a 16-byte chunk
// is wholly inside or wholly past K) staged with zeros.
const uint32_t nfull = (uint32_t)K / kVFK;
if (nfull > 0u) {
const uint32_t t0 = (bm + bn) % nfull;
auto kt = [&](uint32_t t) { const uint32_t u = t0 + t; return (u >= nfull ? u - nfull : u) * kVFK; };
U4 pa[kVSPT], w0[kVTW][kVWC], w1[kVTW][kVWC];
/* Every load is issued unconditionally (the last tile's prefetch re-reads the last tile),
* so the loop has no branch and its waits count exactly. */
auto load = [&](uint32_t k0, U4 (&w)[kVTW][kVWC]) {
#pragma unroll
for (uint32_t i = 0; i < kVSPT; ++i) pa[i] = *(const U4*)(asrc[i] + (size_t)(k0 + aoff[i]) * 2u);
#pragma unroll
for (uint32_t i = 0; i < kVTW; ++i)
#pragma unroll
for (uint32_t c = 0; c < kVWC; ++c) w[i][c] = *(const U4*)(wsrc[i] + k0 + c * 8u);
};
auto tile = [&](uint32_t t, uint32_t buf, U4 (&cur)[kVTW][kVWC], U4 (&nxt)[kVTW][kVWC]) {
#pragma unroll
for (uint32_t i = 0; i < kVSPT; ++i) *(U4*)(s_a[buf] + adst[i]) = pa[i];
lds_barrier();
load(kt(min(t + 1u, nfull - 1u)), nxt);
mma_tile(s_a[buf], cur);
};
load(kt(0), w0);
uint32_t t = 0;
for (; t + 1u < nfull; t += 2u) {
tile(t, 0, w0, w1);
tile(t + 1u, 1, w1, w0);
}
if (t < nfull) tile(t, 0, w0, w1);
}
if ((uint32_t)K % kVFK) {
// The buffer the last whole tile did not use, last read two tiles back.
unsigned char* const sa = s_a[nfull % 2u];
const uint32_t k0 = nfull * kVFK;
const U4 zero = (U4)(0u);
#pragma unroll
for (uint32_t i = 0; i < kVSPT; ++i)
*(U4*)(sa + adst[i]) = k0 + aoff[i] < (uint32_t)K
? *(const U4*)(asrc[i] + (size_t)(k0 + aoff[i]) * 2u) : zero;
U4 w[kVTW][kVWC];
#pragma unroll
for (uint32_t i = 0; i < kVTW; ++i)
#pragma unroll
for (uint32_t c = 0; c < kVWC; ++c)
w[i][c] = k0 + (lane >> 4) * (kVFK / 2u) + c * 8u < (uint32_t)K
? *(const U4*)(wsrc[i] + k0 + c * 8u) : zero;
lds_barrier();
mma_tile(sa, w);
}
// D is [weight row][activation row]: eight consecutive columns of one C row a lane a tile.
// The residual is read by the thread that stores the same element, so R may alias C.
#pragma unroll
for (uint32_t i = 0; i < kVTW; ++i)
#pragma unroll
for (uint32_t j = 0; j < kVTA; ++j) {
const uint32_t m = m0 + (wa * kVTA + j) * 16u + (lane & 15u);
const uint32_t n = n0 + (ww * kVTW + i) * 16u + (lane >> 4) * 8u;
if (m >= (uint32_t)M) 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)vit_finish<ACT, RES>(v[e], bv[e], (unsigned short)rr[e / 2]) |
((uint32_t)vit_finish<ACT, 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 unsigned short r = RES ? R[(size_t)m * ldr + n + e] : (unsigned short)0;
C[(size_t)m * ldc + n + e] = vit_finish<ACT, RES>(v[e], ldw<BF32>(bias, n + e), r);
}
}
}
}
} // namespace
// ============================================================== the plugin ABI entry points
@@ -295,7 +531,9 @@ extern "C" int r4d_rad_layernorm(const RadArgs* a, RadStream stream) {
const RadTensor* b = r4d_opt(a, LN_B);
const RadTensor* y = r4d_opt(a, LN_Y);
if (!x || !w || !y) return R4D_NO(RAD_E_INVAL);
if (x->dtype != RAD_BF16 || y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
/* The row bf16 or f32, the output bf16. */
if ((x->dtype != RAD_BF16 && x->dtype != RAD_F32) || y->dtype != RAD_BF16)
return R4D_NO(RAD_E_DTYPE);
/* Gain and bias share one dtype, f32 or bf16. */
if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if (b && b->dtype != w->dtype) return R4D_NO(RAD_E_DTYPE);
@@ -309,14 +547,17 @@ extern "C" int r4d_rad_layernorm(const RadArgs* a, RadStream stream) {
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
const float eps = (float)r4d_getf(a, "eps", 1e-5);
if (w->dtype == RAD_F32)
return R4D_EMIT(stream, layernorm_kernel<true>, dim3((uint32_t)M), dim3(kThr), 0,
(const unsigned short*)r4d_p(x), r4d_p(w), r4d_p(b),
(unsigned short*)r4d_wp(y), (uint32_t)n, eps, (uint32_t)x_ld,
(uint32_t)y_ld);
return R4D_EMIT(stream, layernorm_kernel<false>, dim3((uint32_t)M), dim3(kThr), 0,
(const unsigned short*)r4d_p(x), r4d_p(w), r4d_p(b),
(unsigned short*)r4d_wp(y), (uint32_t)n, eps, (uint32_t)x_ld, (uint32_t)y_ld);
#define R4D_LN(WF, TX) \
return R4D_EMIT(stream, (layernorm_kernel<WF, TX>), dim3((uint32_t)M), dim3(kThr), 0, \
(const TX*)r4d_p(x), r4d_p(w), r4d_p(b), (unsigned short*)r4d_wp(y), \
(uint32_t)n, eps, (uint32_t)x_ld, (uint32_t)y_ld)
if (x->dtype == RAD_F32) {
if (w->dtype == RAD_F32) R4D_LN(true, float);
R4D_LN(false, float);
}
if (w->dtype == RAD_F32) R4D_LN(true, unsigned short);
R4D_LN(false, unsigned short);
#undef R4D_LN
}
/* ------------------------------------------------------------------ grid_embed */
@@ -421,32 +662,53 @@ extern "C" int r4d_rad_gemm_nt_bias(const RadArgs* a, RadStream stream) {
}
const bool res = R != nullptr, bf32 = B->dtype == RAD_F32;
/* The large tile once its grid reaches 32 workgroups, as gemm_bf16_nt_tiled chooses. */
/* The 128 x 128 kernel once its grid reaches 32 workgroups, as gemm_bf16_nt_tiled chooses;
* below that the 64 x 64 tile, whose four times the blocks fill more of the card. */
const long long g128 = ((N + 127) / 128) * ((M + 127) / 128);
const bool big = g128 >= 32;
const int bt = big ? 128 : 64;
const dim3 grid((unsigned)((N + bt - 1) / bt), (unsigned)((M + bt - 1) / bt)), block(256);
auto Ap = (const unsigned short*)r4d_p(A);
auto Wp = (const unsigned short*)r4d_p(W);
auto Rp = (const unsigned short*)r4d_p(R);
auto Cp = (unsigned short*)r4d_wp(Y);
const void* Bp = r4d_p(B);
#define VB_L(TM, TN, AC, RS, BF) \
return R4D_EMIT(stream, (vit_gemm_kernel<TM, TN, AC, RS, BF>), grid, block, 0, Ap, \
if (big) {
/* Sixteen-byte stores, residual reads and bias reads at every eight-column boundary. */
const unsigned vec = (ldc % 8) == 0 && r4d_aligned(Cp, 16) && r4d_aligned(Bp, 16) &&
(!res || ((ldr % 8) == 0 && r4d_aligned(Rp, 16)));
const dim3 grid((unsigned)((M + kVBM - 1) / kVBM), (unsigned)((N + kVBN - 1) / kVBN));
#define VB_L(AC, RS, BF) \
return R4D_EMIT(stream, (vit_gemm_wa_kernel<AC, RS, BF>), grid, dim3(kVThreads), 0, Ap, \
(unsigned)lda, Wp, (unsigned)K, Bp, Rp, (unsigned)ldr, Cp, (unsigned)ldc, \
(int)M, (int)K, (int)N, vec)
#define VB_ACT(RS, BF) \
do { \
if (act == 1) VB_L(1, RS, BF); \
if (act == 2) VB_L(2, RS, BF); \
VB_L(0, RS, BF); \
} while (0)
#define VB_RES(BF) \
do { if (res) VB_ACT(true, BF); VB_ACT(false, BF); } while (0)
if (bf32) VB_RES(true);
VB_RES(false);
#undef VB_RES
#undef VB_ACT
#undef VB_L
}
const dim3 grid((unsigned)((N + 63) / 64), (unsigned)((M + 63) / 64)), block(256);
#define VB_L(AC, RS, BF) \
return R4D_EMIT(stream, (vit_gemm_kernel<2, 1, AC, RS, BF>), grid, block, 0, Ap, \
(unsigned)lda, Wp, (unsigned)K, Bp, Rp, (unsigned)ldr, Cp, (unsigned)ldc, \
(int)M, (int)K, \
(int)N)
#define VB_ACT(TM, TN, RS, BF) \
(int)M, (int)K, (int)N)
#define VB_ACT(RS, BF) \
do { \
if (act == 1) VB_L(TM, TN, 1, RS, BF); \
if (act == 2) VB_L(TM, TN, 2, RS, BF); \
VB_L(TM, TN, 0, RS, BF); \
if (act == 1) VB_L(1, RS, BF); \
if (act == 2) VB_L(2, RS, BF); \
VB_L(0, RS, BF); \
} while (0)
#define VB_RES(TM, TN, BF) \
do { if (res) VB_ACT(TM, TN, true, BF); VB_ACT(TM, TN, false, BF); } while (0)
if (big) { if (bf32) VB_RES(4, 2, true); VB_RES(4, 2, false); }
if (bf32) VB_RES(2, 1, true);
VB_RES(2, 1, false);
#define VB_RES(BF) \
do { if (res) VB_ACT(true, BF); VB_ACT(false, BF); } while (0)
if (bf32) VB_RES(true);
VB_RES(false);
#undef VB_RES
#undef VB_ACT
#undef VB_L
+1197
View File
File diff suppressed because it is too large. Load diff