use std::sync::{Arc, RwLock};
use fuel_graph::{Graph, NodeId};
use fuel_ir::DType;
use crate::kernel::{BindingEntry, OpParams};
use fuel_ir::Result;
use fuel_ir::probe::BackendId;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProbeTensor {
pub dtype: DType,
pub shape: Vec<usize>,
pub bytes: Vec<u8>,
}
pub trait ProbeDevice: Send + Sync {
fn backend(&self) -> BackendId;
fn invoke_candidate(
&self,
entry: &BindingEntry,
params: &OpParams,
inputs: &[ProbeTensor],
out_dtype: DType,
out_shape: &[usize],
) -> Result<ProbeTensor>;
fn realize(
&self,
graph: Arc<RwLock<Graph>>,
sink: NodeId,
inputs: &[(NodeId, ProbeTensor)],
) -> Result<ProbeTensor>;
}
#[cfg(feature = "cuda")]
pub struct CudaProbeDevice {
device: fuel_cuda_backend::CudaDevice,
}
#[cfg(feature = "cuda")]
impl CudaProbeDevice {
pub fn new(device: fuel_cuda_backend::CudaDevice) -> Self {
Self { device }
}
}
#[cfg(feature = "cuda")]
impl ProbeDevice for CudaProbeDevice {
fn backend(&self) -> BackendId {
BackendId::Cuda
}
fn invoke_candidate(
&self,
entry: &BindingEntry,
params: &OpParams,
inputs: &[ProbeTensor],
out_dtype: DType,
out_shape: &[usize],
) -> Result<ProbeTensor> {
use crate::fkc::verify::{CudaInvoker, HostTensor, KernelInvoker};
use fuel_ir::Error;
let host: Vec<HostTensor> = inputs
.iter()
.map(|t| HostTensor {
dtype: t.dtype,
shape: t.shape.clone(),
bytes: t.bytes.clone(),
})
.collect();
let inv = CudaInvoker::new(self.device.clone(), out_dtype, out_shape.to_vec())
.with_params(params.clone());
let out = inv.invoke(entry, &host).map_err(|e| {
use crate::fkc::verify::VerifyError;
match e {
VerifyError::Invoke(m) | VerifyError::Backend(m) => Error::Msg(m),
VerifyError::NoReference => Error::Msg("no reference".to_string()),
}
})?;
Ok(ProbeTensor {
dtype: out.dtype,
shape: out.shape,
bytes: out.bytes,
})
}
fn realize(
&self,
graph: Arc<RwLock<Graph>>,
sink: NodeId,
inputs: &[(NodeId, ProbeTensor)],
) -> Result<ProbeTensor> {
use crate::pipelined::{DeviceRegistry, PipelinedExecutor, StorageCache};
use fuel_cuda_backend::CudaStorageBytes;
use fuel_ir::Error;
let mut cache = StorageCache::new();
for (id, t) in inputs {
let cb = CudaStorageBytes::from_cpu_bytes(&self.device, &t.bytes)?;
cache.insert(
*id,
Arc::new(RwLock::new(fuel_memory::Storage::new(
fuel_memory::BackendStorage::Cuda(cb),
t.dtype,
))),
);
}
let (out_arc, layout) = PipelinedExecutor::realize_with_devices(
graph,
sink,
cache,
DeviceRegistry::new().with_cuda(self.device.clone()),
)?;
let guard = out_arc.read().map_err(|_| {
Error::Msg("CudaProbeDevice::realize: output storage RwLock poisoned".to_string())
})?;
let bytes = match &guard.inner {
fuel_memory::BackendStorage::Cuda(c) => c.to_cpu_bytes()?,
#[allow(unreachable_patterns)]
_ => {
return Err(Error::Msg(
"CudaProbeDevice::realize: realized output storage is not CUDA".to_string(),
));
}
};
Ok(ProbeTensor {
dtype: guard.dtype,
shape: layout.shape().dims().to_vec(),
bytes,
})
}
}