use std::sync::Arc;
use wgpu::{Adapter, Device as WgpuDevice, Queue};
use crate::backend::ComputeEngine;
pub(crate) struct GpuContext {
pub(crate) adapter: Adapter,
pub(crate) device: WgpuDevice,
pub(crate) queue: Queue,
pub(crate) engine: ComputeEngine,
}
#[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()?;
let engine = ComputeEngine::new(&device);
Some(Self {
kind: Kind::Gpu(Arc::new(GpuContext {
adapter,
device,
queue,
engine,
})),
})
}
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(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()
}
}