backward method

void backward()

Implementation

void backward() {
  if (this.creator == null) {
    this.grad = 1.0 as T;
    return;
  }

  // A more robust topological sort using a stack
  List<Node> topo = [];
  Set<Node> visited = {};
  List<Node> stack = [];

  void buildTopo(Node? node) {
    if (node == null || visited.contains(node)) {
      return;
    }

    visited.add(node);
    for (var inputTensor in node.inputs) {
      if (inputTensor.creator != null) {
        buildTopo(inputTensor.creator!);
      }
    }
    topo.add(node);
  }

  buildTopo(this.creator!);

  this.grad = 1.0 as T;

  for (Node node in topo.reversed) {
    node.backwardFn();
  }
}