use crate::precision::Precision;
use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::ffi::{CString, c_void};
use std::sync::Arc;
use bytemuck::Pod;
use cudarc::cublas::sys as blas;
use cudarc::driver::sys::{self as cu, CUdeviceptr, CUfunction, CUmemoryPool, CUmodule, CUstream};
use cudarc::driver::{CudaContext, CudaStream, result as cur};
use eyre::{Result, WrapErr, bail, ensure, eyre};
use crate::cuda::blaslt::{BlasLt, Epilogue, Operands};
use crate::cuda::cublas::Cublas;
static PTX_SM80: &str = concat!(include_str!("../../kernels/ptx/sam3.sm80.ptx"), "\0");
static PTX_SM120: &str = concat!(include_str!("../../kernels/ptx/sam3.sm120.ptx"), "\0");
const MIN_DRIVER: i32 = 13000;
const PENDING_LIMIT: usize = 256 << 20;
struct Device {
stream: Arc<CudaStream>,
pool: CUmemoryPool,
}
unsafe impl Send for Device {}
unsafe impl Sync for Device {}
impl Device {
fn bind(&self) -> Result<()> {
self.stream.context().bind_to_thread()?;
Ok(())
}
}
impl Drop for Device {
fn drop(&mut self) {
if self.bind().is_ok() {
let _ = self.stream.synchronize();
unsafe {
let _ = cur::mem_pool::destroy(self.pool);
}
}
}
}
pub struct Buf {
ptr: CUdeviceptr,
bytes: usize,
device: Arc<Device>,
}
impl Buf {
pub fn ptr(&self) -> u64 {
self.ptr
}
pub fn bytes(&self) -> usize {
self.bytes
}
pub fn slice<T>(&self) -> Arg {
debug_assert!(self.bytes.is_multiple_of(size_of::<T>()));
Arg::slice(self.ptr, self.bytes / size_of::<T>())
}
}
impl Drop for Buf {
fn drop(&mut self) {
if self.bytes > 0 && self.device.bind().is_ok() {
unsafe {
let _ = cur::free_async(self.ptr, self.device.stream.cu_stream());
}
}
}
}
pub struct Tensor {
buf: Buf,
shape: Vec<usize>,
}
impl Tensor {
pub fn ptr(&self) -> u64 {
self.buf.ptr
}
pub fn at(&self, offset: usize) -> u64 {
debug_assert!(offset <= self.len());
self.buf.ptr + (offset * 4) as u64
}
pub fn shape(&self) -> &[usize] {
&self.shape
}
pub fn len(&self) -> usize {
self.shape.iter().product()
}
pub fn cols(&self) -> usize {
*self.shape.last().unwrap_or(&1)
}
pub fn rows(&self) -> usize {
self.len() / self.cols().max(1)
}
pub fn reshape(mut self, shape: &[usize]) -> Self {
assert_eq!(shape.iter().product::<usize>(), self.len(), "reshape {:?} -> {shape:?}", self.shape);
self.shape = shape.to_vec();
self
}
}
#[derive(Clone, Copy, Debug)]
pub enum Arg {
Slice(u64, u64),
U32(u32),
I32(i32),
F32(f32),
}
impl Arg {
pub const EMPTY: Arg = Arg::Slice(256, 0);
pub fn slice(ptr: u64, len: usize) -> Self {
Arg::Slice(ptr, len as u64)
}
fn params(&self) -> &'static [Param] {
match self {
Arg::Slice(..) => &[Param::Ptr, Param::U64],
Arg::U32(_) | Arg::I32(_) => &[Param::U32],
Arg::F32(_) => &[Param::F32],
}
}
}
impl From<i32> for Arg {
fn from(v: i32) -> Self {
Arg::I32(v)
}
}
impl From<usize> for Arg {
fn from(v: usize) -> Self {
Arg::U32(u32::try_from(v).expect("kernel size argument overflows u32"))
}
}
impl From<f32> for Arg {
fn from(v: f32) -> Self {
Arg::F32(v)
}
}
impl From<&Tensor> for Arg {
fn from(t: &Tensor) -> Self {
Arg::slice(t.ptr(), t.len())
}
}
impl From<&mut Tensor> for Arg {
fn from(t: &mut Tensor) -> Self {
Arg::slice(t.ptr(), t.len())
}
}
macro_rules! launch {
($gpu:expr, $name:expr, $grid:expr, $block:expr, $smem:expr; $($arg:expr),* $(,)?) => {
$gpu.launch($name, $grid, $block, $smem, vec![$($crate::cuda::gpu::Arg::from($arg)),*])
};
}
pub(crate) use launch;
#[derive(Clone, Copy, Debug)]
pub struct Mat {
pub ptr: u64,
pub ld: usize,
pub stride: usize,
pub trans: bool,
pub bf16: bool,
}
impl Mat {
pub fn new(ptr: u64, ld: usize) -> Self {
Self { ptr, ld, stride: 0, trans: false, bf16: false }
}
pub fn bf16(mut self) -> Self {
self.bf16 = true;
self
}
pub fn t(mut self) -> Self {
self.trans = true;
self
}
pub fn stride(mut self, stride: usize) -> Self {
self.stride = stride;
self
}
}
pub struct Gpu {
lt: BlasLt,
device: Arc<Device>,
module: CUmodule,
ptx: &'static str,
functions: RefCell<HashMap<&'static str, Kernel>>,
cublas: &'static Cublas,
blas: blas::cublasHandle_t,
fp32_compute: blas::cublasComputeType_t,
fp32_operands: Operands,
precision: Precision,
sms: usize,
pending: RefCell<Vec<Box<dyn Any + Send>>>,
pending_bytes: Cell<usize>,
}
unsafe impl Send for Gpu {}
impl Gpu {
pub fn new(ordinal: usize, precision: Precision) -> Result<Self> {
let cublas = check_libraries()?;
let ctx = CudaContext::new(ordinal).wrap_err_with(|| format!("open CUDA device {ordinal}"))?;
let (major, minor) = ctx.compute_capability()?;
let sms = ctx.attribute(cu::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT)? as usize;
if major < 8 {
bail!("GPU {ordinal} has compute capability {major}.{minor}; sam3rs needs 8.0 (Ampere) or newer");
}
unsafe { ctx.disable_event_tracking() };
let stream = ctx.new_stream()?;
let device = Arc::new(Device { pool: create_pool(&ctx)?, stream });
let ptx = if major >= 12 { PTX_SM120 } else { PTX_SM80 };
let module = Unowned(
unsafe { cur::module::load_data(ptx.as_ptr().cast()) }.wrap_err("JIT-compile the sam3rs kernels")?,
|m| unsafe {
let _ = cur::module::unload(m);
},
);
let mut raw = std::ptr::null_mut();
unsafe { check_blas((cublas.blas.create)(&mut raw))? };
let handle = Unowned(raw, |h| unsafe {
if let Ok(cublas) = Cublas::get() {
(cublas.blas.destroy)(h);
}
});
unsafe { check_blas((cublas.blas.set_stream)(handle.0, device.stream.cu_stream() as _))? };
let (math, fp32_compute) = match precision {
Precision::Fp32 => {
(blas::cublasMath_t::CUBLAS_PEDANTIC_MATH, blas::cublasComputeType_t::CUBLAS_COMPUTE_32F_PEDANTIC)
}
Precision::Tf32 => {
(blas::cublasMath_t::CUBLAS_DEFAULT_MATH, blas::cublasComputeType_t::CUBLAS_COMPUTE_32F_FAST_TF32)
}
Precision::Bf16 => {
(blas::cublasMath_t::CUBLAS_DEFAULT_MATH, blas::cublasComputeType_t::CUBLAS_COMPUTE_32F_FAST_16BF)
}
};
unsafe { check_blas((cublas.blas.set_math_mode)(handle.0, math))? };
let lt = BlasLt::new(&cublas.lt)?;
let fp32_operands = match fp32_compute {
blas::cublasComputeType_t::CUBLAS_COMPUTE_32F_FAST_TF32 => Operands::F32FastTf32,
blas::cublasComputeType_t::CUBLAS_COMPUTE_32F_FAST_16BF => Operands::F32Fast16Bf,
_ => Operands::F32,
};
Ok(Self {
lt,
device,
module: module.into_inner(),
ptx,
functions: RefCell::new(HashMap::new()),
cublas,
blas: handle.into_inner(),
fp32_compute,
fp32_operands,
precision,
sms,
pending: RefCell::new(Vec::new()),
pending_bytes: Cell::new(0),
})
}
pub fn bind(&self) -> Result<()> {
self.device.bind()
}
pub fn precision(&self) -> Precision {
self.precision
}
pub fn sms(&self) -> usize {
self.sms
}
fn cu_stream(&self) -> CUstream {
self.device.stream.cu_stream()
}
pub fn synchronize(&self) -> Result<()> {
self.device.stream.synchronize()?;
self.pending.borrow_mut().clear();
self.pending_bytes.set(0);
Ok(())
}
pub fn alloc_bytes(&self, bytes: usize) -> Result<Buf> {
let mut ptr = 0;
if bytes > 0 {
unsafe { cu::cuMemAllocFromPoolAsync(&mut ptr, bytes, self.device.pool, self.cu_stream()).result() }
.wrap_err_with(|| format!("allocate {bytes} bytes on the GPU"))?;
}
Ok(Buf { ptr, bytes, device: self.device.clone() })
}
pub fn empty(&self, shape: &[usize]) -> Result<Tensor> {
let n: usize = shape.iter().product();
Ok(Tensor { buf: self.alloc_bytes(n * 4)?, shape: shape.to_vec() })
}
pub fn zeros(&self, shape: &[usize]) -> Result<Tensor> {
let t = self.empty(shape)?;
self.memset_zero(t.ptr(), t.len() * 4)?;
Ok(t)
}
pub fn memset_zero(&self, ptr: u64, bytes: usize) -> Result<()> {
if bytes > 0 {
unsafe { cur::memset_d8_async(ptr, 0, bytes, self.cu_stream())? };
}
Ok(())
}
pub fn upload(&self, host: Vec<f32>, shape: &[usize]) -> Result<Tensor> {
ensure!(host.len() == shape.iter().product::<usize>(), "upload of {} floats as {shape:?}", host.len());
Ok(Tensor { buf: self.upload_buf(host)?, shape: shape.to_vec() })
}
pub fn upload_buf<T: Pod + Send>(&self, host: Vec<T>) -> Result<Buf> {
let bytes: &[u8] = bytemuck::cast_slice(&host);
let buf = self.alloc_bytes(bytes.len())?;
if bytes.is_empty() {
return Ok(buf);
}
unsafe { cur::memcpy_htod_async(buf.ptr, bytes, self.cu_stream())? };
self.pending_bytes.set(self.pending_bytes.get() + bytes.len());
self.pending.borrow_mut().push(Box::new(host));
if self.pending_bytes.get() > PENDING_LIMIT {
self.synchronize()?;
}
Ok(buf)
}
pub fn upload_slice(&self, host: &[u8]) -> Result<Buf> {
let buf = self.alloc_bytes(host.len())?;
if !host.is_empty() {
unsafe { cur::memcpy_htod_async(buf.ptr, host, self.cu_stream())? };
self.synchronize()?;
}
Ok(buf)
}
pub fn copy_dtod(&self, src: u64, dst: u64, bytes: usize) -> Result<()> {
if bytes > 0 {
unsafe { cur::memcpy_dtod_async(dst, src, bytes, self.cu_stream())? };
}
Ok(())
}
pub fn download_into<T: Pod>(&self, src: &Buf, host: &mut [T]) -> Result<()> {
let host: &mut [u8] = bytemuck::cast_slice_mut(host);
ensure!(host.len() <= src.bytes, "download of {} bytes from a {} byte buffer", host.len(), src.bytes);
if !host.is_empty() {
unsafe { cur::memcpy_dtoh_async(host, src.ptr, self.cu_stream())? };
}
self.synchronize()
}
pub fn download_range_into<T: Pod>(&self, src: &Buf, offset: usize, host: &mut [T]) -> Result<()> {
let host: &mut [u8] = bytemuck::cast_slice_mut(host);
let end = offset.checked_add(host.len());
ensure!(
end.is_some_and(|end| end <= src.bytes),
"download of {} bytes at {offset} from a {} byte buffer",
host.len(),
src.bytes
);
if !host.is_empty() {
unsafe { cur::memcpy_dtoh_async(host, src.ptr + offset as u64, self.cu_stream())? };
}
self.synchronize()
}
pub fn download(&self, t: &Tensor) -> Result<Vec<f32>> {
let mut host = vec![0f32; t.len()];
self.download_into(&t.buf, &mut host)?;
Ok(host)
}
pub fn clone_tensor(&self, t: &Tensor) -> Result<Tensor> {
let out = self.empty(t.shape())?;
self.copy_dtod(t.ptr(), out.ptr(), t.len() * 4)?;
Ok(out)
}
fn function(&self, name: &'static str, args: &[Arg]) -> Result<CUfunction> {
if let Some(k) = self.functions.borrow().get(name) {
k.check(name, args)?;
return Ok(k.f);
}
let f = unsafe { cur::module::get_function(self.module, CString::new(name)?) }
.wrap_err_with(|| format!("kernel {name} missing from the PTX"))?;
let k = Kernel { f, params: entry_params(self.ptx, name)? };
k.check(name, args)?;
self.functions.borrow_mut().insert(name, k);
Ok(f)
}
pub fn launch(
&self,
name: &'static str,
grid: (u32, u32, u32),
block: (u32, u32, u32),
smem: u32,
args: Vec<Arg>,
) -> Result<()> {
let f = self.function(name, &args)?;
ensure!(grid.0 as u64 * block.0 as u64 <= 1 << 32, "launch {name}: more than 2^32 threads along x");
let mut params: Vec<*mut c_void> = Vec::with_capacity(2 * args.len());
for a in &args {
match a {
Arg::Slice(ptr, len) => {
params.extend([ptr as *const u64 as *mut c_void, len as *const u64 as *mut c_void]);
}
Arg::U32(v) => params.push(v as *const u32 as *mut c_void),
Arg::I32(v) => params.push(v as *const i32 as *mut c_void),
Arg::F32(v) => params.push(v as *const f32 as *mut c_void),
}
}
if grid.0 == 0 || grid.1 == 0 || grid.2 == 0 {
return Ok(());
}
if smem > 48 * 1024 {
unsafe {
cu::cuFuncSetAttribute(
f,
cu::CUfunction_attribute::CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES,
smem as i32,
)
.result()?;
}
}
unsafe { cur::launch_kernel(f, grid, block, smem, self.cu_stream(), &mut params) }
.wrap_err_with(|| format!("launch {name}"))?;
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn linear_bf16(
&self,
mnk: (usize, usize, usize),
x: u64,
x_ld: usize,
w: u64,
out: (u64, bool),
beta: f32,
bias: u64,
epilogue: Epilogue,
) -> Result<()> {
self.lt.linear(self.cu_stream(), Operands::Bf16, mnk, x, x_ld, w, out, beta, bias, epilogue)
}
#[allow(clippy::too_many_arguments)]
pub fn linear_f32(
&self,
mnk: (usize, usize, usize),
x: u64,
x_ld: usize,
w: u64,
out: u64,
beta: f32,
bias: u64,
epilogue: Epilogue,
) -> Result<()> {
self.lt.linear(self.cu_stream(), self.fp32_operands, mnk, x, x_ld, w, (out, false), beta, bias, epilogue)
}
#[allow(clippy::too_many_arguments)]
pub fn gemm(
&self,
m: usize,
n: usize,
k: usize,
a: Mat,
b: Mat,
c: Mat,
batch: usize,
alpha: f32,
beta: f32,
) -> Result<()> {
let op = |t: bool| if t { blas::cublasOperation_t::CUBLAS_OP_T } else { blas::cublasOperation_t::CUBLAS_OP_N };
assert_eq!(a.bf16, b.bf16, "gemm inputs must share a type");
assert!(!c.bf16, "gemm output is FP32");
let (ty, compute) = if a.bf16 {
(blas::cudaDataType::CUDA_R_16BF, blas::cublasComputeType_t::CUBLAS_COMPUTE_32F)
} else {
(blas::cudaDataType::CUDA_R_32F, self.fp32_compute)
};
let status = unsafe {
(self.cublas.blas.gemm_strided_batched_ex)(
self.blas,
op(b.trans),
op(a.trans),
n as i32,
m as i32,
k as i32,
(&alpha as *const f32).cast(),
b.ptr as *const c_void,
ty,
b.ld as i32,
b.stride as i64,
a.ptr as *const c_void,
ty,
a.ld as i32,
a.stride as i64,
(&beta as *const f32).cast(),
c.ptr as *mut c_void,
blas::cudaDataType::CUDA_R_32F,
c.ld as i32,
c.stride as i64,
batch as i32,
compute,
blas::cublasGemmAlgo_t::CUBLAS_GEMM_DEFAULT,
)
};
check_blas(status).wrap_err_with(|| format!("gemm m={m} n={n} k={k} batch={batch}"))
}
}
struct Unowned<T: Copy>(T, fn(T));
impl<T: Copy> Unowned<T> {
fn into_inner(self) -> T {
let value = self.0;
std::mem::forget(self);
value
}
}
impl<T: Copy> Drop for Unowned<T> {
fn drop(&mut self) {
(self.1)(self.0);
}
}
impl Drop for Gpu {
fn drop(&mut self) {
if self.bind().is_err() {
return;
}
unsafe {
let _ = self.device.stream.synchronize();
(self.cublas.blas.destroy)(self.blas);
let _ = cur::module::unload(self.module);
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Param {
Ptr,
U64,
U32,
F32,
}
struct Kernel {
f: CUfunction,
params: Vec<Param>,
}
impl Kernel {
fn check(&self, name: &str, args: &[Arg]) -> Result<()> {
let mut host = args.iter().flat_map(Arg::params);
for (i, &ptx) in self.params.iter().enumerate() {
match host.next() {
Some(¶m) if param == ptx => {}
Some(¶m) => bail!("kernel {name} param {i}: the PTX declares {ptx:?}, the host passes {param:?}"),
None => bail!("kernel {name} takes {} params, the host passes {i}", self.params.len()),
}
}
let extra = host.count();
ensure!(
extra == 0,
"kernel {name} takes {} params, the host passes {}",
self.params.len(),
self.params.len() + extra
);
Ok(())
}
}
fn entry_params(ptx: &str, name: &str) -> Result<Vec<Param>> {
let entry = format!(".entry {name}(");
let start = ptx.find(&entry).ok_or_else(|| eyre!("kernel {name} missing from the PTX"))? + entry.len();
let end = ptx[start..].find(')').ok_or_else(|| eyre!("kernel {name}: unterminated PTX param list"))?;
ptx[start..start + end]
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.map(|line| {
let ty = line.strip_prefix(".param ").and_then(|rest| rest.split_whitespace().next());
match (ty, line.contains(" .ptr ")) {
(Some(".u64"), true) => Ok(Param::Ptr),
(Some(".u64"), false) => Ok(Param::U64),
(Some(".u32"), false) => Ok(Param::U32),
(Some(".f32"), false) => Ok(Param::F32),
_ => Err(eyre!("kernel {name}: unexpected PTX param `{line}`")),
}
})
.collect()
}
fn create_pool(ctx: &CudaContext) -> Result<CUmemoryPool> {
let pool = unsafe {
let mut props: cu::CUmemPoolProps = std::mem::zeroed();
props.allocType = cu::CUmemAllocationType::CU_MEM_ALLOCATION_TYPE_PINNED;
props.location.type_ = cu::CUmemLocationType::CU_MEM_LOCATION_TYPE_DEVICE;
props.location.id = ctx.cu_device();
cur::mem_pool::create(&props).wrap_err("create the CUDA memory pool")?
};
let mut threshold = u64::MAX;
unsafe {
cur::mem_pool::set_attribute(
pool,
cu::CUmemPool_attribute::CU_MEMPOOL_ATTR_RELEASE_THRESHOLD,
(&mut threshold as *mut u64).cast(),
)?;
}
Ok(pool)
}
fn check_libraries() -> Result<&'static Cublas> {
unsafe {
if !cu::is_culib_present() {
bail!("no NVIDIA driver found (libcuda.so.1); sam3rs needs an NVIDIA GPU with driver r580 or newer");
}
let mut version = 0;
cu::cuDriverGetVersion(&mut version).result()?;
if version < MIN_DRIVER {
bail!(
"the NVIDIA driver supports CUDA {}.{}; sam3rs needs CUDA 13.0 or newer (driver r580+)",
version / 1000,
version % 1000 / 10
);
}
}
let hint =
"install the CUDA 13 toolkit or `pip install nvidia-cublas`, and put its lib directory on LD_LIBRARY_PATH";
Cublas::get().map_err(|e| eyre!("cuBLAS 13 not found (libcublas.so.13, libcublasLt.so.13): {e:#}; {hint}"))
}
fn check_blas(status: blas::cublasStatus_t) -> Result<()> {
if status == blas::cublasStatus_t::CUBLAS_STATUS_SUCCESS { Ok(()) } else { bail!("cuBLAS error {status:?}") }
}
pub fn blocks(n: usize, block: u32) -> u32 {
u32::try_from(n.div_ceil(block as usize)).expect("grid too large")
}
#[cfg(test)]
mod tests {
use super::{PTX_SM80, PTX_SM120, entry_params};
#[test]
fn ptx_params_parse() {
let names: Vec<&str> = PTX_SM120
.match_indices(".entry ")
.map(|(i, m)| {
let rest = &PTX_SM120[i + m.len()..];
&rest[..rest.find('(').unwrap()]
})
.collect();
assert!(names.len() > 40, "found {} entries", names.len());
for name in names {
let params = entry_params(PTX_SM120, name).unwrap();
assert!(!params.is_empty(), "{name} has no params");
assert_eq!(params, entry_params(PTX_SM80, name).unwrap(), "{name} differs between the tiers");
}
}
}