use std::collections::HashMap;
use std::num::NonZeroU64;
use std::sync::mpsc::{Receiver, TryRecvError};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use wgpu::{
Adapter, BindingResource, Buffer, BufferBinding, BufferUsages, CommandEncoder,
Device as WgpuDevice, Queue,
};
use crate::backend::{ComputeEngine, Dispatch};
const MAX_PENDING_OPS: usize = 256;
const ARGS_BYTES: usize = 256 * 1024;
const SPIN_WAIT: Duration = Duration::from_millis(10);
const POOL_BYTES: u64 = 128 << 20;
#[derive(Default)]
pub(crate) struct BufferPool {
free: HashMap<u64, Vec<Buffer>>,
bytes: u64,
}
pub(crate) struct GpuBuffer {
buffer: Option<Buffer>,
pool: Arc<Mutex<BufferPool>>,
}
impl std::ops::Deref for GpuBuffer {
type Target = Buffer;
fn deref(&self) -> &Buffer {
self.buffer.as_ref().expect("buffer used after drop")
}
}
impl Drop for GpuBuffer {
fn drop(&mut self) {
let Some(buffer) = self.buffer.take() else {
return;
};
let Ok(mut pool) = self.pool.lock() else {
return;
};
let size = buffer.size();
if pool.bytes + size <= POOL_BYTES {
pool.bytes += size;
pool.free.entry(size).or_default().push(buffer);
}
}
}
pub(crate) enum Arg<'a> {
Buffer(&'a Buffer),
Params([u32; 4]),
Meta(&'a [u32]),
}
pub(crate) struct GpuContext {
pub(crate) adapter: Adapter,
pub(crate) device: WgpuDevice,
pub(crate) queue: Queue,
pub(crate) engine: ComputeEngine,
args: Buffer,
align: usize,
pending: Mutex<Pending>,
pool: Arc<Mutex<BufferPool>>,
}
#[derive(Default)]
struct Pending {
encoder: Option<CommandEncoder>,
dispatches: Vec<Dispatch>,
args: Vec<u8>,
ops: usize,
}
impl GpuContext {
fn new(adapter: Adapter, device: WgpuDevice, queue: Queue) -> Self {
let engine = ComputeEngine::new(&device);
let limits = device.limits();
let align = limits
.min_uniform_buffer_offset_alignment
.max(limits.min_storage_buffer_offset_alignment)
.max(4) as usize;
let args = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Op arguments"),
size: ARGS_BYTES as u64,
usage: BufferUsages::UNIFORM | BufferUsages::STORAGE | BufferUsages::COPY_DST,
mapped_at_creation: false,
});
Self {
adapter,
device,
queue,
engine,
args,
align,
pending: Mutex::default(),
pool: Arc::default(),
}
}
pub(crate) fn buffer(&self, bytes: u64, create: impl FnOnce() -> Buffer) -> GpuBuffer {
let reused = {
let mut pool = self.pool.lock().expect("buffer pool lock poisoned");
let buffer = pool.free.get_mut(&bytes).and_then(Vec::pop);
if buffer.is_some() {
pool.bytes -= bytes;
}
buffer
};
self.adopt(reused.unwrap_or_else(create))
}
pub(crate) fn adopt(&self, buffer: Buffer) -> GpuBuffer {
GpuBuffer {
buffer: Some(buffer),
pool: Arc::clone(&self.pool),
}
}
fn lock(&self) -> MutexGuard<'_, Pending> {
self.pending.lock().expect("GPU command lock poisoned")
}
pub(crate) fn dispatch(
&self,
kernel: &'static str,
args: &[Arg<'_>],
workgroups: (u32, u32, u32),
) {
let padded = |bytes: usize| bytes.div_ceil(self.align) * self.align;
let needed: usize = args
.iter()
.map(|arg| match arg {
Arg::Buffer(_) => 0,
Arg::Params(_) => padded(16),
Arg::Meta(words) => padded(words.len().max(1) * 4),
})
.sum();
assert!(
needed <= ARGS_BYTES,
"kernel arguments exceed {ARGS_BYTES} bytes"
);
let mut pending = self.lock();
if pending.args.len() + needed > ARGS_BYTES {
self.submit(&mut pending);
}
let staged = &mut pending.args;
let resources = args
.iter()
.map(|arg| {
let bytes: &[u8] = match arg {
Arg::Buffer(buffer) => return buffer.as_entire_binding(),
Arg::Params(words) => bytemuck::cast_slice(words),
Arg::Meta([]) => &[0; 4],
Arg::Meta(words) => bytemuck::cast_slice(words),
};
let offset = staged.len();
staged.extend_from_slice(bytes);
staged.resize(padded(staged.len()), 0);
BindingResource::Buffer(BufferBinding {
buffer: &self.args,
offset: offset as u64,
size: NonZeroU64::new(bytes.len() as u64),
})
})
.collect();
let dispatch = self
.engine
.dispatch(&self.device, kernel, resources, workgroups);
pending.dispatches.push(dispatch);
self.count_op(&mut pending);
}
pub(crate) fn copy(&self, src: &Buffer, dst: &Buffer, bytes: u64) {
let mut pending = self.lock();
self.encoder(&mut pending)
.copy_buffer_to_buffer(src, 0, dst, 0, bytes);
self.count_op(&mut pending);
}
pub(crate) fn flush(&self) {
self.submit(&mut self.lock());
}
pub(crate) fn write_buffer(&self, buffer: &Buffer, data: &[u8]) {
let mut pending = self.lock();
self.submit(&mut pending);
self.queue.write_buffer(buffer, 0, data);
}
pub(crate) fn wait_for<T>(&self, rx: &Receiver<T>) -> T {
let start = Instant::now();
loop {
let blocking = start.elapsed() >= SPIN_WAIT;
self.device.poll(if blocking {
wgpu::Maintain::Wait
} else {
wgpu::Maintain::Poll
});
match rx.try_recv() {
Ok(value) => return value,
Err(TryRecvError::Empty) if !blocking => std::thread::yield_now(),
Err(TryRecvError::Empty) => {}
Err(TryRecvError::Disconnected) => panic!("GPU callback dropped"),
}
}
}
fn count_op(&self, pending: &mut Pending) {
pending.ops += 1;
if pending.ops >= MAX_PENDING_OPS {
self.submit(pending);
}
}
fn encoder<'p>(&self, pending: &'p mut Pending) -> &'p mut CommandEncoder {
let encoder = pending.encoder.get_or_insert_with(|| {
self.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Ferrotensor ops"),
})
});
if !pending.dispatches.is_empty() {
self.engine.encode(encoder, &pending.dispatches);
pending.dispatches.clear();
}
encoder
}
fn submit(&self, pending: &mut Pending) {
if pending.ops == 0 {
return;
}
self.encoder(pending);
if !pending.args.is_empty() {
self.queue.write_buffer(&self.args, 0, &pending.args);
pending.args.clear();
}
if let Some(encoder) = pending.encoder.take() {
self.queue.submit(std::iter::once(encoder.finish()));
}
pending.ops = 0;
}
}
#[derive(Clone)]
enum Kind {
Cpu,
Gpu(Arc<GpuContext>),
}
#[derive(Clone)]
pub struct Device {
kind: Kind,
}
impl Device {
pub fn new() -> Self {
Self::gpu().expect("no GPU adapter available; use Device::best() or Device::cpu()")
}
pub fn cpu() -> Self {
Self { kind: Kind::Cpu }
}
pub fn gpu() -> Option<Self> {
pollster::block_on(Self::gpu_async())
}
pub async fn gpu_async() -> Option<Self> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
..Default::default()
});
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: None,
force_fallback_adapter: false,
})
.await?;
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
label: Some("Ferrotensor Device"),
required_features: wgpu::Features::empty(),
required_limits: adapter.limits(),
},
None,
)
.await
.ok()?;
Some(Self {
kind: Kind::Gpu(Arc::new(GpuContext::new(adapter, device, queue))),
})
}
pub async fn new_async() -> Self {
Self::gpu_async()
.await
.expect("no GPU adapter available; use Device::best() or Device::cpu()")
}
pub fn best() -> Self {
Self::gpu().unwrap_or_else(Self::cpu)
}
pub fn is_cpu(&self) -> bool {
matches!(self.kind, Kind::Cpu)
}
pub fn is_gpu(&self) -> bool {
!self.is_cpu()
}
pub fn name(&self) -> String {
match &self.kind {
Kind::Cpu => "CPU".to_string(),
Kind::Gpu(ctx) => ctx.adapter.get_info().name,
}
}
pub fn backend(&self) -> String {
match &self.kind {
Kind::Cpu => "Cpu".to_string(),
Kind::Gpu(ctx) => format!("{:?}", ctx.adapter.get_info().backend),
}
}
pub fn supports_training(&self) -> bool {
true
}
pub fn same_as(&self, other: &Device) -> bool {
match (&self.kind, &other.kind) {
(Kind::Cpu, Kind::Cpu) => true,
(Kind::Gpu(a), Kind::Gpu(b)) => Arc::ptr_eq(a, b),
_ => false,
}
}
pub fn synchronize(&self) {
if let Some(ctx) = self.gpu_ctx() {
ctx.flush();
let (tx, rx) = std::sync::mpsc::channel();
ctx.queue.on_submitted_work_done(move || {
let _ = tx.send(());
});
ctx.wait_for(&rx);
}
}
pub(crate) fn gpu_ctx(&self) -> Option<&GpuContext> {
match &self.kind {
Kind::Cpu => None,
Kind::Gpu(ctx) => Some(ctx),
}
}
}
impl Default for Device {
fn default() -> Self {
Self::best()
}
}
impl std::fmt::Debug for Device {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Device")
.field("name", &self.name())
.field("backend", &self.backend())
.finish()
}
}