use eyre::{Result, bail, eyre};
use crate::blaslt::Epilogue;
use crate::gpu::{Arg, Buf, Gpu, Mat, Precision, Tensor, blocks, launch};
use crate::weights::Weights;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum Act {
None = 0,
Relu = 1,
Gelu = 2,
GeluTanh = 3,
Sigmoid = 4,
}
impl Act {
fn epilogue(self, has_bias: bool) -> Option<Epilogue> {
Some(match (self, has_bias) {
(Self::None, false) => Epilogue::None,
(Self::None, true) => Epilogue::Bias,
(Self::Relu, false) => Epilogue::Relu,
(Self::Relu, true) => Epilogue::ReluBias,
(Self::GeluTanh, false) => Epilogue::Gelu,
(Self::GeluTanh, true) => Epilogue::GeluBias,
(Self::Gelu | Self::Sigmoid, _) => return None,
})
}
}
impl From<Act> for Arg {
fn from(act: Act) -> Self {
Arg::I32(act as i32)
}
}
pub fn ew(n: usize) -> (u32, u32, u32) {
assert!(n.next_multiple_of(256) <= 1 << 32, "{n} elements exceed the 2^32 threads of a 32-bit thread index");
(blocks(n, 256), 1, 1)
}
pub const B256: (u32, u32, u32) = (256, 1, 1);
pub fn bias_act(gpu: &Gpu, x: &Tensor, bias: Option<&Tensor>, act: Act) -> Result<()> {
assert!(
bias.is_none_or(|b| b.len() == x.cols()),
"bias of {} for rows of {}",
bias.map_or(0, Tensor::len),
x.cols()
);
launch!(gpu, "bias_act", ew(x.len()), B256, 0; x, bias.map_or(Arg::EMPTY, Arg::from), act)
}
pub fn add(gpu: &Gpu, a: &Tensor, b: &Tensor) -> Result<Tensor> {
assert_eq!(a.len(), b.len());
let out = gpu.empty(a.shape())?;
launch!(gpu, "add", ew(a.len()), B256, 0; &out, a, b)?;
Ok(out)
}
pub fn add_assign(gpu: &Gpu, a: &Tensor, b: &Tensor) -> Result<()> {
assert_eq!(a.len(), b.len());
launch!(gpu, "add_assign", ew(a.len()), B256, 0; a, b)
}
pub fn add_assign_bf16(gpu: &Gpu, a: &Tensor, b16: &Bf16) -> Result<()> {
assert_eq!(a.len(), b16.rows * b16.cols);
launch!(gpu, "add_assign_bf16", ew(a.len()), B256, 0; a, b16)
}
pub struct Bf16 {
pub buf: Buf,
pub rows: usize,
pub cols: usize,
}
impl Bf16 {
pub fn empty(gpu: &Gpu, rows: usize, cols: usize) -> Result<Self> {
Ok(Self { buf: gpu.alloc_bytes(rows * cols * 2)?, rows, cols })
}
pub fn from_f32(gpu: &Gpu, x: &Tensor) -> Result<Self> {
Ok(Self { buf: to_bf16(gpu, x, x.cols(), x.rows(), x.cols())?, rows: x.rows(), cols: x.cols() })
}
}
impl From<&Bf16> for Arg {
fn from(x: &Bf16) -> Self {
x.buf.slice::<u16>()
}
}
pub struct Linear {
w: LinearWeights,
shape: [usize; 2],
pub b: Option<Tensor>,
}
enum LinearWeights {
Fp32(Tensor),
Bf16 { w: Buf, b: Option<Buf> },
}
impl Linear {
pub fn new(w: Tensor, b: Option<Tensor>) -> Self {
let shape = [w.rows(), w.cols()];
Self { w: LinearWeights::Fp32(w), shape, b }
}
pub fn bf16(mut self, gpu: &Gpu) -> Result<Self> {
if gpu.precision() == Precision::Bf16
&& let LinearWeights::Fp32(w) = &self.w
{
let w16 = to_bf16(gpu, w, w.cols(), w.rows(), w.cols())?;
let b16 = self.b.as_ref().map(|b| to_bf16(gpu, b, b.len(), 1, b.len())).transpose()?;
self.w = LinearWeights::Bf16 { w: w16, b: b16 };
}
Ok(self)
}
fn is_bf16(&self) -> bool {
matches!(self.w, LinearWeights::Bf16 { .. })
}
fn w(&self) -> &Tensor {
match &self.w {
LinearWeights::Fp32(w) => w,
LinearWeights::Bf16 { .. } => panic!("FP32 path of a linear that keeps only BF16 weights"),
}
}
pub fn load(gpu: &Gpu, wts: &Weights, prefix: &str) -> Result<Self> {
let w = wts.get(gpu, &format!("{prefix}.weight"))?;
let w = match w.shape().len() {
2 => w,
_ => {
let (o, c) = (w.shape()[0], w.len() / w.shape()[0]);
w.reshape(&[o, c])
}
};
let bias = format!("{prefix}.bias");
let b = if wts.contains(&bias) { Some(wts.get(gpu, &bias)?) } else { None };
Ok(Self::new(w, b))
}
pub fn load_concat(gpu: &Gpu, wts: &Weights, prefixes: &[String]) -> Result<Self> {
let names = |s: &str| prefixes.iter().map(|p| format!("{p}.{s}")).collect::<Vec<_>>();
let w = wts.concat(gpu, &names("weight"))?;
let b = Some(wts.concat(gpu, &names("bias"))?);
Ok(Self::new(w, b))
}
pub fn out_features(&self) -> usize {
self.shape[0]
}
pub fn in_features(&self) -> usize {
self.shape[1]
}
pub fn forward(&self, gpu: &Gpu, x: &Tensor) -> Result<Tensor> {
self.forward_act(gpu, x, Act::None)
}
pub fn forward_act(&self, gpu: &Gpu, x: &Tensor, act: Act) -> Result<Tensor> {
assert_eq!(x.cols(), self.in_features(), "linear input {:?} vs weight {:?}", x.shape(), self.shape);
let rows = x.rows();
let out = gpu.empty(&[rows, self.out_features()])?;
if self.is_bf16() {
if !self.forward_bf16(gpu, x, out.ptr(), 0.0, act)? {
bias_act(gpu, &out, None, act)?;
}
return Ok(out);
}
let (epilogue, fused) = self.epilogue(act);
let bias = self.b.as_ref().map_or(0, Tensor::ptr);
let mnk = (rows, self.out_features(), self.in_features());
gpu.linear_f32(mnk, x.ptr(), x.cols(), self.w().ptr(), out.ptr(), 0.0, bias, epilogue)?;
if !fused {
bias_act(gpu, &out, None, act)?;
}
Ok(out)
}
fn epilogue(&self, act: Act) -> (Epilogue, bool) {
let has_bias = self.b.is_some();
match act.epilogue(has_bias) {
Some(epilogue) => (epilogue, true),
None => (if has_bias { Epilogue::Bias } else { Epilogue::None }, false),
}
}
pub fn forward_residual(&self, gpu: &Gpu, x: &Tensor, residual: &Tensor) -> Result<()> {
assert_eq!(residual.cols(), self.out_features());
assert_eq!(x.rows(), residual.rows());
if self.is_bf16() {
self.forward_bf16(gpu, x, residual.ptr(), 1.0, Act::None)?;
return Ok(());
}
let (epilogue, _) = self.epilogue(Act::None);
let bias = self.b.as_ref().map_or(0, Tensor::ptr);
let mnk = (x.rows(), self.out_features(), self.in_features());
gpu.linear_f32(mnk, x.ptr(), x.cols(), self.w().ptr(), residual.ptr(), 1.0, bias, epilogue)
}
fn forward_bf16(&self, gpu: &Gpu, x: &Tensor, out: u64, beta: f32, act: Act) -> Result<bool> {
let x16 = Bf16::from_f32(gpu, x)?;
self.forward_lt(gpu, &x16, (out, false), beta, act)
}
pub fn forward16_act16(&self, gpu: &Gpu, x16: &Bf16, act: Act) -> Result<Bf16> {
let out = Bf16::empty(gpu, x16.rows, self.out_features())?;
if !self.forward_lt(gpu, x16, (out.buf.ptr(), true), 0.0, act)? {
bail!("activation {act:?} has no cuBLASLt epilogue");
}
Ok(out)
}
pub fn forward_from16(&self, gpu: &Gpu, x16: &Bf16) -> Result<Tensor> {
let out = gpu.empty(&[x16.rows, self.out_features()])?;
self.forward_lt(gpu, x16, (out.ptr(), false), 0.0, Act::None)?;
Ok(out)
}
pub fn forward16_residual(&self, gpu: &Gpu, x16: &Bf16, residual: &Tensor) -> Result<()> {
assert_eq!((residual.rows(), residual.cols()), (x16.rows, self.out_features()));
self.forward_lt(gpu, x16, (residual.ptr(), false), 1.0, Act::None)?;
Ok(())
}
fn forward_lt(&self, gpu: &Gpu, x16: &Bf16, out: (u64, bool), beta: f32, act: Act) -> Result<bool> {
let LinearWeights::Bf16 { w: w16, b: b16 } = &self.w else { bail!("linear has no BF16 weights") };
assert_eq!(x16.cols, self.in_features());
let (m, n, k) = (x16.rows, self.out_features(), self.in_features());
let bias = if out.1 { b16.as_ref().map_or(0, Buf::ptr) } else { self.b.as_ref().map_or(0, Tensor::ptr) };
let (epilogue, fused) = self.epilogue(act);
gpu.linear_bf16((m, n, k), x16.buf.ptr(), k, w16.ptr(), out, beta, bias, epilogue)?;
Ok(fused)
}
pub fn forward_raw(&self, gpu: &Gpu, x: u64, x_ld: usize, rows: usize, out: u64, beta: f32) -> Result<()> {
let (n, k) = (self.out_features(), self.in_features());
gpu.gemm(rows, n, k, Mat::new(x, x_ld), Mat::new(self.w().ptr(), k).t(), Mat::new(out, n), 1, 1.0, beta)
}
}
pub struct Mlp {
pub layers: Vec<Linear>,
pub act: Act,
}
impl Mlp {
pub fn load(gpu: &Gpu, wts: &Weights, prefixes: &[String], act: Act) -> Result<Self> {
let layers = prefixes.iter().map(|p| Linear::load(gpu, wts, p)).collect::<Result<_>>()?;
Ok(Self { layers, act })
}
pub fn load_numbered(gpu: &Gpu, wts: &Weights, prefix: &str, n: usize, act: Act) -> Result<Self> {
let prefixes: Vec<String> = (1..=n).map(|i| format!("{prefix}.layer{i}")).collect();
Self::load(gpu, wts, &prefixes, act)
}
pub fn load_indexed(gpu: &Gpu, wts: &Weights, prefix: &str, n: usize, act: Act) -> Result<Self> {
let prefixes: Vec<String> = (0..n).map(|i| format!("{prefix}.layers.{i}")).collect();
Self::load(gpu, wts, &prefixes, act)
}
pub fn load_in_out(gpu: &Gpu, wts: &Weights, prefix: &str, n: usize, act: Act) -> Result<Self> {
let mut prefixes = vec![format!("{prefix}.proj_in")];
prefixes.extend((0..n - 2).map(|i| format!("{prefix}.layers.{i}")));
prefixes.push(format!("{prefix}.proj_out"));
Self::load(gpu, wts, &prefixes, act)
}
pub fn forward(&self, gpu: &Gpu, x: &Tensor) -> Result<Tensor> {
let last = self.layers.len() - 1;
let mut h = self.layers[0].forward_act(gpu, x, if last == 0 { Act::None } else { self.act })?;
for (i, layer) in self.layers.iter().enumerate().skip(1) {
h = layer.forward_act(gpu, &h, if i == last { Act::None } else { self.act })?;
}
Ok(h)
}
}
fn row_block(cols: usize) -> (u32, u32, u32) {
(cols.next_multiple_of(32).clamp(32, 256) as u32, 1, 1)
}
pub struct LayerNorm {
pub w: Tensor,
pub b: Tensor,
pub eps: f32,
}
impl LayerNorm {
pub fn load(gpu: &Gpu, wts: &Weights, prefix: &str, eps: f32) -> Result<Self> {
Ok(Self { w: wts.get(gpu, &format!("{prefix}.weight"))?, b: wts.get(gpu, &format!("{prefix}.bias"))?, eps })
}
pub fn forward(&self, gpu: &Gpu, x: &Tensor) -> Result<Tensor> {
let out = gpu.empty(x.shape())?;
self.forward_into(gpu, x, &out)?;
Ok(out)
}
pub fn forward_inplace(&self, gpu: &Gpu, x: &Tensor) -> Result<()> {
assert_eq!(x.cols(), self.w.len());
launch!(gpu, "layernorm_inplace", (x.rows() as u32, 1, 1), row_block(x.cols()), 0;
x, &self.w, &self.b, x.cols(), self.eps)
}
pub fn forward16(&self, gpu: &Gpu, x: &Tensor) -> Result<Bf16> {
assert_eq!(x.cols(), self.w.len());
let out = Bf16::empty(gpu, x.rows(), x.cols())?;
launch!(gpu, "layernorm_bf16", (x.rows() as u32, 1, 1), B256, 0;
&out, x, &self.w, &self.b, x.cols(), self.eps)?;
Ok(out)
}
pub fn add_forward16(&self, gpu: &Gpu, x: &Tensor, add16: &Bf16) -> Result<Bf16> {
assert_eq!(x.cols(), self.w.len());
assert_eq!((add16.rows, add16.cols), (x.rows(), x.cols()));
let out = Bf16::empty(gpu, x.rows(), x.cols())?;
launch!(gpu, "add_layernorm_bf16", (x.rows() as u32, 1, 1), B256, 0;
&out, x, add16, &self.w, &self.b, x.cols(), self.eps)?;
Ok(out)
}
fn forward_into(&self, gpu: &Gpu, x: &Tensor, out: &Tensor) -> Result<()> {
assert_eq!(x.cols(), self.w.len());
launch!(gpu, "layernorm", (x.rows() as u32, 1, 1), row_block(x.cols()), 0;
out, x, &self.w, &self.b, x.cols(), self.eps)
}
}
#[derive(Clone, Copy, Default)]
pub struct Mask {
pub bias: u64,
pub bias_div: usize,
pub key_pad: u64,
pub causal: bool,
pub rpb: Option<BoxRpb>,
}
const F32_D64_SMEM_BYTES: u32 = (64 * 64 + 64 * 68 + 64 * 64) * 4;
const RPB_SPLITS: usize = 16;
const SPLIT_UNDER_BLOCKS: usize = 64;
const SPLIT_BLOCKS: usize = 256;
const SPLIT_MIN_KEYS: usize = 1024;
const TALL_MIN: usize = 512;
#[derive(Clone, Copy)]
pub struct BoxRpb {
pub dx: u64,
pub dy: u64,
pub side: usize,
}
#[allow(clippy::too_many_arguments)]
pub fn attention(
gpu: &Gpu,
q: Mat,
k: Mat,
v: Mat,
out: Mat,
batch: usize,
lq: usize,
lk: usize,
hd: usize,
mask: Mask,
) -> Result<()> {
let extent = |m: Mat, rows: usize| match batch * rows {
0 => 0,
_ => (batch - 1) * m.stride + (rows - 1) * m.ld + hd,
};
let key_pad = match mask.key_pad {
0 => Arg::EMPTY,
p => Arg::slice(p, lk),
};
let rpb_len = |r: BoxRpb| batch * (lq - 1) * r.side;
if f32_flash_ok(gpu, &[q, k, v, out], hd, &mask) {
let scale_log2 = std::f32::consts::LOG2_E / (hd as f32).sqrt();
let view = |(m, rows): (Mat, usize)| [Arg::slice(m.ptr, extent(m, rows)), Arg::from(m.ld), Arg::from(m.stride)];
let args = [(out, lq), (q, lq), (k, lk), (v, lk)]
.into_iter()
.flat_map(view)
.chain([Arg::from(lq), Arg::from(lk), Arg::from(scale_log2)])
.collect();
let grid = (lq.div_ceil(64) as u32, batch as u32, 1);
return gpu.launch("flash_attn_f32_d64", grid, (128, 1, 1), F32_D64_SMEM_BYTES, args);
}
let tf32 = tf32_flash_ok(gpu, &[q, k, v, out], hd, &mask);
if tf32 || flash_ok(gpu, &[q, k, v, out], hd, &mask) {
let tall = !q.bf16 && hd == 32 && mask.rpb.is_none() && lq >= TALL_MIN && lk >= TALL_MIN;
let kernel = match (tf32, q.bf16, hd, mask.rpb) {
(true, _, 32, Some(_)) => "flash_attn_tf32_rpb_d32",
(true, _, 32, None) if tall => "flash_attn_tf32_tall_d32",
(true, _, 32, None) => "flash_attn_tf32_d32",
(true, _, _, _) => "flash_attn_tf32_d64",
(false, true, _, _) => "flash_attn_bf16_d64",
(false, false, 32, Some(_)) => "flash_attn_rpb_d32",
(false, false, 32, None) => "flash_attn_d32",
_ => "flash_attn_d64",
};
let scale_log2 = std::f32::consts::LOG2_E / (hd as f32).sqrt();
let view = |(m, rows): (Mat, usize)| [Arg::slice(m.ptr, extent(m, rows)), Arg::from(m.ld), Arg::from(m.stride)];
if tall && !tf32 {
let n = lk * batch * hd;
let kv = gpu.alloc_bytes(2 * n * 2)?;
launch!(gpu, "kv_to_16", ew(2 * n / 8), B256, 0;
kv.slice::<[u16; 8]>(), Arg::slice(k.ptr, extent(k, lk)), k.ld, k.stride,
Arg::slice(v.ptr, extent(v, lk)), v.ld, v.stride, batch, hd)?;
let packed = |ptr: u64| (Mat::new(ptr, batch * hd).stride(hd), lk);
let tail = [Arg::from(lq), Arg::from(lk), Arg::from(scale_log2), key_pad];
let args = [(out, lq), (q, lq), packed(kv.ptr()), packed(kv.ptr() + (n * 2) as u64)]
.into_iter()
.flat_map(view)
.chain(tail)
.collect();
let grid = (lq.div_ceil(128) as u32, batch as u32, 1);
return gpu.launch("flash_attn_kv16_d32", grid, (256, 1, 1), 0, args);
}
let rows = if tall { 128 } else { 64 };
let grid = (lq.div_ceil(rows) as u32, batch as u32, 1);
let mut args = Vec::with_capacity(16);
for m in [(out, lq), (q, lq), (k, lk), (v, lk)] {
args.extend(view(m));
}
args.extend([Arg::from(lq), Arg::from(lk), Arg::from(scale_log2)]);
let tiles = (grid.0 * grid.1) as usize;
let splits = match mask.rpb {
Some(_) => RPB_SPLITS,
None if hd == 32 && tiles < SPLIT_UNDER_BLOCKS && lk >= SPLIT_MIN_KEYS => SPLIT_BLOCKS.div_ceil(tiles),
None => 1,
};
let chunk = lk.div_ceil(splits).next_multiple_of(64);
let splits = lk.div_ceil(chunk);
let part = if splits > 1 { Some(gpu.empty(&[splits, batch, lq, hd + 2])?) } else { None };
match mask.rpb {
Some(r) => {
assert!(r.side.is_multiple_of(2), "the fused box RPB needs an even side");
args.extend([Arg::slice(r.dx, rpb_len(r)), Arg::slice(r.dy, rpb_len(r)), Arg::from(r.side)]);
}
None => args.push(key_pad),
}
args.extend([part.as_ref().map_or(Arg::EMPTY, Arg::from), Arg::from(chunk)]);
gpu.launch(kernel, (grid.0, grid.1, splits as u32), (rows as u32 * 2, 1, 1), 0, args)?;
let Some(part) = part else { return Ok(()) };
let warps = batch * lq;
return launch!(gpu, "flash_combine_d32", (blocks(warps * 32, 256), 1, 1), B256, 0;
Arg::slice(out.ptr, extent(out, lq)), out.ld, out.stride, &part, batch, lq);
}
let (bias, bias_div) = match mask.rpb {
Some(r) => {
assert!(mask.bias == 0 && lk == r.side * r.side, "box RPB covers a side x side key grid");
let bias = gpu.empty(&[batch, lq, lk])?;
launch!(gpu, "rpb_combine", ew(bias.len()), B256, 0;
&bias, Arg::slice(r.dx, rpb_len(r)), Arg::slice(r.dy, rpb_len(r)), lq - 1, r.side)?;
(Some(bias), 1)
}
None => (None, mask.bias_div.max(1)),
};
let bias_arg = match (&bias, mask.bias) {
(Some(b), _) => Arg::from(b),
(None, 0) => Arg::EMPTY,
(None, p) => Arg::slice(p, batch.div_ceil(bias_div) * lq * lk),
};
let scores = gpu.empty(&[batch, lq, lk])?;
let scale = 1.0 / (hd as f32).sqrt();
let s = Mat::new(scores.ptr(), lk).stride(lq * lk);
gpu.gemm(lq, lk, hd, q, k.t(), s, batch, scale, 0.0)?;
let block = if lk <= 32 { (32, 1, 1) } else { B256 };
launch!(gpu, "softmax", ((batch * lq) as u32, 1, 1), block, 0;
&scores, lq, bias_arg, bias_div, key_pad, mask.causal as i32)?;
gpu.gemm(lq, hd, lk, s, v, out, batch, 1.0, 0.0)
}
fn f32_flash_ok(gpu: &Gpu, [q, k, v, out]: &[Mat; 4], hd: usize, mask: &Mask) -> bool {
let aligned =
|m: &Mat| !m.trans && m.ptr.is_multiple_of(16) && m.ld.is_multiple_of(4) && m.stride.is_multiple_of(4);
gpu.precision() == Precision::Fp32
&& !q.bf16
&& hd == 64
&& mask.rpb.is_none()
&& mask.key_pad == 0
&& mask.bias == 0
&& !mask.causal
&& [q, k, v, out].into_iter().all(aligned)
}
fn tf32_flash_ok(gpu: &Gpu, [q, k, v, out]: &[Mat; 4], hd: usize, mask: &Mask) -> bool {
let aligned = |m: &Mat, elems: usize| {
!m.trans
&& m.ptr.is_multiple_of(elems as u64 * 4)
&& m.ld.is_multiple_of(elems)
&& m.stride.is_multiple_of(elems)
};
gpu.precision() == Precision::Tf32
&& !q.bf16
&& (hd == 32 || hd == 64)
&& (mask.rpb.is_none() || (hd == 32 && mask.key_pad == 0))
&& mask.bias == 0
&& !mask.causal
&& aligned(out, 2)
&& [q, k, v].iter().all(|m| aligned(m, 4))
}
fn flash_ok(gpu: &Gpu, [q, k, v, out]: &[Mat; 4], hd: usize, mask: &Mask) -> bool {
let aligned = |m: &Mat, elems: usize, size: usize| {
!m.trans
&& m.ptr.is_multiple_of((elems * size) as u64)
&& m.ld.is_multiple_of(elems)
&& m.stride.is_multiple_of(elems)
};
let bf16 = q.bf16;
assert!(k.bf16 == bf16 && v.bf16 == bf16 && !out.bf16, "q/k/v share a type, out is FP32");
let inputs = if bf16 { (8, 2) } else { (4, 4) };
let ok = gpu.precision() == Precision::Bf16
&& (hd == 64 || (hd == 32 && !bf16))
&& (mask.rpb.is_none() || (hd == 32 && !bf16 && mask.key_pad == 0))
&& mask.bias == 0
&& !mask.causal
&& aligned(out, 2, 4)
&& [q, k, v].iter().all(|m| aligned(m, inputs.0, inputs.1));
assert!(ok || !bf16, "BF16 attention inputs need the fused kernel");
ok
}
#[allow(clippy::too_many_arguments)]
pub fn mha(
gpu: &Gpu,
q: (u64, usize),
k: (u64, usize),
v: (u64, usize),
lq: usize,
lk: usize,
heads: usize,
hd: usize,
mask: Mask,
) -> Result<Tensor> {
let out = gpu.empty(&[lq, heads * hd])?;
attention(
gpu,
Mat::new(q.0, q.1).stride(hd),
Mat::new(k.0, k.1).stride(hd),
Mat::new(v.0, v.1).stride(hd),
Mat::new(out.ptr(), heads * hd).stride(hd),
heads,
lq,
lk,
hd,
Mask { bias_div: mask.bias_div.max(1), ..mask },
)?;
Ok(out)
}
const FLASH_D256_SMEM: u32 = 3 * 64 * 264 * 2;
const D256_MAX_SPLITS: usize = 8;
pub fn attention_f16_d256(gpu: &Gpu, q: &Buf, k: &Buf, v: &Buf, lq: usize, lk: usize) -> Result<Tensor> {
let kernel = SplitAttention { name: "flash_attn_f16_d256", combine: "flash_combine_d256", dv: 256, rows: 64 };
kernel.run(gpu, q, k, v, lq, lk, (128, FLASH_D256_SMEM))
}
const FLASH_MEM_SMEM: u32 = 2 * 64 * 264 * 2 + 2 * 64 * 72 * 2;
pub fn attention_f16_qk256_v64(gpu: &Gpu, q: &Buf, k: &Buf, v: &Buf, lq: usize, lk: usize) -> Result<Tensor> {
let kernel = SplitAttention { name: "flash_attn_f16_qk256_v64", combine: "flash_combine_d64", dv: 64, rows: 128 };
kernel.run(gpu, q, k, v, lq, lk, (256, FLASH_MEM_SMEM))
}
struct SplitAttention {
name: &'static str,
combine: &'static str,
dv: usize,
rows: usize,
}
impl SplitAttention {
#[allow(clippy::too_many_arguments)]
fn run(&self, gpu: &Gpu, q: &Buf, k: &Buf, v: &Buf, lq: usize, lk: usize, block: (u32, u32)) -> Result<Tensor> {
const D: usize = 256;
let dv = self.dv;
assert!(lk > 0 && q.bytes() >= lq * D * 2 && k.bytes() >= lk * D * 2 && v.bytes() >= lk * dv * 2);
let out = gpu.empty(&[lq, dv])?;
let qblocks = lq.div_ceil(self.rows);
let cost = |s: usize| (qblocks * s).div_ceil(gpu.sms()) as f64 / s as f64;
let splits = (1..=D256_MAX_SPLITS)
.filter(|s| lk >= s * 64)
.fold(1, |best, s| if cost(s) < cost(best) { s } else { best });
let chunk = lk.div_ceil(splits).next_multiple_of(64);
let splits = lk.div_ceil(chunk);
let part = if splits > 1 { Some(gpu.empty(&[splits, 1, lq, dv + 2])?) } else { None };
let view = |ptr: u64, rows: usize, w: usize| [Arg::slice(ptr, rows * w), Arg::from(w), Arg::from(0usize)];
let mut args: Vec<Arg> = [(out.ptr(), lq, dv), (q.ptr(), lq, D), (k.ptr(), lk, D), (v.ptr(), lk, dv)]
.into_iter()
.flat_map(|(p, r, w)| view(p, r, w))
.collect();
let scale_log2 = std::f32::consts::LOG2_E / (D as f32).sqrt();
args.extend([Arg::from(lq), Arg::from(lk), Arg::from(scale_log2)]);
args.extend([part.as_ref().map_or(Arg::EMPTY, Arg::from), Arg::from(chunk)]);
gpu.launch(self.name, (qblocks as u32, 1, splits as u32), (block.0, 1, 1), block.1, args)?;
if let Some(part) = part {
launch!(gpu, self.combine, (blocks(lq * 32, 256), 1, 1), B256, 0; &out, dv, 0usize, &part, 1usize, lq)?;
}
Ok(out)
}
}
const IM2COL_ROWS: usize = 16 << 10;
pub struct Conv3x3 {
pub w: Tensor,
pub b: Tensor,
w16: Option<Buf>,
}
impl Conv3x3 {
pub fn load(gpu: &Gpu, wts: &Weights, prefix: &str) -> Result<Self> {
let (w, shape) = wts.host(&format!("{prefix}.weight"))?;
let (o, c) = (shape[0], shape[1]);
assert_eq!(&shape[2..], &[3, 3]);
let mut taps = vec![0f32; w.len()];
for oc in 0..o {
for ic in 0..c {
for t in 0..9 {
taps[(t * o + oc) * c + ic] = w[(oc * c + ic) * 9 + t];
}
}
}
let w16 = match gpu.precision() {
Precision::Fp32 | Precision::Tf32 => None,
Precision::Bf16 => {
let mut rows = vec![0f32; w.len()];
for oc in 0..o {
for t in 0..9 {
for ic in 0..c {
rows[(oc * 9 + t) * c + ic] = w[(oc * c + ic) * 9 + t];
}
}
}
let rows = gpu.upload(rows, &[o, 9 * c])?;
Some(to_bf16(gpu, &rows, rows.len(), 1, rows.len())?)
}
};
let w = gpu.upload(taps, &[9, o, c])?;
Ok(Self { w, b: wts.get(gpu, &format!("{prefix}.bias"))?, w16 })
}
pub fn forward(&self, gpu: &Gpu, x: &Tensor, h: usize, w: usize) -> Result<Tensor> {
let (o, c) = (self.w.shape()[1], self.w.shape()[2]);
assert_eq!(x.shape(), &[h * w, c]);
if let Some(w16) = &self.w16 {
return self.forward_im2col(gpu, x, w16, h, w);
}
let wp = w + 2;
let rows = (h + 2) * wp + 2;
let xp = gpu.alloc_bytes(rows * c * 4)?;
launch!(gpu, "pad1", ew(rows * c), B256, 0; xp.slice::<f32>(), x, w, c)?;
let yp = gpu.empty(&[h * wp, o])?;
for t in 0..9 {
let (dy, dx) = (t / 3, t % 3);
let input = Mat::new(xp.ptr() + ((dy * wp + dx) * c * 4) as u64, c);
let weight = Mat::new(self.w.at(t * o * c), c).t();
let beta = if t == 0 { 0.0 } else { 1.0 };
gpu.linear_f32((h * wp, o, c), input.ptr, c, weight.ptr, yp.ptr(), beta, 0, Epilogue::None)?;
}
let y = gpu.empty(&[h * w, o])?;
launch!(gpu, "crop_bias", ew(y.len()), B256, 0; &y, &yp, &self.b, w, o)?;
Ok(y)
}
pub fn forward_up(
&self,
gpu: &Gpu,
fine: &Tensor,
coarse: &Tensor,
norm: Option<&PendingNorm>,
h: usize,
w: usize,
) -> Result<Tensor> {
let c = self.w.shape()[2];
assert_eq!(fine.shape(), &[h * w, c]);
assert_eq!(coarse.shape(), &[h * w / 4, c]);
let Some(w16) = &self.w16 else {
if let Some(norm) = norm {
norm.apply(gpu, coarse)?;
}
let up = gpu.empty(&[h * w, c])?;
launch!(gpu, "upsample2_add", ew(up.len()), B256, 0; &up, fine, coarse, w / 2, c)?;
return self.forward(gpu, &up, h, w);
};
assert!(norm.is_none_or(|n| (c / n.groups).is_multiple_of(8)), "im2col normalizes 8 channels of one group");
let (stats, gw, gb) = norm
.map_or((Arg::EMPTY, Arg::EMPTY, Arg::EMPTY), |n| (Arg::from(&n.stats), Arg::from(n.w), Arg::from(n.b)));
let (groups, eps, act) = norm.map_or((1, 0.0, Act::None), |n| (n.groups, n.eps, n.act));
self.im2col_gemm(gpu, w16, h, w, |cols, p0, n| {
launch!(gpu, "im2col3x3_up_bf16", ew(n * 9 * c / 8), B256, 0;
cols, fine, coarse, stats, gw, gb, groups, eps, act, w, c, p0)
})
}
fn forward_im2col(&self, gpu: &Gpu, x: &Tensor, w16: &Buf, h: usize, w: usize) -> Result<Tensor> {
let c = self.w.shape()[2];
self.im2col_gemm(
gpu,
w16,
h,
w,
|cols, p0, n| launch!(gpu, "im2col3x3_bf16", ew(n * 9 * c / 8), B256, 0; cols, x, w, c, p0),
)
}
fn im2col_gemm(
&self,
gpu: &Gpu,
w16: &Buf,
h: usize,
w: usize,
im2col: impl Fn(Arg, usize, usize) -> Result<()>,
) -> Result<Tensor> {
let (o, c) = (self.w.shape()[1], self.w.shape()[2]);
assert!(c.is_multiple_of(8), "im2col copies 8 channels at a time");
let (pixels, k) = (h * w, 9 * c);
let y = gpu.empty(&[pixels, o])?;
let cols = gpu.alloc_bytes(pixels.min(IM2COL_ROWS) * k * 2)?;
for p0 in (0..pixels).step_by(IM2COL_ROWS) {
let n = IM2COL_ROWS.min(pixels - p0);
im2col(Arg::slice(cols.ptr(), n * k / 8), p0, n)?;
let out = (y.at(p0 * o), false);
gpu.linear_bf16((n, o, k), cols.ptr(), k, w16.ptr(), out, 0.0, self.b.ptr(), Epilogue::Bias)?;
}
Ok(y)
}
}
pub struct ConvT2x2 {
pub w: Tensor,
pub b: Tensor,
w16: Option<Buf>,
}
impl ConvT2x2 {
pub fn load(gpu: &Gpu, wts: &Weights, prefix: &str) -> Result<Self> {
let w = wts.get(gpu, &format!("{prefix}.weight"))?;
let c = w.shape()[0];
let n = w.len() / c;
let w = w.reshape(&[c, n]);
let w16 = bf16_weights(gpu, &w)?;
Ok(Self { w, b: wts.get(gpu, &format!("{prefix}.bias"))?, w16 })
}
pub fn forward(&self, gpu: &Gpu, x: &Tensor, h: usize, w: usize) -> Result<Tensor> {
let (c, n) = (self.w.shape()[0], self.w.shape()[1]);
assert_eq!(x.shape(), &[h * w, c]);
let g = gpu.empty(&[h * w, n])?;
match &self.w16 {
Some(w16) => {
let x16 = Bf16::from_f32(gpu, x)?;
let (input, weight) = (Mat::new(x16.buf.ptr(), c).bf16(), Mat::new(w16.ptr(), n).bf16());
gpu.gemm(h * w, n, c, input, weight, Mat::new(g.ptr(), n), 1, 1.0, 0.0)?;
}
None => gpu.gemm(
h * w,
n,
c,
Mat::new(x.ptr(), c),
Mat::new(self.w.ptr(), n),
Mat::new(g.ptr(), n),
1,
1.0,
0.0,
)?,
}
let o = n / 4;
let y = gpu.empty(&[4 * h * w, o])?;
launch!(gpu, "convt2x2_scatter", ew(y.len()), B256, 0; &y, &g, &self.b, w, o)?;
Ok(y)
}
pub fn forward16(&self, gpu: &Gpu, x16: &Bf16, h: usize, w: usize, act: Act) -> Result<Bf16> {
let w16 = self.w16.as_ref().ok_or_else(|| eyre!("transposed conv has no BF16 weights"))?;
let (c, n) = (self.w.shape()[0], self.w.shape()[1]);
assert_eq!((x16.rows, x16.cols), (h * w, c));
let g = gpu.empty(&[h * w, n])?;
let (input, weight) = (Mat::new(x16.buf.ptr(), c).bf16(), Mat::new(w16.ptr(), n).bf16());
gpu.gemm(h * w, n, c, input, weight, Mat::new(g.ptr(), n), 1, 1.0, 0.0)?;
let o = n / 4;
let y = Bf16::empty(gpu, 4 * h * w, o)?;
launch!(gpu, "convt2x2_scatter_bf16", ew(4 * h * w * o), B256, 0; &y, &g, &self.b, w, o, act)?;
Ok(y)
}
}
pub struct Attention {
pub q: Linear,
pub k: Linear,
pub v: Linear,
pub o: Linear,
pub heads: usize,
}
impl Attention {
pub fn load(gpu: &Gpu, wts: &Weights, prefix: &str, heads: usize) -> Result<Self> {
let l = |n: &str| Linear::load(gpu, wts, &format!("{prefix}.{n}"));
Ok(Self { q: l("q_proj")?, k: l("k_proj")?, v: l("v_proj")?, o: l("o_proj")?, heads })
}
pub fn forward_residual(
&self,
gpu: &Gpu,
q_in: &Tensor,
k_in: &Tensor,
v_in: &Tensor,
mask: Mask,
residual: &Tensor,
) -> Result<()> {
let attn = self.attend(gpu, q_in, k_in, v_in, mask)?;
self.o.forward_residual(gpu, &attn, residual)
}
fn attend(&self, gpu: &Gpu, q_in: &Tensor, k_in: &Tensor, v_in: &Tensor, mask: Mask) -> Result<Tensor> {
let q = self.q.forward(gpu, q_in)?;
let k = self.k.forward(gpu, k_in)?;
let v = self.v.forward(gpu, v_in)?;
let dim = q.cols();
mha(gpu, (q.ptr(), dim), (k.ptr(), dim), (v.ptr(), dim), q.rows(), k.rows(), self.heads, dim / self.heads, mask)
}
pub fn forward_batch(
&self,
gpu: &Gpu,
q_in: &Tensor,
k_in: &Tensor,
v_in: &Tensor,
batch: usize,
) -> Result<Tensor> {
let attn = self.attend_batch(gpu, q_in, k_in, v_in, batch)?;
self.o.forward(gpu, &attn)
}
pub fn forward_residual_batch(
&self,
gpu: &Gpu,
q_in: &Tensor,
k_in: &Tensor,
v_in: &Tensor,
batch: usize,
residual: &Tensor,
) -> Result<()> {
let attn = self.attend_batch(gpu, q_in, k_in, v_in, batch)?;
self.o.forward_residual(gpu, &attn, residual)
}
fn attend_batch(&self, gpu: &Gpu, q_in: &Tensor, k_in: &Tensor, v_in: &Tensor, batch: usize) -> Result<Tensor> {
if batch == 1 {
return self.attend(gpu, q_in, k_in, v_in, Mask::default());
}
assert!(q_in.rows().is_multiple_of(batch) && k_in.rows().is_multiple_of(batch), "rows of {batch} sequences");
let q = self.q.forward(gpu, q_in)?;
let k = self.k.forward(gpu, k_in)?;
let v = self.v.forward(gpu, v_in)?;
let (dim, heads) = (q.cols(), self.heads);
let hd = dim / heads;
let (lq, lk) = (q.rows() / batch, k.rows() / batch);
let [q, k, v] = [(&q, lq), (&k, lk), (&v, lk)].map(|(x, rows)| swap_middle(gpu, x, rows, heads, hd));
let (q, k, v) = (q?, k?, v?);
let by_head = gpu.empty(&[batch * heads * lq, hd])?;
let view = |t: &Tensor, rows: usize| Mat::new(t.ptr(), hd).stride(rows * hd);
let mask = Mask { bias_div: 1, ..Mask::default() };
attention(gpu, view(&q, lq), view(&k, lk), view(&v, lk), view(&by_head, lq), batch * heads, lq, lk, hd, mask)?;
Ok(swap_middle(gpu, &by_head, heads, lq, hd)?.reshape(&[batch * lq, dim]))
}
}
pub fn group_norm_stats<'a>(
gpu: &Gpu,
x: &Tensor,
groups: usize,
w: &'a Tensor,
b: &'a Tensor,
eps: f32,
act: Act,
) -> Result<PendingNorm<'a>> {
let (hw, c) = (x.rows(), x.cols());
let chunk = 256usize;
let blocks = hw.div_ceil(chunk);
let part = gpu.empty(&[groups * blocks, 2])?;
launch!(gpu, "group_stats", (blocks as u32, groups as u32, 1), B256, 0;
&part, x, c, groups, chunk)?;
let stats = gpu.empty(&[groups, 2])?;
launch!(gpu, "group_stats_reduce", (groups as u32, 1, 1), B256, 0; &stats, &part)?;
Ok(PendingNorm { stats, w, b, groups, eps, act })
}
pub struct PendingNorm<'a> {
stats: Tensor,
w: &'a Tensor,
b: &'a Tensor,
groups: usize,
eps: f32,
act: Act,
}
impl PendingNorm<'_> {
pub fn apply(&self, gpu: &Gpu, x: &Tensor) -> Result<()> {
launch!(gpu, "group_norm_apply", ew(x.len()), B256, 0;
x, &self.stats, self.w, self.b, x.cols(), self.groups, self.eps, self.act)
}
}
fn swap_middle(gpu: &Gpu, x: &Tensor, a: usize, b: usize, d: usize) -> Result<Tensor> {
assert!(x.len().is_multiple_of(a * b * d), "{:?} is not [n, {a}, {b}, {d}]", x.shape());
let out = gpu.empty(&[x.len() / d, d])?;
launch!(gpu, "swap_middle", ew(out.len()), B256, 0; &out, x, a, b, d)?;
Ok(out)
}
pub fn concat_rows(gpu: &Gpu, a: &Tensor, b: &Tensor) -> Result<Tensor> {
assert_eq!(a.cols(), b.cols());
let out = gpu.empty(&[a.rows() + b.rows(), a.cols()])?;
gpu.copy_dtod(a.ptr(), out.ptr(), a.len() * 4)?;
gpu.copy_dtod(b.ptr(), out.at(a.len()), b.len() * 4)?;
Ok(out)
}
fn bf16_weights(gpu: &Gpu, w: &Tensor) -> Result<Option<Buf>> {
Ok(match gpu.precision() {
Precision::Fp32 | Precision::Tf32 => None,
Precision::Bf16 => Some(to_bf16(gpu, w, w.len(), 1, w.len())?),
})
}
pub fn to_bf16(gpu: &Gpu, src: &Tensor, cols: usize, rows: usize, ld: usize) -> Result<Buf> {
let out = gpu.alloc_bytes(rows * cols * 2)?;
launch!(gpu, "f32_to_bf16", ew(rows * cols), B256, 0; out.slice::<u16>(), src, cols, ld)?;
Ok(out)
}
pub fn upload_i32(gpu: &Gpu, v: Vec<i32>) -> Result<Buf> {
gpu.upload_buf(v)
}
#[cfg(test)]
mod tests {
use super::Act;
#[test]
fn act_numbers_match_the_kernels() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/crates/sam3rs-kernels/src/common.rs");
if !std::path::Path::new(path).exists() {
eprintln!("skipped: {path} is not in the packaged crate");
return;
}
let source = std::fs::read_to_string(path).unwrap();
let mut kernel: Vec<(&str, i32)> = source
.lines()
.filter_map(|line| line.strip_prefix("pub const ACT_")?.strip_suffix(';')?.split_once(": i32 = "))
.map(|(name, value)| (name, value.parse().unwrap()))
.collect();
kernel.sort_by_key(|&(_, value)| value);
let host = [("RELU", Act::Relu), ("GELU", Act::Gelu), ("GELU_TANH", Act::GeluTanh), ("SIGMOID", Act::Sigmoid)];
let host: Vec<(&str, i32)> = host.iter().map(|&(name, act)| (name, act as i32)).collect();
assert_eq!(kernel, host);
assert!(kernel.iter().all(|&(_, value)| value != Act::None as i32));
}
}