Last active
June 26, 2020 23:05
-
-
Save logancyang/a976cf6bcecebab8b3cd973a89730ae1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Tensor: | |
... | |
def backward(self): | |
# topological order all of the parents in the graph | |
topo = [] | |
visited = set() | |
def build_topo(v): | |
if v not in visited: | |
visited.add(v) | |
for parent in v._prev: | |
build_topo(parent) | |
topo.append(v) | |
build_topo(self) | |
# Initialize the gradient of the last node as 1 | |
self.grad = 1 | |
# Go one variable at a time and apply the chain rule to get its gradient | |
for v in reversed(topo): | |
v._backward() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment