Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,11 @@ 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<()>;
#[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
121 changes: 121 additions & 0 deletions src/cuda/kernels.cu
Original file line number Diff line number Diff line change
Expand Up @@ -6064,6 +6064,127 @@ 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<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;
}

// ---- 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
7 changes: 4 additions & 3 deletions src/cuda/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,7 @@ fn kernel_names_with(sm80: bool, dp4a: bool) -> Vec<String> {
.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"].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(), 474);
assert_eq!(sm70.len(), 402);
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(), 450);
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
6 changes: 5 additions & 1 deletion 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
98 changes: 98 additions & 0 deletions src/hip/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,104 @@ fn candidates(vars: Option<PathBuf>, default_suffix: &[&str]) -> Vec<PathBuf> {
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 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<GemmEx>,
_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<Blas> {
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::<unsafe extern "C" fn(*mut c_void, Stream) -> c_int>(&lib, "hipblasSetStream") else {
tried.push(format!("{}: no hipblasSetStream", path.display())); continue
};
let Some(gemm_ex) = Self::sym::<GemmEx>(&lib, "hipblasGemmEx") else {
tried.push(format!("{}: no hipblasGemmEx", path.display())); continue
};
let Some(destroy) = Self::sym::<unsafe extern "C" fn(*mut c_void) -> 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::<GemmEx>(&lib, "hipblasGemmEx_v2");
return Ok(Blas { handle, destroy, set_stream, gemm_ex, gemm_ex_v2, _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,
Comment thread
I-AM-ENGINEER marked this conversation as resolved.
Resolved
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(())
}

unsafe fn sym<T: Copy>(lib: &Library, name: &str) -> Option<T> {
let s = unsafe { lib.get::<T>(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,
Expand Down
Loading
Loading