Adding requires_grad flag to Value class #12
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I've added a
requires_grad
flag to theValue
class that defaults toFalse
, mimicking PyTorch's behavior.The topological sort of the computational graph can then stop expanding nodes that don't require gradient propagation. E.g. in expressions such as
x + 2
the conversion of the scalar2
toValue(2)
will no longer propagate the gradient for that node.I've also incorporated these changes into the neural network where all parameters receive
requires_grad=True
. All unit tests continue to pass and the demo notebook finds the exact same loss after 99 iterations.Note that I also did some other small refactorings such as the separation between local gradient computation and propagation. This made it easier to selectively propagate the gradient based on the
requires_grad
flags. I've renamed the internal_backward
attribute to a constructor argumentgradient_fn
.All in all, the
engine.py
module was reduced by 15 lines, and weighs in at less than 80 lines now.