Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
c3e32ad
HIP RDNA2: prefill attention on hipBLAS
I-AM-ENGINEER Dec 5, 2026
98bddb1
hip/ffi.rs: LF line endings and "\0" in the symbol lookup, no code ch…
I-AM-ENGINEER Dec 6, 2026
b509c3d
HIP RDNA2: u16 scores in q_to_h, skip the turbo KV cache, a separate …
I-AM-ENGINEER Dec 6, 2026
25b44af
HIP RDNA2: the prefill attention stays on the GEMMs at any depth (the…
I-AM-ENGINEER Dec 6, 2026
8e2c1ea
HIP RDNA2: batched MoE rounds on GemmStridedBatchedEx
I-AM-ENGINEER Dec 5, 2026
e6548fc
HIP RDNA2: gemm_grouped in the Backend impl (prefill calls it), a dot…
I-AM-ENGINEER Dec 6, 2026
c9cb5ee
HIP RDNA2: u16 expert tiles (the CUDA build compiles kernels.cu too)
I-AM-ENGINEER Dec 6, 2026
18a4003
HIP RDNA2: f2h for the expert tiles' stores (a u16 tile takes the f16…
I-AM-ENGINEER Dec 6, 2026
4bce3dc
HIP RDNA2: the experts retry on the dot2 kernel when hipBLAS fails be…
I-AM-ENGINEER Dec 6, 2026
63071b0
HIP RDNA2: size the expert mailbox in u64 slots, and clear the partia…
I-AM-ENGINEER Dec 6, 2026
d3e91c1
HIP RDNA2: the expert rounds leave int8-typed weights to the int8 GEMM
I-AM-ENGINEER Dec 6, 2026
52f9d98
HIP RDNA2: dense prefill projections on GemmEx
I-AM-ENGINEER Dec 5, 2026
b7d2493
HIP RDNA2: u16 dense tiles (the CUDA build compiles kernels.cu too)
I-AM-ENGINEER Dec 6, 2026
89ad3ee
HIP RDNA2: the grouped path asks for the strides the gather and scatt…
I-AM-ENGINEER Dec 6, 2026
70a132b
HIP RDNA2: the dense path rejects MOE_GATE_X instead of dropping it
I-AM-ENGINEER Dec 6, 2026
edd130a
HIP RDNA2: the dense path leaves int8-typed weights to the int8 GEMM
I-AM-ENGINEER Dec 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,15 @@ pub trait Backend: Send {
/// words a row, rows up to `t` rounded up to 64; see `qsa_select`). `qm` 0: no mask. `sink` (0 = none): per-head
/// attention-sink logits. `win` (0 = none): sliding-window width.
fn attn_prefill_m(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize, scale: f32, qm: u64, mw: usize, sink: u64, win: usize) -> anyhow::Result<()>;
fn gemm_grouped(&self, ty: GgmlType, rows: usize, cols: usize, tiles_dev: u64, tiles_host: &[u64],
x: u64, x_stride: usize, n_x: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> {
self.gemm(ty, rows, cols, tiles_dev, tiles_host.len() / 2, x, x_stride, n_x, xrow, y, y_stride, act)
}
#[allow(clippy::too_many_arguments)]
fn attn_prefill_m_at(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, t: usize, nh: usize, nkv: usize, hd: usize,
scale: f32, qm: u64, mw: usize, sink: u64, win: usize, _pos: usize) -> anyhow::Result<()> {
self.attn_prefill_m(q, kc, vc, qg, out, step, t, nh, nkv, hd, scale, qm, mw, sink, win)
}
/// QSA indexer keys (see `Model::qsa`): pool the blocks of 4 positions that the `t` raw keys (rows of 128) at
/// positions step[0] .. complete into `pool` (rows of 128 per block: mean, rms norm with `w`, NEOX rope at the
/// block's first position). `ring`: 4 rows of 128, the raw keys of the incomplete block (row = position % 4).
Expand Down
202 changes: 202 additions & 0 deletions src/cuda/kernels.cu
Original file line number Diff line number Diff line change
Expand Up @@ -6064,6 +6064,208 @@ extern "C" __global__ void moe_combine_seq(float* x, const float* ye, const floa
x[i] += y;
}

extern "C" __global__ void kv_to_h(const u16* kc, const u16* vc, u16* k16, u16* v16, int rows, int n, int hd) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= rows * n / 8) return;
Comment thread
I-AM-ENGINEER marked this conversation as resolved.
Resolved
size_t off = (size_t)(i / (hd / 8)) * hd + (i % (hd / 8)) * 8;
unsigned o[4];
ldkv<K_MODE, 8>(kc, off, hd, o);
*(uint4*)(k16 + off) = *(uint4*)o;
ldkv<V_MODE, 8>(vc, off, hd, o);
*(uint4*)(v16 + off) = *(uint4*)o;
}

extern "C" __global__ void q_to_h(const float* q, u16* out, int n, float scale) {
int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x);
if (i >= n) return;
float4 v = *(const float4*)(q + i);
*(uint2*)(out + i) = make_uint2(h2pack(v.x * scale, v.y * scale), h2pack(v.z * scale, v.w * scale));
}

#if STRATA_HIP
__device__ __forceinline__ float att_exp(float x) {
float y = x * 1.442695041f, r;
asm volatile("v_exp_f32 %0, %1" : "=v"(r) : "0"(y));
return r;
}
#define ATT_EXP(x) att_exp(x)
#else
#define ATT_EXP(x) __expf(x)
#endif

template <bool MASKED>
__device__ __forceinline__ void att_softmax_wave(u16* row, float* inv, int n, int L, const unsigned* mr) {
const int lane = threadIdx.x & 31, nv = L >> 3;
auto bits = [&](int k) { return mr[k >> 7] >> ((k >> 2) & 31); };
float m = -3.402823466e38f;
for (int v = lane; v < nv; v += 32) {
int k = v << 3;
unsigned w = 3u;
if constexpr (MASKED) {
w = bits(k);
if (!(w & 3u)) continue;
}
uint4 x = *(const uint4*)(row + k);
float f[8] = {h2f((u16)x.x), h2f((u16)(x.x >> 16)), h2f((u16)x.y), h2f((u16)(x.y >> 16)),
h2f((u16)x.z), h2f((u16)(x.z >> 16)), h2f((u16)x.w), h2f((u16)(x.w >> 16))};
if (k + 8 <= n) {
#pragma unroll
for (int j = 0; j < 8; j++)
if (w >> (j >> 2) & 1u) m = fmaxf(m, f[j]);
} else {
#pragma unroll
for (int j = 0; j < 8; j++)
if (k + j < n && (w >> (j >> 2) & 1u)) m = fmaxf(m, f[j]);
}
}
for (int k = (nv << 3) + lane; k < n; k += 32)
if (!MASKED || (bits(k) & 1u)) m = fmaxf(m, h2f(row[k]));
#pragma unroll
for (int o = 16; o > 0; o >>= 1) m = fmaxf(m, __shfl_xor_sync(0xffffffffu, m, o));
float sum = 0.f;
for (int v = lane; v < nv; v += 32) {
int k = v << 3;
unsigned w = 3u;
if constexpr (MASKED) {
w = bits(k);
if (!(w & 3u)) { *(uint4*)(row + k) = make_uint4(0u, 0u, 0u, 0u); continue; }
}
uint4 x = *(const uint4*)(row + k);
float f[8] = {h2f((u16)x.x), h2f((u16)(x.x >> 16)), h2f((u16)x.y), h2f((u16)(x.y >> 16)),
h2f((u16)x.z), h2f((u16)(x.z >> 16)), h2f((u16)x.w), h2f((u16)(x.w >> 16))};
unsigned p[4] = {};
if (k + 8 <= n) {
#pragma unroll
for (int j = 0; j < 8; j++) {
float e = (w >> (j >> 2) & 1u) ? ATT_EXP(f[j] - m) : 0.f;
sum += e;
p[j >> 1] |= (unsigned)f2h(e) << (16 * (j & 1));
}
} else {
#pragma unroll
for (int j = 0; j < 8; j++) {
float e = k + j < n && (w >> (j >> 2) & 1u) ? ATT_EXP(f[j] - m) : 0.f;
sum += e;
p[j >> 1] |= (unsigned)f2h(e) << (16 * (j & 1));
}
}
*(uint4*)(row + k) = make_uint4(p[0], p[1], p[2], p[3]);
}
for (int k = (nv << 3) + lane; k < n; k += 32) {
float e = !MASKED || (bits(k) & 1u) ? ATT_EXP(h2f(row[k]) - m) : 0.f;
sum += e;
row[k] = f2h(e);
}
#pragma unroll
for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
if (lane == 0) *inv = sum > 0.f ? 1.f / sum : 0.f;
}

extern "C" __global__ void att_softmax(u16* s, float* inv, int qb, int L, int pos, int q0, int nh, int rows,
const unsigned* qm, int mw) {
int r = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5);
if (r >= rows) return;
int i = r / nh, n = pos + q0 + i + 1;
u16* row = s + (size_t)(r % nh) * qb * L + (size_t)i * L;
if (qm) att_softmax_wave<true>(row, inv + r, n, L, qm + (size_t)(q0 + i) * mw);
else att_softmax_wave<false>(row, inv + r, n, L, 0);
}

extern "C" __global__ void att_scale(float* out, const float* inv, const float* qg, int nh, int hd, int n) {
int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x);
if (i >= n) return;
float4 v = *(float4*)(out + i);
float s = inv[i / hd];
if (qg) {
const float* g = qg + (size_t)(i / (nh * hd)) * nh * 2 * hd + (size_t)((i / hd) % nh) * 2 * hd + hd + i % hd;
v.x *= s * sigmoid(g[0]); v.y *= s * sigmoid(g[1]); v.z *= s * sigmoid(g[2]); v.w *= s * sigmoid(g[3]);
} else {
v.x *= s; v.y *= s; v.z *= s; v.w *= s;
}
*(float4*)(out + i) = v;
}

extern "C" __global__ void blas_scatter(const u16* c, const u64* m0, const u64* cnt, int P, int rows, float* y,
int y_stride, int act, int n) {
int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x);
if (i >= n) return;
int d = i % rows, r = (i / rows) % P, e = i / (P * rows);
if ((u64)r >= cnt[e]) return;
uint2 a = *(const uint2*)(c + i);
float4 v = make_float4(h2f((u16)a.x), h2f((u16)(a.x >> 16)), h2f((u16)a.y), h2f((u16)(a.y >> 16)));
float* yr = y + (size_t)((int)m0[e] + r) * y_stride + d;
yr[0] = act == 0 ? v.x : act == 1 ? silu(yr[0]) * v.x : yr[0] + v.x;
yr[1] = act == 0 ? v.y : act == 1 ? silu(yr[1]) * v.y : yr[1] + v.y;
yr[2] = act == 0 ? v.z : act == 1 ? silu(yr[2]) * v.z : yr[2] + v.z;
yr[3] = act == 0 ? v.w : act == 1 ? silu(yr[3]) * v.w : yr[3] + v.w;
}

#define DEF_DEQUANT_H(T, NAME, SBB) \
extern "C" __global__ void dequant_h_##NAME(const u8* w, u16* out, int cols, float sc) { \
const u8* r = w + blockIdx.x * ROWB(cols, SBB); \
for (int s = threadIdx.x; s < cols / 8; s += blockDim.x) { \
float v[8]; \
deq8<T>(r + (size_t)(s >> 5) * SBB, s & 31, v); \
u16* dst = out + (size_t)blockIdx.x * cols + s * 8; \
for (int i = 0; i < 8; i++) dst[i] = f2h(v[i] * sc); \
} \
} \
\
extern "C" __global__ void dequant_hg_##NAME(const u64* ws, u16* out, int rows, int cols, float sc) { \
const u8* r = (const u8*)ws[blockIdx.x / rows] + (size_t)(blockIdx.x % rows) * ROWB(cols, SBB); \
u16* o = out + (size_t)blockIdx.x * cols; \
for (int s = threadIdx.x; s < cols / 8; s += blockDim.x) { \
float v[8]; \
deq8<T>(r + (size_t)(s >> 5) * SBB, s & 31, v); \
for (int i = 0; i < 8; i++) o[s * 8 + i] = f2h(v[i] * sc); \
} \
}
QTYPES(DEF_DEQUANT_H)

extern "C" __global__ void x_gather_h(const float* x, int x_stride, const int* xrow, int m0, int cnt, int cols,
u16* out) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= cnt * cols) return;
int r = i / cols, c = i % cols;
int row = xrow ? xrow[m0 + r] : m0 + r;
out[(size_t)r * cols + c] = f2h(x[(size_t)row * x_stride + c]);
}

extern "C" __global__ void x_gather_hg(const float* x, int x_stride, const int* xrow, const u64* m0, const u64* cnt,
int P, int cols, int n, u16* out) {
int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x);
if (i >= n) return;
int c = i % cols, r = (i / cols) % P, e = i / (P * cols);
uint2 z = make_uint2(0u, 0u);
if ((u64)r < cnt[e]) {
int row = xrow ? xrow[(int)m0[e] + r] : (int)m0[e] + r;
float4 v = *(const float4*)(x + (size_t)row * x_stride + c);
z = make_uint2((u32)f2h(v.x) | ((u32)f2h(v.y) << 16), (u32)f2h(v.z) | ((u32)f2h(v.w) << 16));
}
*(uint2*)(out + i) = z;
}

extern "C" __global__ void x_to_h(const float* x, int x_stride, int cols, int n, u16* out) {
int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x);
if (i >= n) return;
int c = i % cols, r = i / cols;
float4 v = *(const float4*)(x + (size_t)r * x_stride + c);
*(uint2*)(out + i) = make_uint2((u32)f2h(v.x) | ((u32)f2h(v.y) << 16), (u32)f2h(v.z) | ((u32)f2h(v.w) << 16));
}

extern "C" __global__ void blas_scatter_d(const u16* c, float* y, int y_stride, int rows, int act, int n) {
int i = 4 * (blockIdx.x * blockDim.x + threadIdx.x);
if (i >= n) return;
int d = i % rows, r = i / rows;
uint2 a = *(const uint2*)(c + i);
float4 v = make_float4(h2f((u16)a.x), h2f((u16)(a.x >> 16)), h2f((u16)a.y), h2f((u16)(a.y >> 16)));
float* yr = y + (size_t)r * y_stride + d;
yr[0] = act == 0 ? v.x : act == 1 ? silu(yr[0]) * v.x : yr[0] + v.x;
yr[1] = act == 0 ? v.y : act == 1 ? silu(yr[1]) * v.y : yr[1] + v.y;
yr[2] = act == 0 ? v.z : act == 1 ? silu(yr[2]) * v.z : yr[2] + v.z;
yr[3] = act == 0 ? v.w : act == 1 ? silu(yr[3]) * v.w : yr[3] + v.w;
}

// ---- attention prefill (flash, tensor cores) ----

// grid = (ceil(T / 64), heads), block = 128: warp w owns queries 16w .. 16w + 15 of the tile. Query t (position
Expand Down
9 changes: 5 additions & 4 deletions src/cuda/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -581,12 +581,13 @@ fn kernel_names_with(sm80: bool, dp4a: bool) -> Vec<String> {
let int8_i = move |&&t: &&GgmlType| (sm80 || dp4a) && !t.float_x();
let int8_d = move |&&t: &&GgmlType| sm80 && !t.float_x();
KERNELS.iter().map(|s| s.to_string())
.chain(QTYPES.iter().flat_map(|&t| ["dequant", "gemv", "gemvn", "moe_gemv", "gemm", "gemms", "gemmm"].map(|p| kname(p, t))))
.chain(QTYPES.iter().flat_map(|&t| ["dequant", "dequant_h", "dequant_hg", "gemv", "gemvn", "moe_gemv", "gemm", "gemms", "gemmm"].map(|p| kname(p, t))))
.chain(QTYPES.iter().flat_map(|&t| ["gemv", "gemvn", "moe_gemv"].map(|p| kname(p, t) + "_p")))
.chain(QTYPES.iter().filter(int8_i).flat_map(|&t| [kname("gemmi", t), kname("gemmis", t)]))
.chain(QTYPES.iter().filter(int8_d).map(|&t| kname("gemmd", t)))
.chain([64, 128, 256, 512].iter().flat_map(|h| [format!("attn_decode_{h}"), format!("attn_decode_gqa_{h}")]))
.chain(["attn_decode_gqa4_128".to_string()])
.chain(["kv_to_h", "q_to_h", "att_softmax", "att_scale", "blas_scatter", "x_gather_h", "x_gather_hg", "x_to_h", "blas_scatter_d"].map(String::from))
.collect()
}

Expand Down Expand Up @@ -2415,8 +2416,8 @@ mod tests {
#[test]
fn kernel_names() {
let (sm70, sm80) = (super::kernel_names(false), super::kernel_names(true));
assert_eq!(sm80.len(), 470);
assert_eq!(sm70.len(), 398);
assert_eq!(sm80.len(), 539);
assert_eq!(sm70.len(), 467);
assert!(sm70.iter().all(|n| !n.starts_with("gemmi") && !n.starts_with("gemmd")),
"sm_70 must not load the int8 prefill GEMM: {:?}",
sm70.iter().filter(|n| n.starts_with("gemmi")).collect::<Vec<_>>());
Expand All @@ -2427,7 +2428,7 @@ mod tests {
#[test]
fn kernel_names_tu11x_dp4a() {
let tu11x = super::kernel_names_with(false, true);
assert_eq!(tu11x.len(), 446);
assert_eq!(tu11x.len(), 515);
assert!(tu11x.contains(&"gemmi_q4_k".to_string()));
assert!(tu11x.contains(&"gemmis_q8_0".to_string()));
assert!(tu11x.iter().all(|n| !n.starts_with("gemmd")),
Expand Down
12 changes: 8 additions & 4 deletions src/gpu_model/prefill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -757,7 +757,11 @@ impl GpuModel<'_> {
}
_ => (kc[self.cur].addr(), vc[self.cur].addr()),
};
g.attn_prefill_m(at(l.b), kca, vca, if c.q_gate { at(l.a) } else { 0 }, at(l.d), step, t, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), qm, mw, sink_addr, win)?;
if rows.is_none() {
g.attn_prefill_m_at(at(l.b), kca, vca, if c.q_gate { at(l.a) } else { 0 }, at(l.d), step, t, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), qm, mw, sink_addr, win, self.pos)?;
} else {
g.attn_prefill_m(at(l.b), kca, vca, if c.q_gate { at(l.a) } else { 0 }, at(l.d), step, t, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), qm, mw, sink_addr, win)?;
}
probe(&mut tr, "q", &pf.slab, at(l.a), nh * qs, t)?;
probe(&mut tr, "k", &pf.slab, kk, kv, t)?;
probe(&mut tr, "v", &pf.slab, vv, kv, t)?;
Expand Down Expand Up @@ -1042,14 +1046,14 @@ impl GpuModel<'_> {
for ((_, cp), (gu, downs)) in steps.iter().zip(&spans) {
g.beside(&mut || {
if gu[0].1 > 0 {
g.gemm(mg.ty, mg.rows, mg.cols, tp(gu[0].0), gu[0].1, hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, gate_flags)?;
g.gemm_grouped(mg.ty, mg.rows, mg.cols, tp(gu[0].0), &tiles[2 * gu[0].0..2 * (gu[0].0 + gu[0].1)], hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, gate_flags)?;
gate_flags |= SAME_X;
g.gemm(mu.ty, mu.rows, mu.cols, tp(gu[1].0), gu[1].1, hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, 1 | gate_flags)?;
g.gemm_grouped(mu.ty, mu.rows, mu.cols, tp(gu[1].0), &tiles[2 * gu[1].0..2 * (gu[1].0 + gu[1].1)], hx, ne, t, xrow_d, at(l.ge), c.n_ff_exp, 1 | gate_flags)?;
}
for &((s0, n0), lo, hi) in downs {
let ge = at(l.ge) + (4 * lo * c.n_ff_exp) as u64;
if let Some((s, r)) = rot { g.hadamard(ge, 0, s[1].addr(), 0, ge, c.n_ff_exp, r.block, hi - lo)?; }
g.gemm(md.ty, md.rows, md.cols, tp(s0), n0, at(l.ge) + (4 * lo * c.n_ff_exp) as u64, c.n_ff_exp, hi - lo, 0, at(l.ye) + (4 * lo * ne) as u64, ne, 0)?;
g.gemm_grouped(md.ty, md.rows, md.cols, tp(s0), &tiles[2 * s0..2 * (s0 + n0)], at(l.ge) + (4 * lo * c.n_ff_exp) as u64, c.n_ff_exp, hi - lo, 0, at(l.ye) + (4 * lo * ne) as u64, ne, 0)?;
}
if let Some(j) = *cp { if !pre_staged(j) { copy(j)?; } }
Ok(())
Expand Down
Loading
Loading