use anyhow::Result;
use scirs2_core::numeric::Float;
use std::fmt::Debug;
use tenrso_core::DenseND;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OperationId(pub u64);
pub trait AdOperation<T>: Debug
where
T: Float + 'static,
{
fn forward(&self) -> Result<Vec<DenseND<T>>>;
fn backward(&self, output_grads: &[DenseND<T>]) -> Result<Vec<DenseND<T>>>;
fn name(&self) -> &str;
fn num_inputs(&self) -> usize;
fn num_outputs(&self) -> usize;
}
pub trait AdContext<T>
where
T: Float + 'static,
{
fn register_operation(&mut self, op: Box<dyn AdOperation<T>>) -> OperationId;
fn backward(&mut self, op_id: OperationId, grad: &DenseND<T>) -> Result<()>;
fn clear(&mut self);
fn get_gradient(&self, tensor_id: u64) -> Option<&DenseND<T>>;
}
pub struct GenericAdAdapter<T>
where
T: Float + 'static,
{
operations: Vec<Box<dyn AdOperation<T>>>,
gradients: std::collections::HashMap<u64, DenseND<T>>,
next_op_id: u64,
recording: bool,
}
impl<T> GenericAdAdapter<T>
where
T: Float + 'static,
{
pub fn new() -> Self {
Self {
operations: Vec::new(),
gradients: std::collections::HashMap::new(),
next_op_id: 0,
recording: true,
}
}
pub fn start_recording(&mut self) {
self.recording = true;
}
pub fn stop_recording(&mut self) {
self.recording = false;
}
pub fn is_recording(&self) -> bool {
self.recording
}
pub fn num_operations(&self) -> usize {
self.operations.len()
}
}
impl<T> Default for GenericAdAdapter<T>
where
T: Float + 'static,
{
fn default() -> Self {
Self::new()
}
}
impl<T> AdContext<T> for GenericAdAdapter<T>
where
T: Float + 'static,
{
fn register_operation(&mut self, op: Box<dyn AdOperation<T>>) -> OperationId {
if !self.recording {
return OperationId(0); }
let op_id = OperationId(self.next_op_id);
self.next_op_id += 1;
self.operations.push(op);
op_id
}
fn backward(&mut self, _op_id: OperationId, grad: &DenseND<T>) -> Result<()> {
let mut current_grads = vec![grad.clone()];
for op in self.operations.iter().rev() {
let input_grads = op.backward(¤t_grads)?;
for (idx, grad) in input_grads.iter().enumerate() {
let tensor_id = self.operations.len() as u64 + idx as u64;
self.gradients.insert(tensor_id, grad.clone());
}
current_grads = input_grads;
}
Ok(())
}
fn clear(&mut self) {
self.operations.clear();
self.gradients.clear();
self.next_op_id = 0;
}
fn get_gradient(&self, tensor_id: u64) -> Option<&DenseND<T>> {
self.gradients.get(&tensor_id)
}
}
#[derive(Debug)]
pub struct TensorlogicAdapter {
_private: (),
}
impl TensorlogicAdapter {
pub fn new() -> Self {
Self { _private: () }
}
pub fn register_tenrso_ops(&mut self) {
}
pub fn to_tensorlogic<T>(&self, _tensor: &DenseND<T>) -> Result<()>
where
T: Float + 'static,
{
anyhow::bail!("Tensorlogic integration not yet implemented")
}
pub fn from_tensorlogic<T>(&self) -> Result<DenseND<T>>
where
T: Float + 'static,
{
anyhow::bail!("Tensorlogic integration not yet implemented")
}
}
impl Default for TensorlogicAdapter {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_generic_ad_adapter_creation() {
let adapter = GenericAdAdapter::<f64>::new();
assert!(adapter.is_recording());
assert_eq!(adapter.num_operations(), 0);
}
#[test]
fn test_generic_ad_adapter_recording() {
let mut adapter = GenericAdAdapter::<f64>::new();
assert!(adapter.is_recording());
adapter.stop_recording();
assert!(!adapter.is_recording());
adapter.start_recording();
assert!(adapter.is_recording());
}
#[test]
fn test_generic_ad_adapter_clear() {
let mut adapter = GenericAdAdapter::<f64>::new();
adapter.clear();
assert_eq!(adapter.num_operations(), 0);
}
#[test]
fn test_tensorlogic_adapter_creation() {
let _adapter = TensorlogicAdapter::new();
}
}