Compute the gradients of the output w.r.t the parameters Args: y: the output tensor, e.g., the loss dy: gradient of the target w.r.t y; None indicates the gradient is 1.0; it can be used to rescale the loss. Return: a dictionary storing the gradient
(y, dy=None)
| 103 | |
| 104 | |
| 105 | def gradients(y, dy=None): |
| 106 | """ |
| 107 | Compute the gradients of the output w.r.t the parameters |
| 108 | |
| 109 | Args: |
| 110 | y: the output tensor, e.g., the loss |
| 111 | dy: gradient of the target w.r.t y; None indicates the gradient is 1.0; |
| 112 | it can be used to rescale the loss. |
| 113 | |
| 114 | Return: |
| 115 | a dictionary storing the gradient tensors of all tensors |
| 116 | whose stores_grad is true (e.g. parameter tensors) |
| 117 | """ |
| 118 | grads = {} # mapping: x->dx if x.stores_grad |
| 119 | for p, dp in backward(y, dy): |
| 120 | # TODO: this fn is only helper for test case for now. |
| 121 | # 1. could implement __hash__ or |
| 122 | # 2. make grad as a attribute of tensor class |
| 123 | # p.grad = dp |
| 124 | grads[id(p)] = dp |
| 125 | return grads |
| 126 | |
| 127 | |
| 128 | def backward(y, dy=None): |
nothing calls this directly
no test coverage detected