diff --git a/src/backend.rs b/src/backend.rs index efbacad0..86b365ba 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -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). diff --git a/src/cuda/kernels.cu b/src/cuda/kernels.cu index 64454c0e..b34f29ae 100644 --- a/src/cuda/kernels.cu +++ b/src/cuda/kernels.cu @@ -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; + size_t off = (size_t)(i / (hd / 8)) * hd + (i % (hd / 8)) * 8; + unsigned o[4]; + ldkv(kc, off, hd, o); + *(uint4*)(k16 + off) = *(uint4*)o; + ldkv(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 +__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(row, inv + r, n, L, qm + (size_t)(q0 + i) * mw); + else att_softmax_wave(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(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(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 diff --git a/src/cuda/mod.rs b/src/cuda/mod.rs index 989c3f11..8b432ca5 100644 --- a/src/cuda/mod.rs +++ b/src/cuda/mod.rs @@ -581,12 +581,13 @@ fn kernel_names_with(sm80: bool, dp4a: bool) -> Vec { 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() } @@ -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::>()); @@ -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")), diff --git a/src/gpu_model/prefill.rs b/src/gpu_model/prefill.rs index c16fa787..eda03a06 100644 --- a/src/gpu_model/prefill.rs +++ b/src/gpu_model/prefill.rs @@ -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)?; @@ -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(()) diff --git a/src/hip/ffi.rs b/src/hip/ffi.rs index 18a5d51e..8b9783f4 100644 --- a/src/hip/ffi.rs +++ b/src/hip/ffi.rs @@ -3,7 +3,7 @@ use anyhow::{Context, bail}; use libloading::Library; -use std::ffi::{CStr, c_char, c_int, c_void}; +use std::ffi::{CStr, c_char, c_int, c_longlong, c_void}; use std::path::PathBuf; use std::sync::OnceLock; @@ -66,6 +66,123 @@ fn candidates(vars: Option, default_suffix: &[&str]) -> Vec { v } +pub const BLAS_OP_N: c_int = 111; +pub const BLAS_OP_T: c_int = 112; +pub const BLAS_R_16F: c_int = 150; +pub const BLAS_R_32F: c_int = 151; +pub const BLAS_COMPUTE_32F: c_int = BLAS_R_32F; +pub const BLAS_GEMM_DEFAULT: c_int = 160; +pub const BLAS_V2_R_16F: c_int = 2; +pub const BLAS_V2_COMPUTE_32F: c_int = 2; + +type GemmBatchedEx = unsafe extern "C" fn(*mut c_void, c_int, c_int, c_int, c_int, c_int, *const c_void, *const c_void, + c_int, c_int, c_longlong, *const c_void, c_int, c_int, c_longlong, *const c_void, + *mut c_void, c_int, c_int, c_longlong, c_int, c_int, c_int) -> c_int; + +type GemmEx = unsafe extern "C" fn(*mut c_void, c_int, c_int, c_int, c_int, c_int, *const c_void, *const c_void, + c_int, c_int, *const c_void, c_int, c_int, *const c_void, *mut c_void, c_int, + c_int, c_int, c_int) -> c_int; + +pub struct Blas { + handle: *mut c_void, + destroy: unsafe extern "C" fn(*mut c_void) -> c_int, + set_stream: unsafe extern "C" fn(*mut c_void, Stream) -> c_int, + gemm_ex: GemmEx, + gemm_ex_v2: Option, + pub gemm_batched: Option, + _lib: &'static Library, +} + +impl Drop for Blas { + fn drop(&mut self) { if !self.handle.is_null() { unsafe { (self.destroy)(self.handle) }; } } +} + +impl Blas { + pub fn open() -> anyhow::Result { + let want = candidates(std::env::var_os("STRATA_HIPBLAS_LIB").map(Into::into), + &["hipblas.dll", "libhipblas.so", "libhipblas.so.7", "libhipblas.so.6"]); + let mut tried = Vec::new(); + for path in &want { + let lib = match unsafe { Library::new(path) } { + Ok(l) => l, + Err(e) => { tried.push(format!("{}: not loadable ({e})", path.display())); continue } + }; + unsafe { + let create: unsafe extern "C" fn(*mut *mut c_void) -> c_int = match Self::sym(&lib, "hipblasCreate") { + Some(f) => f, + None => { tried.push(format!("{}: no hipblasCreate", path.display())); continue } + }; + let Some(set_stream) = Self::sym:: c_int>(&lib, "hipblasSetStream") else { + tried.push(format!("{}: no hipblasSetStream", path.display())); continue + }; + let Some(gemm_ex) = Self::sym::(&lib, "hipblasGemmEx") else { + tried.push(format!("{}: no hipblasGemmEx", path.display())); continue + }; + let Some(destroy) = Self::sym:: c_int>(&lib, "hipblasDestroy") else { + tried.push(format!("{}: no hipblasDestroy", path.display())); continue + }; + let mut handle: *mut c_void = std::ptr::null_mut(); + if create(&mut handle) != 0 || handle.is_null() { + tried.push(format!("{}: hipblasCreate failed", path.display())); continue + } + let gemm_ex_v2 = Self::sym::(&lib, "hipblasGemmEx_v2"); + let gemm_batched = Self::sym::(&lib, "hipblasGemmStridedBatchedEx_v2"); + return Ok(Blas { handle, destroy, set_stream, gemm_ex, gemm_ex_v2, gemm_batched, _lib: Box::leak(Box::new(lib)) }); + } + } + Err(anyhow::anyhow!("no hipblas: {}", tried.join(", "))).context("hipblas init") + } + + pub fn set_stream(&self, stream: Stream) -> anyhow::Result<()> { + let r = unsafe { (self.set_stream)(self.handle, stream) }; + if r != 0 { anyhow::bail!("hipblasSetStream: {r}") } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + pub fn gemm_ex_f16_f32(&self, transa: c_int, transb: c_int, m: usize, n: usize, k: usize, alpha: f32, + a: u64, lda: usize, b: u64, ldb: usize, beta: f32, c: u64, ldc: usize) -> anyhow::Result<()> { + let r = unsafe { (self.gemm_ex)(self.handle, transa, transb, m as c_int, n as c_int, k as c_int, + &alpha as *const f32 as *const c_void, a as *const c_void, BLAS_R_16F, lda as c_int, + b as *const c_void, BLAS_R_16F, ldb as c_int, + &beta as *const f32 as *const c_void, c as *mut c_void, BLAS_R_32F, ldc as c_int, + BLAS_COMPUTE_32F, BLAS_GEMM_DEFAULT) }; + if r != 0 { anyhow::bail!("hipblasGemmEx({m}x{n}x{k}): status {r}") } + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + pub fn gemm_ex_f16_f16(&self, transa: c_int, transb: c_int, m: usize, n: usize, k: usize, alpha: f32, + a: u64, lda: usize, b: u64, ldb: usize, beta: f32, c: u64, ldc: usize) -> anyhow::Result<()> { + let Some(f) = self.gemm_ex_v2 else { anyhow::bail!("hipblasGemmEx_v2 is not exported") }; + let r = unsafe { f(self.handle, transa, transb, m as c_int, n as c_int, k as c_int, + &alpha as *const f32 as *const c_void, a as *const c_void, BLAS_V2_R_16F, lda as c_int, + b as *const c_void, BLAS_V2_R_16F, ldb as c_int, + &beta as *const f32 as *const c_void, c as *mut c_void, BLAS_V2_R_16F, ldc as c_int, + BLAS_V2_COMPUTE_32F, BLAS_GEMM_DEFAULT) }; + if r != 0 { anyhow::bail!("hipblasGemmEx_v2({m}x{n}x{k}): status {r}") } + Ok(()) + } + + pub fn gemm_batched_f16_f16(&self, transa: c_int, transb: c_int, m: usize, n: usize, k: usize, a: u64, lda: usize, sa: i64, + b: u64, ldb: usize, sb: i64, c: u64, ldc: usize, sc: i64, batch: usize) -> anyhow::Result<()> { + let Some(f) = self.gemm_batched else { anyhow::bail!("hipblasGemmStridedBatchedEx_v2 is not exported") }; + let (alpha, beta) = (1.0f32, 0.0f32); + let r = unsafe { f(self.handle, transa, transb, m as c_int, n as c_int, k as c_int, + &alpha as *const f32 as *const c_void, a as *const c_void, BLAS_V2_R_16F, lda as c_int, sa as c_longlong, + b as *const c_void, BLAS_V2_R_16F, ldb as c_int, sb as c_longlong, + &beta as *const f32 as *const c_void, c as *mut c_void, BLAS_V2_R_16F, ldc as c_int, sc as c_longlong, + batch as c_int, BLAS_V2_COMPUTE_32F, BLAS_GEMM_DEFAULT) }; + if r != 0 { anyhow::bail!("hipblasGemmStridedBatchedEx_v2({m}x{n}x{k} x {batch}): status {r}") } + Ok(()) + } + + unsafe fn sym(lib: &Library, name: &str) -> Option { + let s = unsafe { lib.get::(format!("{name}\0").as_bytes()).ok() }?; + Some(*s) + } +} + pub struct Hip { pub init: unsafe extern "C" fn(c_int) -> c_int, pub device_count: unsafe extern "C" fn(*mut c_int) -> c_int, diff --git a/src/hip/mod.rs b/src/hip/mod.rs index cfa7119b..d7bcfc31 100644 --- a/src/hip/mod.rs +++ b/src/hip/mod.rs @@ -80,6 +80,16 @@ pub struct Gpu { /// Pinned staging for large `htod`, used as a ring: the copy returns before its DMA, so the host fills the next /// region while the card reads the previous one (expert streaming in prefill). staging: Mutex, + blas: Option, + att_kv: std::cell::RefCell>, + att_q: std::cell::RefCell>, + att_s: std::cell::RefCell>, + att_inv: std::cell::RefCell>, + blas_w: std::cell::RefCell>, + blas_x: std::cell::RefCell>, + blas_y: std::cell::RefCell>, + blas_idx: std::cell::RefCell>, + moe_plan: std::cell::RefCell, Vec)>>, } // The HIP handles are raw pointers but the runtime is thread-safe for the calls the backend makes, and `Backend` @@ -177,6 +187,245 @@ fn cache_key(src: &str, arch: &str, rtc: &str) -> u64 { } impl Gpu { + + fn blas_buf(&self, cell: &std::cell::RefCell>, bytes: usize) -> anyhow::Result { + let mut b = cell.borrow_mut(); + if b.as_ref().map(|buf| buf.len() < bytes).unwrap_or(true) { + *b = None; + *b = Some(self.alloc(bytes)?); + } + Ok(b.as_ref().unwrap().addr()) + } + + fn gemm_grouped_blas(&self, ty: GgmlType, rows: usize, cols: usize, tiles_host: &[u64], + x: u64, x_stride: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + let blas = self.blas.as_ref().unwrap(); + let mut ex: Vec<(u64, usize, usize)> = Vec::new(); + let mut i = 0; + while i * 2 < tiles_host.len() { + let (w, m0) = (tiles_host[2 * i], (tiles_host[2 * i + 1] as u32) as usize); + let mut cnt = (tiles_host[2 * i + 1] >> 32) as u32 as usize; + i += 1; + while i * 2 < tiles_host.len() && tiles_host[2 * i] == w && (tiles_host[2 * i + 1] as u32) as usize == m0 + cnt { + cnt += (tiles_host[2 * i + 1] >> 32) as u32 as usize; + i += 1; + } + if cnt > 0 { ex.push((w, m0, cnt)); } + } + let worst = ex.iter().map(|e| (e.2 + 15) / 16).sum::(); + if ex.len() >= 2 && worst <= MOE_ITEMS_MAX && *MOE_BATCH_ON && blas.gemm_batched.is_some() { + return self.moe_rounds(blas, ty, rows, cols, &ex, x, x_stride, xrow, y, y_stride, act); + } + let slot = rows * cols; + let most = ex.iter().map(|e| e.2).max().unwrap_or(1); + let w_buf = self.blas_buf(&self.blas_w, slot * 2)?; + let xp = self.blas_buf(&self.blas_x, most * cols * 2)?; + let yp = self.blas_buf(&self.blas_y, most * rows * 4)?; + for (i, &(w, m0, cnt)) in ex.iter().enumerate() { + let one = |g: &Gpu| -> anyhow::Result<()> { + launch!(g, &kname("dequant_h", ty), cfg((rows as u32, 1), 256, 0), w, w_buf, cols as i32, 1.0f32); + launch!(g, "x_gather_h", cfg((((cnt * cols + 255) / 256) as u32, 1), 256, 0), + x, x_stride as i32, xrow, m0 as i32, cnt as i32, cols as i32, xp); + if act == 0 { + blas.gemm_ex_f16_f32(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, cnt, cols, 1.0, w_buf, cols, xp, cols, + 0.0, y + (m0 as u64) * (y_stride as u64) * 4, y_stride)?; + } else { + blas.gemm_ex_f16_f32(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, cnt, cols, 1.0, w_buf, cols, xp, cols, 0.0, yp, rows)?; + launch!(g, "gemm_splitk_sum", cfg((((cnt * rows + 255) / 256) as u32, 1), 256, 0), + yp, 1i32, cnt as i32, rows as i32, y + (m0 as u64) * (y_stride as u64) * 4, y_stride as i32, act); + } + Ok(()) + }; + if let Err(e) = one(self) { + if i > 0 { MOE_PARTIAL.store(true, std::sync::atomic::Ordering::Relaxed); } + return Err(e); + } + } + Ok(()) + } + + fn moe_idx(&self, items: &[(u64, usize, usize, usize)]) -> anyhow::Result { + const WORDS: usize = 3 * MOE_ITEMS_MAX; + const SLOTS: usize = 128; + if self.blas_idx.borrow().is_none() { + let (buf, host) = self.host_mailbox(WORDS * SLOTS * 2)?; + *self.blas_idx.borrow_mut() = Some((buf, host as *mut u64, 0)); + } + let mut b = self.blas_idx.borrow_mut(); + let (buf, host, next) = b.as_mut().unwrap(); + if *next == SLOTS { self.sync()?; *next = 0; } + let n = items.len(); + let p = unsafe { host.add(*next * WORDS) }; + for (i, &(w, m0, cnt, _)) in items.iter().enumerate() { + unsafe { *p.add(i) = w; *p.add(n + i) = m0 as u64; *p.add(2 * n + i) = cnt as u64; } + } + *next += 1; + Ok(buf.addr() + ((*next - 1) * WORDS * 8) as u64) + } + + fn moe_sizes(rows: usize, cols: usize) -> &'static [(usize, f32)] { + if rows < cols { + &[(16, 9.8), (32, 15.9), (48, 27.1), (64, 29.1), (96, 40.6), (384, 47.7), (448, 48.0), (512, 47.0), (768, 70.2), (1536, 123.4)] + } else { + &[(16, 14.3), (32, 16.1), (48, 18.8), (64, 21.8), (192, 20.5), (256, 22.1), (384, 31.5), (640, 47.4), (1024, 71.4)] + } + } + + fn moe_plan(&self, rows: usize, cols: usize, cnt: usize) -> Vec { + let sizes = Self::moe_sizes(rows, cols); + let mut cell = self.moe_plan.borrow_mut(); + let entry = match cell.as_mut() { + Some(e) if e.0 == rows && e.1 == cols => e, + _ => { *cell = Some((rows, cols, vec![0], vec![0.0])); cell.as_mut().unwrap() } + }; + let (_, _, plan, cost) = entry; + for c in cost.len()..=cnt { + let (mut best, mut take) = (f32::INFINITY, sizes[0].0 as u32); + for &(s, k) in sizes { + let total = k + MOE_ITEM_US + if s < c { cost[c - s] } else { 0.0 }; + if total < best { (best, take) = (total, s as u32); } + } + cost.push(best); + plan.push(take); + } + plan.clone() + } + + fn moe_rounds(&self, blas: &ffi::Blas, ty: GgmlType, rows: usize, cols: usize, ex: &[(u64, usize, usize)], + x: u64, x_stride: usize, xrow: u64, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + let plan = self.moe_plan(rows, cols, ex.iter().map(|e| e.2).max().unwrap_or(1)); + let mut items: Vec<(u64, usize, usize, usize)> = Vec::with_capacity(ex.len() * 2); + for &(w, m0, cnt) in ex { + let (mut m0, mut c) = (m0, cnt); + while c > 0 { + let s = (plan[c] as usize).min(c); + items.push((w, m0, s, plan[c] as usize)); + m0 += s; + c -= s; + } + } + items.sort_by_key(|it| it.3); + let n = items.len(); + anyhow::ensure!(n <= MOE_ITEMS_MAX, "moe_rounds: {n} items"); + if *MOE_STATS && MOE_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 200 < 6 { + let mut counts: Vec = ex.iter().map(|e| e.2).collect(); + counts.sort_unstable_by(|a, b| b.cmp(a)); + let slots: usize = ex.iter().map(|e| e.2).sum(); + let us: f32 = items.iter().map(|it| Self::moe_sizes(rows, cols).iter().find(|s| s.0 == it.3).unwrap().1 + MOE_ITEM_US).sum(); + crate::say!("moe stats: {rows}x{cols} experts={} slots={} items={} padded={} about {us:.0} us; top {:?}", + ex.len(), slots, n, items.iter().map(|it| it.3).sum::(), &counts[..counts.len().min(16)]); + } + let idx = self.moe_idx(&items)?; + let (wp, m0p, cntp) = (idx, idx + (8 * n) as u64, idx + (16 * n) as u64); + let w_items = (BLAS_W_BYTES / (rows * cols * 2)).max(1); + let b_max = MOE_BATCH.min(n).min(w_items); + let row_cap = (MOE_C_BYTES / (rows * 2)).max(64); + let round = |i: usize| { + let p = items[i].3; + let mut b = 1; + while i + b < n && b < b_max && items[i + b].3 == p && b < row_cap / p { b += 1; } + (b, p) + }; + let (mut x_cap, mut c_cap) = (0usize, 0usize); + let mut i = 0; + while i < n { + let (b, p) = round(i); + x_cap = x_cap.max(b * p * cols * 2); + c_cap = c_cap.max(b * p * rows * 2); + i += b; + } + let w_buf = self.blas_buf(&self.blas_w, b_max * rows * cols * 2)?; + let xp = self.blas_buf(&self.blas_x, x_cap)?; + let c = self.blas_buf(&self.blas_y, c_cap)?; + let mut i = 0; + while i < n { + let (b, p) = round(i); + let (m0, cnt) = (m0p + (8 * i) as u64, cntp + (8 * i) as u64); + let one = |g: &Gpu| -> anyhow::Result<()> { + launch!(g, &kname("dequant_hg", ty), cfg(((b * rows) as u32, 1), 256, 0), + wp + (8 * i) as u64, w_buf, rows as i32, cols as i32, 1.0f32); + launch!(g, "x_gather_hg", cfg(((b * p * cols / 4).div_ceil(256) as u32, 1), 256, 0), + x, x_stride as i32, xrow, m0, cnt, p as i32, cols as i32, (b * p * cols) as i32, xp); + blas.gemm_batched_f16_f16(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, p, cols, w_buf, cols, (rows * cols) as i64, + xp, cols, (p * cols) as i64, c, rows, (p * rows) as i64, b)?; + launch!(g, "blas_scatter", cfg(((b * p * rows / 4).div_ceil(256) as u32, 1), 256, 0), + c, m0, cnt, p as i32, rows as i32, y, y_stride as i32, act, (b * p * rows) as i32); + Ok(()) + }; + if let Err(e) = one(self) { + if i > 0 { MOE_PARTIAL.store(true, std::sync::atomic::Ordering::Relaxed); } + return Err(e); + } + i += b; + } + Ok(()) + } + fn gemm_dense_blas(&self, w: &GpuTensor, n: usize, x: u64, x_stride: usize, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { + let blas = self.blas.as_ref().unwrap(); + let (rows, cols) = (w.rows, w.cols); + let w16 = self.blas_buf(&self.blas_w, rows * cols * 2)?; + launch!(self, &kname("dequant_h", w.ty), cfg((rows as u32, 1), 256, 0), w.ptr, w16, cols as i32, w.scale); + let step_cap = (BLAS_W_BYTES / (2 * rows.max(cols).max(1))).max(1); + let step = (if rows >= 4096 && n > 4096 { 4096 } else { n }).min(step_cap); + let x16 = self.blas_buf(&self.blas_x, step * cols * 2)?; + let c16 = self.blas_buf(&self.blas_y, step * rows * 2)?; + for n0 in (0..n).step_by(step) { + let b = step.min(n - n0); + let done = (|| -> anyhow::Result<()> { + launch!(self, "x_to_h", cfg(((b * cols / 4).div_ceil(256) as u32, 1), 256, 0), + x + (4 * n0 * x_stride) as u64, x_stride as i32, cols as i32, (b * cols) as i32, x16); + blas.gemm_ex_f16_f16(ffi::BLAS_OP_T, ffi::BLAS_OP_N, rows, b, cols, 1.0, w16, cols, x16, cols, 0.0, c16, rows)?; + launch!(self, "blas_scatter_d", cfg(((b * rows / 4).div_ceil(256) as u32, 1), 256, 0), + c16, y + (4 * n0 * y_stride) as u64, y_stride as i32, rows as i32, act, (b * rows) as i32); + Ok(()) + })(); + if let Err(e) = done { + if n0 > 0 { DENSE_PARTIAL.store(true, std::sync::atomic::Ordering::Relaxed); } + return Err(e); + } + } + Ok(()) + } + + fn attn_prefill_blas(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, t: usize, pos: usize, nh: usize, nkv: usize, hd: usize, + scale: f32, qm: u64, mw: usize) -> anyhow::Result<()> { + let blas = self.blas.as_ref().unwrap(); + let (rows, n) = (pos + t, nkv * hd); + let kv_bytes = rows * n * 2; + let k16 = self.blas_buf(&self.att_kv, 2 * kv_bytes)?; + let v16 = k16 + kv_bytes as u64; + launch!(self, "kv_to_h", cfg(((rows * n / 8).div_ceil(256) as u32, 1), 256, 0), + kc, vc, k16, v16, rows as i32, n as i32, hd as i32); + let q16 = self.blas_buf(&self.att_q, t * nh * hd * 2)?; + launch!(self, "q_to_h", cfg(((t * nh * hd / 4).div_ceil(256) as u32, 1), 256, 0), q, q16, (t * nh * hd) as i32, scale); + let qb = (ATT_S_BYTES / (nh * ((pos + t + 7) & !7) * 2)).clamp(1, ATT_QB).min(t).max(1); + let s = self.blas_buf(&self.att_s, nh * qb * ((pos + t + 7) & !7) * 2)?; + let inv = self.blas_buf(&self.att_inv, t * nh * 4)?; + for q0 in (0..t).step_by(qb) { + let (b, l) = (qb.min(t - q0), pos + q0 + qb.min(t - q0)); + let lp = (l + 7) & !7; + for h in 0..nh { + let sh = s + (h * qb * lp * 2) as u64; + blas.gemm_ex_f16_f16(ffi::BLAS_OP_T, ffi::BLAS_OP_N, l, b, hd, 1.0, + k16 + ((h / (nh / nkv)) * hd * 2) as u64, n, q16 + ((q0 * nh + h) * hd * 2) as u64, nh * hd, + 0.0, sh, lp)?; + } + launch!(self, "att_softmax", cfg(((b * nh).div_ceil(8) as u32, 1), 256, 0), + s, inv + (q0 * nh * 4) as u64, qb as i32, lp as i32, pos as i32, q0 as i32, nh as i32, (b * nh) as i32, + qm, mw as i32); + for h in 0..nh { + let sh = s + (h * qb * lp * 2) as u64; + blas.gemm_ex_f16_f32(ffi::BLAS_OP_N, ffi::BLAS_OP_N, hd, b, l, 1.0, + v16 + ((h / (nh / nkv)) * hd * 2) as u64, n, sh, lp, 0.0, + out + ((q0 * nh + h) * hd * 4) as u64, nh * hd)?; + } + launch!(self, "att_scale", cfg(((b * nh * hd / 4).div_ceil(256) as u32, 1), 256, 0), + out + (q0 * nh * hd * 4) as u64, inv + (q0 * nh * 4) as u64, + if qg == 0 { 0 } else { qg + (q0 * nh * 2 * hd * 4) as u64 }, + nh as i32, hd as i32, (b * nh * hd) as i32); + } + Ok(()) + } pub fn new(device: usize) -> anyhow::Result { let (kv_k_mode, kv_v_mode) = (crate::cuda::kv_k_mode(), crate::cuda::kv_v_mode()); anyhow::ensure!(!((kv_k_mode > 0 || kv_v_mode > 0) && crate::cuda::llama_numerics()), "--kv q8/q4 does not combine with --llama-numerics (its attention reads f16 KV)"); @@ -251,8 +500,13 @@ impl Gpu { let sms = hip.attribute(ffi::ATTR_MULTIPROCESSOR_COUNT, device as i32).unwrap_or(16).max(1) as usize; let wm = hip_wmma && wmma_arch(&arch); let (mla_wmma, idx_wmma) = (wm && std::env::var_os("STRATA_MLA_SIMT").is_none(), wm && std::env::var("STRATA_IDX_WMMA").is_ok_and(|v| v == "1")); + let rdna2 = arch.starts_with("gfx103"); + let blas = (std::env::var("STRATA_HIPBLAS").map(|v| v != "0").unwrap_or(rdna2)) + .then(|| ffi::Blas::open().ok()).flatten() + .filter(|b| b.set_stream(stream).is_ok()); + if blas.is_some() { crate::say!("hipblas: prefill GEMMs run on GemmEx (fp16 in, f32 compute)"); } Ok(Gpu { hip, device, stream, side, marks, next_mark: Default::default(), pinned: Default::default(), beside: Default::default(), beside_lag: Default::default(), fns, arch, kv_mode: if kv_k_mode == kv_v_mode { kv_k_mode } else { 10 }, kv_k_mode, kv_v_mode, flags: ink_flags(), pci, max_smem, sms, mla_wmma, idx_wmma, am: am_buf, - graphs: Mutex::new(HashMap::new()), graph_failed: Default::default(), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging) }) + graphs: Mutex::new(HashMap::new()), graph_failed: Default::default(), fr: Mutex::new((HashMap::new(), Vec::new())), staging: Mutex::new(staging), blas, att_kv: Default::default(), att_q: Default::default(), att_s: Default::default(), att_inv: Default::default(), blas_w: Default::default(), blas_x: Default::default(), blas_y: Default::default(), blas_idx: Default::default(), moe_plan: Default::default() }) } pub fn arch(&self) -> &str { &self.arch } @@ -569,6 +823,26 @@ const GRAPHS_MAX: usize = 32; const RING: usize = 64 << 20; /// Mark events of the copy queue (`Gpu::mark`). const MARKS: usize = 64; + +const ATT_QB: usize = 1024; +const ATT_S_BYTES: usize = 768 << 20; +static ATT_FALLBACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static MOE_FALLBACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static MOE_PARTIAL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +const ATT_DENSE_MAX: usize = 1 << 40; +const BLAS_W_BYTES: usize = 384 << 20; +const MOE_BATCH: usize = 32; +const MOE_C_BYTES: usize = 64 << 20; +const MOE_ITEMS_MAX: usize = 2048; +const MOE_ITEM_US: f32 = 10.0; +const DENSE_MIN: usize = 512; +static DENSE_ON: LazyLock = LazyLock::new(|| std::env::var("STRATA_HIP_DENSE").map(|v| v != "0").unwrap_or(true)); +static DENSE_FALLBACK: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static DENSE_PARTIAL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +static MOE_BATCH_ON: LazyLock = LazyLock::new(|| std::env::var("STRATA_MOE_BATCH").map(|v| v != "0").unwrap_or(true)); +static MOE_STATS: LazyLock = LazyLock::new(|| std::env::var("STRATA_MOE_STATS").is_ok()); +static MOE_CALLS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); const RING_MIN: usize = 256 << 10; fn alloc_raw(hip: &Arc, bytes: usize) -> anyhow::Result { @@ -642,6 +916,31 @@ fn wmma_arch(arch: &str) -> bool { } impl Backend for Gpu { + 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<()> { + let full_act = act; + let (same, act) = (act & SAME_X != 0, act & 3); + let _ = (same, n_x); + let dot2 = |g: &Gpu| g.gemm(ty, rows, cols, tiles_dev, tiles_host.len() / 2, x, x_stride, n_x, xrow, y, y_stride, full_act); + let Some(slot_bytes) = rows.checked_mul(cols).and_then(|n| n.checked_mul(2)) else { return dot2(self) }; + if tiles_host.len() < 2 || cols % 8 != 0 || act > 2 || ty.float_x() || self.blas.is_none() || self.int8_gemm(ty) + || slot_bytes > BLAS_W_BYTES || rows % 4 != 0 || MOE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) + || x_stride % 4 != 0 || y_stride % 4 != 0 || x_stride < cols || y_stride < rows { + return dot2(self); + } + MOE_PARTIAL.store(false, std::sync::atomic::Ordering::Relaxed); + match self.gemm_grouped_blas(ty, rows, cols, tiles_host, x, x_stride, xrow, y, y_stride, act) { + Ok(()) => Ok(()), + Err(e) if MOE_PARTIAL.load(std::sync::atomic::Ordering::Relaxed) => Err(e), + Err(e) => { + if !MOE_FALLBACK.swap(true, std::sync::atomic::Ordering::Relaxed) { + crate::say!("hipblas experts: {e:#}; the dot2 kernel takes over"); + } + dot2(self) + } + } + } + fn name(&self) -> &'static str { "hip" } fn device(&self) -> String { self.hip.device_name(self.device as i32) } @@ -830,7 +1129,24 @@ impl Backend for Gpu { } fn gemm_dense(&self, w: &GpuTensor, n: usize, x: u64, x_stride: usize, y: u64, y_stride: usize, act: i32) -> anyhow::Result<()> { - self.gemm_raw(w.ty, w.rows, w.cols, 0, n.div_ceil(GEMM_BM), w.ptr, n, x, x_stride, n, 0, y, y_stride, act, w.scale) + let (rows, cols) = (w.rows, w.cols); + let weight_ok = rows.checked_mul(cols).and_then(|v| v.checked_mul(2)).is_some_and(|b| b <= BLAS_W_BYTES); + let act_ok = (act & 3) <= 2 && act & !(3 | SAME_X) == 0; + let take = *DENSE_ON && !DENSE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) && !DENSE_PARTIAL.load(std::sync::atomic::Ordering::Relaxed) + && self.blas.is_some() && n >= DENSE_MIN && act_ok && weight_ok && !self.int8_gemm(w.ty) + && w.ty.block_elems() >= 32 && cols % 8 == 0 && rows % 4 == 0 && x_stride % 4 == 0 && y_stride % 4 == 0 + && x_stride >= cols && y_stride >= rows; + if take { + match self.gemm_dense_blas(w, n, x, x_stride, y, y_stride, act & 3) { + Ok(()) => return Ok(()), + Err(e) if DENSE_PARTIAL.load(std::sync::atomic::Ordering::Relaxed) => return Err(e), + Err(e) => { + if !DENSE_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) { crate::say!("hipblas dense GEMM ({} {rows} x {cols}, {n} tokens): {e:#}; the dot2 kernel takes over", w.ty.name()); } + DENSE_FALLBACK.store(true, std::sync::atomic::Ordering::Relaxed); + } + } + } + self.gemm_raw(w.ty, rows, cols, 0, n.div_ceil(GEMM_BM), w.ptr, n, x, x_stride, n, 0, y, y_stride, act, w.scale) } fn int8_gemm(&self, _ty: GgmlType) -> bool { false } @@ -1186,6 +1502,24 @@ impl Backend for Gpu { Ok(()) } + + #[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<()> { + if self.blas.is_some() && !ATT_FALLBACK.load(std::sync::atomic::Ordering::Relaxed) + && self.kv_k_mode < 4 && self.kv_v_mode < 4 + && sink == 0 && win == 0 && hd % 8 == 0 && nh % nkv == 0 && t >= 8 && pos + t <= ATT_DENSE_MAX { + match self.attn_prefill_blas(q, kc, vc, qg, out, t, pos, nh, nkv, hd, scale, qm, mw) { + Ok(()) => return Ok(()), + Err(e) if !ATT_FALLBACK.swap(true, std::sync::atomic::Ordering::Relaxed) => { + crate::say!("hipblas attention: {e:#}; the flash kernel takes over"); + } + Err(_) => {} + } + } + self.attn_prefill_m(q, kc, vc, qg, out, step, t, nh, nkv, hd, scale, qm, mw, sink, win) + } + fn qsa_pool(&self, ik: u64, ring: u64, pool: u64, w: u64, step: u64, t: usize, n_rot: usize, base: f32, eps: f32) -> anyhow::Result<()> { launch!(self, "qsa_pool", cfg(((t / 4 + 1) as u32, 1), 128, 0), ik, ring, pool, w, step, t as i32, n_rot as i32, base, eps); Ok(())