Custom Autograd Function
For experimental architectures or custom CUDA kernels, you can register custom autograd operators by implementing the BackwardFn trait.
Implementing BackwardFn
rust
use darkforest_core::autograd::{BackwardFn, TapeNode};
use darkforest_core::tensor::Tensor;
pub struct GELUBackward {
saved_input: Tensor,
}
impl BackwardFn for GELUBackward {
fn apply(&self, grad_output: &Tensor) -> Vec<Tensor> {
// Compute GELU derivative:
// 0.5 * (1.0 + erf(x/sqrt(2))) + (x / sqrt(2*pi)) * exp(-x^2 / 2)
let dx = compute_gelu_grad(&self.saved_input, grad_output);
vec![dx]
}
}
Registering on the Tape
rust
pub fn gelu(input: &Tensor) -> Tensor {
let output = compute_gelu_forward(input);
if input.requires_grad() {
let backward_fn = Box::new(GELUBackward {
saved_input: input.clone(),
});
TapeNode::push(backward_fn, vec![input.node_id()]);
}
output
}
This modularity allows researchers to benchmark novel activation functions and fused kernels with full autograd support.