pub use super::build_module::BuildModule;
pub use super::to_device::*;
use crate::{shapes::Dtype, tensor_ops::Device};
use super::tensor_collection::*;
pub trait Module<Input> {
type Output;
type Error: core::fmt::Debug;
fn try_forward(&self, input: Input) -> Result<Self::Output, Self::Error>;
fn forward(&self, input: Input) -> Self::Output {
self.try_forward(input).unwrap()
}
}
pub trait ModuleMut<Input> {
type Output;
type Error: core::fmt::Debug;
fn try_forward_mut(&mut self, input: Input) -> Result<Self::Output, Self::Error>;
fn forward_mut(&mut self, input: Input) -> Self::Output {
self.try_forward_mut(input).unwrap()
}
}
pub trait BuildOnDevice<D: Device<E>, E: Dtype> {
type Built: BuildModule<D, E>;
fn build_on_device(device: &D) -> Self::Built {
Self::try_build_on_device(device).unwrap()
}
fn try_build_on_device(device: &D) -> Result<Self::Built, D::Err> {
Self::Built::try_build(device)
}
}
pub trait DeviceBuildExt {
fn build_module<M: BuildOnDevice<Self, E>, E: Dtype>(&self) -> M::Built
where
Self: Device<E>,
{
M::build_on_device(self)
}
fn try_build_module<M: BuildOnDevice<Self, E>, E: Dtype>(&self) -> Result<M::Built, Self::Err>
where
Self: Device<E>,
{
M::try_build_on_device(self)
}
}
impl DeviceBuildExt for crate::tensor::Cpu {}
#[cfg(feature = "cuda")]
impl DeviceBuildExt for crate::tensor::Cuda {}
pub trait ZeroSizedModule: Default {}
impl<T: ZeroSizedModule + BuildModule<D, E>, D: Device<E>, E: Dtype> BuildOnDevice<D, E> for T {
type Built = T;
}
impl<E: Dtype, D: Device<E>, T: ZeroSizedModule> TensorCollection<E, D> for T {
type To<E2: Dtype, D2: Device<E2>> = T;
fn iter_tensors<V: ModuleVisitor<Self, E, D>>(
visitor: &mut V,
) -> Result<Option<Self::To<V::E2, V::D2>>, V::Err> {
visitor.visit_fields((), |_| Default::default())
}
}
pub trait NonMutableModule {}
impl<M: NonMutableModule, T> ModuleMut<T> for M
where
Self: Module<T>,
{
type Output = <Self as Module<T>>::Output;
type Error = <Self as Module<T>>::Error;
fn try_forward_mut(&mut self, input: T) -> Result<Self::Output, Self::Error> {
self.try_forward(input)
}
}