Skip to content

Instantly share code, notes, and snippets.

@logancyang
Last active June 26, 2020 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save logancyang/a976cf6bcecebab8b3cd973a89730ae1 to your computer and use it in GitHub Desktop.
Save logancyang/a976cf6bcecebab8b3cd973a89730ae1 to your computer and use it in GitHub Desktop.
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