use std::collections::HashSet;
use std::sync::Arc;
use super::{GradFn, Var};
use crate::runtime::Runtime;
use crate::tensor::TensorId;
pub(super) fn collect_captures<R: Runtime>(
output: &Var<R>,
boundary: TensorId,
known: &HashSet<TensorId>,
) -> Vec<TensorId> {
let mut visited: HashSet<TensorId> = HashSet::new();
let mut captures: Vec<TensorId> = Vec::new();
let mut stack: Vec<(TensorId, Option<Arc<dyn GradFn<R>>>)> =
vec![(output.id(), output.grad_fn().cloned())];
while let Some((id, grad_fn)) = stack.pop() {
if !visited.insert(id) {
continue;
}
let Some(gf) = grad_fn else {
if id.raw() < boundary.raw() && !known.contains(&id) {
captures.push(id);
}
continue;
};
for (input_id, input_grad_fn) in gf.inputs().iter().zip(gf.input_grad_fns()) {
stack.push((*input_id, input_grad_fn));
}
}
captures
}
#[cfg(test)]
mod tests {
use super::*;
use crate::autograd::{var_add, var_mul, var_sum};
use crate::runtime::cpu::{CpuDevice, CpuRuntime};
use crate::tensor::Tensor;
fn leaf(device: &CpuDevice, value: f32, requires_grad: bool) -> Var<CpuRuntime> {
Var::new(
Tensor::<CpuRuntime>::from_slice(&[value], &[1], device).unwrap(),
requires_grad,
)
}
#[test]
fn detached_only_segment_captures_nothing() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let x = leaf(&device, 3.0, false);
let known: HashSet<TensorId> = [x.id()].into_iter().collect();
let boundary = TensorId::new();
let y = var_mul(&x, &x, &client).unwrap();
assert!(collect_captures(&y, boundary, &known).is_empty());
}
#[test]
fn trainable_capture_is_found_once() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let x = leaf(&device, 3.0, false);
let w = leaf(&device, 2.0, true);
let known: HashSet<TensorId> = [x.id()].into_iter().collect();
let boundary = TensorId::new();
let a = var_mul(&x, &w, &client).unwrap();
let b = var_mul(&a, &w, &client).unwrap();
let out = var_sum(&b, &[], false, &client).unwrap();
assert_eq!(collect_captures(&out, boundary, &known), vec![w.id()]);
}
#[test]
fn captured_intermediate_resolves_to_its_leaves() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let a = leaf(&device, 2.0, true);
let h = var_mul(&a, &a, &client).unwrap();
let x = leaf(&device, 3.0, false);
let known: HashSet<TensorId> = [x.id()].into_iter().collect();
let boundary = TensorId::new();
let out = var_mul(&x, &h, &client).unwrap();
assert_eq!(collect_captures(&out, boundary, &known), vec![a.id()]);
}
#[test]
fn leaves_minted_inside_the_segment_are_ignored() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let x = leaf(&device, 3.0, false);
let w = leaf(&device, 2.0, true);
let known: HashSet<TensorId> = [x.id()].into_iter().collect();
let boundary = TensorId::new();
let inside = leaf(&device, 1.0, false);
let scaled = var_mul(&x, &w, &client).unwrap();
let out = var_add(&scaled, &inside, &client).unwrap();
assert_eq!(collect_captures(&out, boundary, &known), vec![w.id()]);
}
}