use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use super::Tensor;
thread_local! {
static GRAD_ENABLED: Cell<bool> = const { Cell::new(true) };
}
pub fn is_grad_enabled() -> bool {
GRAD_ENABLED.with(Cell::get)
}
pub fn no_grad<R>(f: impl FnOnce() -> R) -> R {
let _guard = NoGradGuard::new();
f()
}
pub struct NoGradGuard {
previous: bool,
}
impl NoGradGuard {
pub fn new() -> Self {
let previous = GRAD_ENABLED.with(|g| g.replace(false));
Self { previous }
}
}
impl Default for NoGradGuard {
fn default() -> Self {
Self::new()
}
}
impl Drop for NoGradGuard {
fn drop(&mut self) {
GRAD_ENABLED.with(|g| g.set(self.previous));
}
}
pub(crate) type BackwardFn = Box<dyn Fn(&Tensor) -> Vec<Option<Tensor>> + Send + Sync>;
pub(crate) struct Node {
pub(crate) name: &'static str,
pub(crate) inputs: Vec<Tensor>,
pub(crate) backward: BackwardFn,
}
impl Drop for Node {
fn drop(&mut self) {
let mut stack: Vec<Arc<Node>> = self
.inputs
.iter_mut()
.filter_map(|t| t.node.take())
.collect();
while let Some(node) = stack.pop() {
if let Ok(mut node) = Arc::try_unwrap(node) {
stack.extend(node.inputs.iter_mut().filter_map(|t| t.node.take()));
}
}
}
}
impl Tensor {
pub(crate) fn with_node(
mut self,
name: &'static str,
inputs: Vec<Tensor>,
backward: impl Fn(&Tensor) -> Vec<Option<Tensor>> + Send + Sync + 'static,
) -> Tensor {
if is_grad_enabled() && inputs.iter().any(|t| t.requires_grad) {
self.requires_grad = true;
self.node = Some(Arc::new(Node {
name,
inputs,
backward: Box::new(backward),
}));
}
self
}
pub fn grad_fn_name(&self) -> Option<&'static str> {
self.node.as_ref().map(|n| n.name)
}
pub fn backward(&self) {
let seed = Tensor::ones(&self.shape, &self.device);
self.backward_with(&seed);
}
#[expect(
clippy::expect_used,
reason = "lock poisoning means another thread panicked while holding the lock"
)]
pub fn backward_with(&self, grad: &Tensor) {
assert_eq!(
grad.shape, self.shape,
"gradient shape must match the tensor"
);
if !self.requires_grad {
return;
}
let _guard = NoGradGuard::new();
let order = topological_order(self);
let mut pending: HashMap<usize, Tensor> = HashMap::new();
pending.insert(self.id(), grad.detach());
for tensor in order.iter().rev() {
let Some(g) = pending.remove(&tensor.id()) else {
continue;
};
match &tensor.node {
Some(node) => {
let input_grads = (node.backward)(&g);
debug_assert_eq!(input_grads.len(), node.inputs.len());
for (input, input_grad) in node.inputs.iter().zip(input_grads) {
let Some(input_grad) = input_grad else {
continue;
};
if !input.requires_grad {
continue;
}
assert_eq!(
input_grad.shape, input.shape,
"backward of '{}' produced a gradient of the wrong shape",
node.name
);
let merged = match pending.remove(&input.id()) {
Some(existing) => existing.add(&input_grad),
None => input_grad,
};
pending.insert(input.id(), merged);
}
}
None => {
let mut slot = tensor.grad.write().expect("grad lock poisoned");
let total = match slot.take() {
Some(existing) => existing.add(&g),
None => g.deep_clone(),
};
*slot = Some(total);
}
}
}
}
}
fn topological_order(root: &Tensor) -> Vec<Tensor> {
let mut order = Vec::new();
let mut visited = HashSet::new();
let mut stack = vec![(root.clone(), false)];
while let Some((tensor, expanded)) = stack.pop() {
if expanded {
order.push(tensor);
continue;
}
if !visited.insert(tensor.id()) {
continue;
}
let inputs: Vec<Tensor> = tensor
.node
.as_ref()
.map(|n| n.inputs.clone())
.unwrap_or_default();
stack.push((tensor, true));
for input in inputs {
if input.requires_grad && !visited.contains(&input.id()) {
stack.push((input, false));
}
}
}
order
}