use std::any::Any;
use std::fmt;
use std::sync::Arc;
use tenferro_tensor::{AllocationDomainId, Engine, Tensor, TensorRead};
use super::{
EngineId, EventDomainDriver, EventDomainRun, ExecutionContextIdentity,
ImmediateEventDomainDriver,
};
use crate::extension_cache::ExtensionCacheStore;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct EngineTarget {
engine_id: EngineId,
context_identity: ExecutionContextIdentity,
allocation_domain: Option<AllocationDomainId>,
}
impl EngineTarget {
pub fn new(
engine_id: EngineId,
context_identity: ExecutionContextIdentity,
allocation_domain: Option<AllocationDomainId>,
) -> Self {
Self {
engine_id,
context_identity,
allocation_domain,
}
}
pub fn engine_id(&self) -> &EngineId {
&self.engine_id
}
pub fn context_identity(&self) -> ExecutionContextIdentity {
self.context_identity
}
pub fn allocation_domain(&self) -> Option<AllocationDomainId> {
self.allocation_domain
}
}
pub trait ExecutionEngine: Engine {
fn target(&self) -> EngineTarget;
fn take_extension_caches(&mut self) -> ExtensionCacheStore {
ExtensionCacheStore::new()
}
fn restore_extension_caches(&mut self, caches: ExtensionCacheStore) {
drop(caches);
}
fn mark_broken(&mut self) {}
fn event_domain_driver(&self) -> Arc<dyn EventDomainDriver> {
Arc::new(ImmediateEventDomainDriver::new())
}
fn retire_run(&mut self, mut run: Box<dyn EventDomainRun>) -> crate::Result<()> {
run.drain()
}
fn synchronize(&mut self) -> crate::Result<()> {
Ok(())
}
fn as_any_mut(&mut self) -> &mut dyn Any;
}
#[allow(clippy::large_enum_variant)]
pub enum Output<'a> {
Owned(Tensor),
Borrowed(TensorRead<'a>),
}
impl<'a> Output<'a> {
pub fn read(&self) -> TensorRead<'_> {
match self {
Self::Owned(tensor) => TensorRead::from_tensor(tensor),
Self::Borrowed(read) => read.clone(),
}
}
pub fn into_owned(self) -> Option<Tensor> {
match self {
Self::Owned(tensor) => Some(tensor),
Self::Borrowed(_) => None,
}
}
pub fn into_tensor(self, engine: &mut dyn Engine) -> tenferro_tensor::Result<Tensor> {
match self {
Self::Owned(tensor) => Ok(tensor),
Self::Borrowed(read) => engine.to_contiguous_read(read),
}
}
}
impl fmt::Debug for Output<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Owned(tensor) => formatter
.debug_struct("Output::Owned")
.field("dtype", &tensor.dtype())
.field("shape", &tensor.shape())
.finish(),
Self::Borrowed(read) => formatter
.debug_struct("Output::Borrowed")
.field("dtype", &read.dtype())
.field("shape", &read.shape())
.finish(),
}
}
}