review: apply the Unlimited-OCR code-review findings

The 2a1ca01..f308216 range's 45 review findings (12 performance, 33 quality)
are applied: ABI 23 for the RadBatch append, the fused q|k|v projection, the
batched patch-embed GEMM and pitched layout copies, the sam_attn w-dot hoist
with an alignment-gated vector row path and NaN poisoning for malformed
segments, the fused quick_gelu act, and the R-SWA/scheduler/drafting gates.

Quality items: stale comments corrected, env reads hoisted, the ngram_window
negative refusal, the parts-form chat template instruction, the whitelist
fallback warning, and the segmented R-SWA refusal of the fixed/runtime window
mix.

The 3.2 MB generated resample header becomes a 9.6 MB little-endian blob
(tests/data/golden/uocr_resample_golden.bin) read by a small loader;
resample_golden.py emits and round-trip-verifies it.

One perf-med item (AVX2 bicubic passes/LUT patch staging in the processor) is
left as the follow-up the review itself recommends; the code says why.

Verified: ninja -C build-review -k 0; host ctest 89/89; GPU r4d_selftest
0 failures, kbench/kbench_moe and the card tests pass.
This commit is contained in:
Juup committed 2026-10-20 07:06:18 +00:00
1 parent 1f661bf2e0
commit 859efc7208
35 files changed
+799 -399093

No files matched your search

+7 -3
View File
@@ -28,6 +28,8 @@ __device__ __forceinline__ float act_of(float g) {
if (ACT == 0) return g / (1.0f + expf(-g));
if (ACT == 1) return 0.5f * g * (1.0f + erff(g * 0.70710678118654752f));
if (ACT == 3) return 1.0f / (1.0f + expf(-g));
if (ACT == 4) // quick_gelu: sigmoid of the bf16-rounded 1.702*g, as the unfused mul stores it
return 1.0f / (1.0f + expf(-bf2f(f32_to_bf16(g * bf2f(f32_to_bf16(1.702f))))));
return 0.5f * g * (1.0f + tanhf(0.7978845608028654f * (g + 0.044715f * g * g * g)));
}
@@ -739,11 +741,11 @@ __global__ __launch_bounds__(kLrThreads) void attn_local_rel_kernel(
// ============================================================== launchers
// act: 0 silu, 1 gelu (erf), 2 gelu_tanh, 3 sigmoid.
// act: 0 silu, 1 gelu (erf), 2 gelu_tanh, 3 sigmoid, 4 quick_gelu (sigmoid(bf16(1.702*a))).
extern "C" int r4d_act_mul_bf16(long a, long b, long y, int M, int n, int act, int a_ld, int b_ld,
int y_ld, long stream) {
if (!a || !b || !y) return -1;
if (M <= 0 || n <= 0 || act < 0 || act > 3) return -2;
if (M <= 0 || n <= 0 || act < 0 || act > 4) return -2;
const dim3 grid((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M));
#define R4D_AM(A) \
hipLaunchKernelGGL(act_mul_kernel<A>, grid, dim3(kThreads), 0, (hipStream_t)stream, \
@@ -752,7 +754,8 @@ extern "C" int r4d_act_mul_bf16(long a, long b, long y, int M, int n, int act, i
if (act == 0) R4D_AM(0);
else if (act == 1) R4D_AM(1);
else if (act == 2) R4D_AM(2);
else R4D_AM(3);
else if (act == 3) R4D_AM(3);
else R4D_AM(4);
#undef R4D_AM
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -1033,6 +1036,7 @@ extern "C" int r4d_rad_act_mul(const RadArgs* a, RadStream s) {
else if (act && !std::strcmp(act, "gelu")) ai = 1;
else if (act && !std::strcmp(act, "gelu_tanh")) ai = 2;
else if (act && !std::strcmp(act, "sigmoid")) ai = 3;
else if (act && !std::strcmp(act, "quick_gelu")) ai = 4;
if (ai < 0) 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);
+7 -4
View File
@@ -2694,7 +2694,8 @@ static const RadOpSchema kSchemas[] = {
"op, not gelu, because gated feed-forwards are trained with the tanh form and the "
"unary gelu is the exact erf one."),
SCHEMA("act_mul", pActMul, oBinary,
"y = act(a) * b, the activation (silu, gelu, gelu_tanh) rounded to y's dtype before "
"y = act(a) * b, the activation (silu, gelu, gelu_tanh, sigmoid or quick_gelu) rounded "
"to y's dtype before "
"the product: silu_mul with its two halves in two operands."),
SCHEMA("seg_mean", pSegMean, oSegMean,
"Row s of y is the mean of x's rows [cu_seqlens[s], cu_seqlens[s+1]), summed in f64 "
@@ -3797,9 +3798,8 @@ static const RadConstraint cAttnDecodeH128G1Fp8[] = {
static const RadConstraint cAttnDecodeH128G1Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 1), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 64), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};/* KEY RENAME. libr4d writes C_IN("q_dtype","bf16") and C_IN("kv_dtype","bf16"); docs/OPS.md's
* `attn_dense` has one `dtype` because nothing about a dense bf16 tower is mixed-precision. The
* predicate -- "bf16, and nothing else" -- is unchanged. */
};
/* Two queries per KV head at head_dim 128 (Qwen3-1.7B, Qwen3-ASR's decoder): the gqa8 pair's
* constraints with the ratio and the decode verify width changed together. A decode workgroup
* holds 64 (query, head) rows, so q_len <= 32 at gqa 2. */
@@ -3862,6 +3862,9 @@ static const RadConstraint cCastNarrow[] = {
* bidirectional with any window, or a text encoder's causal prompt. gqa 1 at 256 and 512 is
* attn_dense_small_h256's and the wide kernel's. */
/* Causal or not at head_dim 64: a vision tower's heads, and a codec's sliding causal layers. */
/* KEY RENAME. libr4d writes C_IN("q_dtype","bf16") and C_IN("kv_dtype","bf16"); docs/OPS.md's
* `attn_dense` has one `dtype` because nothing about a dense bf16 tower is mixed-precision. The
* predicate -- "bf16, and nothing else" -- is unchanged. */
static const RadConstraint cAttnDenseH64[] = {
C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"),
};
+148 -17
View File
@@ -36,6 +36,11 @@ namespace {
constexpr uint32_t kThreads = 128;
constexpr float kLog2e = 1.4426950408889634f;
/* Row loads stay scalar uint16: the operand contract allows any row pitch (the tower's q/k/v are
* column slices of one fused projection, and a tower may pad rows), so a 16-byte bf16x8 read
* would be misaligned for a pitch that is not a multiple of 8 elements. The register diet is the
* w-dot hoist below, not the load width. */
/* q . row(d) of a rel_pos table as the reference resized it to `want` rows: linear interpolation
* between the two source rows at align_corners=False's coordinate, clamped at the edges. With
* rows == want the source is row d itself (f == 0), so the direct read is unchanged bit for bit. */
@@ -65,8 +70,88 @@ __device__ inline float tab_dot(const uint16_t* __restrict__ tab, int rows, int
return s;
}
template <int HD>
__global__ __launch_bounds__(kThreads) void sam_attn_kernel(
/* Eight bf16 of a q/k/v/out row as one 16-byte uint4. VEC is only instantiated when the caller
* proved every involved pointer is 16-byte aligned and every row pitch a multiple of 8 elements
* (launch_sam_attn); otherwise the scalar uint16 path below runs, because the operand contract
* allows any pitch (the tower's q/k/v are column slices and may carry a filler column). The
* element order is the scalar order, so both paths produce bit-identical dots. */
__device__ inline void bf16x8_to_f32(uint4 u, float* f) {
const unsigned* w = (const unsigned*)&u;
#pragma unroll
for (int i = 0; i < 4; ++i) {
f[2 * i] = bf16_to_f32((uint16_t)(w[i] & 0xffffu));
f[2 * i + 1] = bf16_to_f32((uint16_t)(w[i] >> 16));
}
}
template <bool VEC, int HD>
__device__ inline void ld_row(const uint16_t* p, float* f) {
if (VEC) {
const uint4* u = (const uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) bf16x8_to_f32(u[c8], f + c8 * 8);
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) f[c] = bf16_to_f32(p[c]);
}
}
template <bool VEC, int HD>
__device__ inline void st_row(uint16_t* p, const float* f) {
if (VEC) {
uint4 u[HD / 8];
uint16_t* b = (uint16_t*)u;
#pragma unroll
for (int c = 0; c < HD; ++c) b[c] = f32_to_bf16(f[c]);
uint4* o = (uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) o[c8] = u[c8];
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) p[c] = f32_to_bf16(f[c]);
}
}
template <bool VEC, int HD>
__device__ inline float dot_row(const uint16_t* p, const float* qf) {
float s = 0.0f;
if (VEC) {
const uint4* u = (const uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) {
const unsigned* w = (const unsigned*)&u[c8];
#pragma unroll
for (int i = 0; i < 4; ++i) {
s += qf[c8 * 8 + 2 * i] * bf16_to_f32((uint16_t)(w[i] & 0xffffu));
s += qf[c8 * 8 + 2 * i + 1] * bf16_to_f32((uint16_t)(w[i] >> 16));
}
}
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) s += qf[c] * bf16_to_f32(p[c]);
}
return s;
}
template <bool VEC, int HD>
__device__ inline void axpy_row(float* acc, const uint16_t* p, float pv) {
if (VEC) {
const uint4* u = (const uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) {
float f8[8];
bf16x8_to_f32(u[c8], f8);
#pragma unroll
for (int i = 0; i < 8; ++i) acc[c8 * 8 + i] += pv * f8[i];
}
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) acc[c] += pv * bf16_to_f32(p[c]);
}
}
template <int HD, bool VEC>
__device__ inline void sam_attn_body(
const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, const uint16_t* __restrict__ rh,
@@ -82,7 +167,18 @@ __global__ __launch_bounds__(kThreads) void sam_attn_kernel(
const int seq = b;
const int s0 = cu[seq];
if (cu[seq + 1] - s0 != gh * gw) return; // a segment is exactly one grid
if (cu[seq + 1] - s0 != gh * gw) {
// A segment that is not one grid is a tower bug, not a shape: the shim pre-checks the
// row count against the segment count, and this is the device-side guard. Write NaN over
// the segment's rows (the vit kernel's poison convention) so the corruption reaches the
// consumer -- a silent return would pass a garbage plane on as success.
const int n = cu[seq + 1] - s0;
for (int r = (int)threadIdx.x; r < n; r += (int)kThreads) {
uint16_t* op = go + (size_t)(s0 + r) * (size_t)o_ld + (size_t)head * HD;
for (int c = 0; c < HD; ++c) op[c] = (uint16_t)0x7fc0u; // bf16 NaN, as vit poisons
}
return;
}
const int keys = th * tw;
for (int r = (int)threadIdx.x; r < keys; r += (int)kThreads) {
@@ -93,21 +189,31 @@ __global__ __launch_bounds__(kThreads) void sam_attn_kernel(
const size_t qrow = (size_t)(s0 + ih * gw + iw);
const uint16_t* qp = gq + qrow * (size_t)q_ld + (size_t)head * HD;
float qf[HD];
#pragma unroll
for (int c = 0; c < HD; ++c) qf[c] = bf16_to_f32(qp[c]);
ld_row<VEC, HD>(qp, qf);
float acc[HD];
#pragma unroll
for (int c = 0; c < HD; ++c) acc[c] = 0.0f;
float m = -INFINITY, l = 0.0f;
/* The w rel-pos dots depend on (lw, jw) only: computed once for the query row when the
* tile is narrow (the windowed tiles are 14 wide), recomputed per key otherwise (a
* whole-grid tile of 64 columns would cost more registers than the dots save). */
float wr[16];
const bool wr_hoist = tw <= 16;
if (wr_hoist)
for (int jw = 0; jw < tw; ++jw)
wr[jw] = tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1, qf);
for (int jh = 0; jh < th; ++jh) {
const float hr = tab_dot<HD>(rh, rh_rows, 2 * th - 1, lh - jh + th - 1, qf);
const int kh = ty * th + jh;
const bool hreal = kh < gh;
for (int jw = 0; jw < tw; ++jw) {
float s = hr + tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1, qf);
float s = hr + (wr_hoist ? wr[jw]
: tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1,
qf));
const int kw = tx * tw + jw;
const bool real = hreal && kw < gw;
@@ -115,9 +221,7 @@ __global__ __launch_bounds__(kThreads) void sam_attn_kernel(
if (real) {
const size_t krow = (size_t)(s0 + kh * gw + kw);
const uint16_t* kp = gk + krow * (size_t)k_ld + (size_t)head * HD;
float d = 0.0f;
#pragma unroll
for (int c = 0; c < HD; ++c) d += qf[c] * bf16_to_f32(kp[c]);
const float d = dot_row<VEC, HD>(kp, qf);
s += scale * d;
vp = gv + krow * (size_t)v_ld + (size_t)head * HD;
}
@@ -132,20 +236,34 @@ __global__ __launch_bounds__(kThreads) void sam_attn_kernel(
}
const float p = ex2((s - m) * kLog2e);
l += p;
if (real) {
#pragma unroll
for (int c = 0; c < HD; ++c) acc[c] += p * bf16_to_f32(vp[c]);
}
if (real) axpy_row<VEC, HD>(acc, vp, p);
}
}
const float inv = l > 0.0f ? 1.0f / l : 0.0f;
uint16_t* op = go + qrow * (size_t)o_ld + (size_t)head * HD;
#pragma unroll
for (int c = 0; c < HD; ++c) op[c] = f32_to_bf16(acc[c] * inv);
for (int c = 0; c < HD; ++c) acc[c] *= inv;
st_row<VEC, HD>(op, acc);
}
}
template <int HD>
__global__ __launch_bounds__(kThreads) void sam_attn_kernel(
const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, const uint16_t* __restrict__ rh,
const uint16_t* __restrict__ rw, int rh_rows, int rw_rows,
int q_ld, int k_ld, int v_ld, int o_ld, int nhead, int gh, int gw, int th, int tw,
int nth, int ntw, int vec_rows, float scale) {
if (vec_rows)
sam_attn_body<HD, true>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, th, tw, nth, ntw, scale);
else
sam_attn_body<HD, false>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, th, tw, nth, ntw, scale);
}
int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uint16_t* o,
const int* cu, const uint16_t* rh, const uint16_t* rw,
int rh_rows, int rw_rows,
@@ -155,9 +273,16 @@ int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uin
const int nth = (gh + th - 1) / th, ntw = (gw + tw - 1) / tw;
const size_t blocks = (size_t)nseq * nth * ntw * nhead;
if (blocks == 0 || blocks > 0x7fffffff) return R4D_NO(RAD_E_SHAPE);
/* The 16-byte row loads are legal only when every q/k/v/out row starts on a 16-byte
* boundary: all four bases aligned, every row pitch a multiple of 8 bf16. The selftest's
* padded pitch and a slice with a filler column both fail this and take the scalar path. */
const uintptr_t addr_bits = (uintptr_t)q | (uintptr_t)k | (uintptr_t)v | (uintptr_t)o;
const bool vec_rows = (addr_bits & 15u) == 0 &&
((q_ld | k_ld | v_ld | o_ld) & 7) == 0;
hipLaunchKernelGGL((sam_attn_kernel<64>), dim3((uint32_t)blocks), dim3(kThreads), 0,
(hipStream_t)stream, q, k, v, o, cu, rh, rw, rh_rows, rw_rows,
q_ld, k_ld, v_ld, o_ld, nhead, gh, gw, th, tw, nth, ntw, scale);
q_ld, k_ld, v_ld, o_ld, nhead, gh, gw, th, tw, nth, ntw,
vec_rows ? 1 : 0, scale);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
@@ -167,8 +292,10 @@ int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uin
//
// The shim checks what the kernel assumes: bf16 operands, rank 2 with dense columns and any row
// pitch (the tower's q/k/v are the three column slices of one fused projection), an i32 cu with one
// entry a segment plus the terminator, tables of exactly 2*tile-1 rows, head_dim 64. The segment
// lengths are the kernel's to check against cu (it cannot be read on the host at issue).
// entry a segment plus the terminator, tables of exactly 2*tile-1 rows, head_dim 64. The shim
// checks the row count against the segment count host-side; per-segment length is the kernel's to
// check, and a malformed segment writes NaN over its rows (the vit kernel's poison convention)
// so the corruption reaches the consumer instead of passing as success.
#define R4D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R4D_NO(_s); } while (0)
@@ -212,6 +339,10 @@ extern "C" int r4d_rad_sam_attn(const RadArgs* a, RadStream s) {
if (cu->dtype != RAD_I32 || !r4d_contig(cu)) return R4D_NO(RAD_E_DTYPE);
const long long nseq = r4d_numel(cu) - 1;
if (nseq < 1) return R4D_NO(RAD_E_SHAPE);
/* The tower declares cu as one segment per grid, so the host-side row count pins the
* segment count. A mismatch is a malformed segment and fails at issue, not on the device
* (the kernel's per-segment guard poisons the visible rows for what this cannot see). */
if (qrows != nseq * gh * gw) return R4D_NO(RAD_E_SHAPE);
// The tables: [2*tile-1, head_dim] when the geometry has its own, else the checkpoint's rows
// (the 127-row global table at a 40 grid), resampled on read.
+24 -7
View File
@@ -18984,10 +18984,12 @@ static void sam_attn_case(const Plugin& pl) {
if (!r) { ok(what, false, "row absent"); return; }
/* tab_rows 0 means "2*tile-1, no resize". The third geometry is the production 40-grid global
* block: the checkpoint's 127-row tables serve the 79 rows that block wants. */
struct Geo { int64_t gh, gw, win, nh, hd, nseq, tab_rows; };
const Geo geos[3] = { { 16, 16, 14, 2, 64, 2, 0 }, { 16, 16, 0, 2, 64, 1, 0 },
{ 40, 40, 0, 2, 64, 1, 127 } };
* block: the checkpoint's 127-row tables serve the 79 rows that block wants. `pad` is the
* filler column in front of the row: 1 exercises any-pitch (scalar) rows, 0 a 16-byte-aligned
* dense pitch, which is what the kernel's uint4 row-load path requires -- both must agree. */
struct Geo { int64_t gh, gw, win, nh, hd, nseq, tab_rows, pad; };
const Geo geos[4] = { { 16, 16, 14, 2, 64, 2, 0, 1 }, { 16, 16, 14, 2, 64, 2, 0, 0 },
{ 16, 16, 0, 2, 64, 1, 0, 1 }, { 40, 40, 0, 2, 64, 1, 127, 1 } };
int64_t checked = 0, bad_total = 0;
float worst = 0.0f;
@@ -18995,8 +18997,9 @@ static void sam_attn_case(const Plugin& pl) {
const int64_t W = g.nh * g.hd, R = g.gh * g.gw, M = g.nseq * R;
const int64_t want = 2 * (g.win > 0 ? g.win : (g.gh > g.gw ? g.gh : g.gw)) - 1;
const int64_t tab = g.tab_rows > 0 ? g.tab_rows : want;
/* One filler column, so the row pitch is W + 1: q/k/v/out are all slices. */
const int64_t ld = W + 1;
/* A filler column gives the row pitch W + 1 (q/k/v/out are all slices); pad 0 keeps the
* dense pitch W, aligned for the vector row path. */
const int64_t ld = W + g.pad;
const float scale = 1.0f / std::sqrt((float)g.hd);
std::vector<uint16_t> q((size_t)(M * ld)), k((size_t)(M * ld)), v((size_t)(M * ld));
@@ -23457,7 +23460,7 @@ static void device_phase(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "act_mul_bf16");
if (!r) ok("act_mul_bf16", false, "row absent");
else
for (const char* act : { "silu", "gelu", "gelu_tanh" }) {
for (const char* act : { "silu", "gelu", "gelu_tanh", "sigmoid", "quick_gelu" }) {
std::vector<RadTensor> ts = { T(nullptr, RAD_BF16, { 5, 645 }),
T(nullptr, RAD_BF16, { 5, 645 }),
T(nullptr, RAD_BF16, { 5, 645 }) };
@@ -23646,6 +23649,20 @@ static void device_phase(const Plugin& pl) {
for (size_t i = 0; i < g.size(); ++i)
want[i] = h_bf16(h_to_bf16(1.0f / (1.0f + std::exp(-g[i])))) * u[i];
check("act_mul_bf16 sigmoid numerics", down(dy, g.size()), want, 1e-2);
/* quick_gelu fuses mul-by-bf16(1.702) + sigmoid: the scale and the activation are
* both rounded to bf16 exactly as the unfused pair stored them. */
std::vector<RadParam> pq = { PI("M", M), PI("n", n), PS("act", "quick_gelu"),
PS("dtype", "bf16") };
if (r) run_case(r, ts, pq);
const float k1702 = h_bf16(h_to_bf16(1.702f));
std::vector<float> wantq(g.size());
for (size_t i = 0; i < g.size(); ++i) {
const float t = h_bf16(h_to_bf16(g[i] * k1702));
const float s = 1.0f / (1.0f + std::exp(-t));
wantq[i] = h_bf16(h_to_bf16(s)) * u[i];
}
check("act_mul_bf16 quick_gelu numerics", down(dy, g.size()), wantq, 1e-2);
}
if (sel("rmsnorm_bf16")) {
const RadKernelInfo* r = find(pl, "rmsnorm_bf16");