()
| 264 | |
| 265 | |
| 266 | def test_clear_grad(): |
| 267 | class StopGradient(Function): |
| 268 | def forward(self, a): |
| 269 | return a |
| 270 | |
| 271 | def backward(self, *_): |
| 272 | return None |
| 273 | |
| 274 | class Simple(Module): |
| 275 | def __init__(self, a): |
| 276 | super().__init__() |
| 277 | self.a = Parameter(a, dtype=np.float32) |
| 278 | self.layer = StopGradient() |
| 279 | |
| 280 | def forward(self): |
| 281 | b = self.a * 3.0 |
| 282 | c = self.a * 4.0 |
| 283 | return self.layer(b) + c |
| 284 | |
| 285 | a = tensor(np.array([1.0], dtype=np.float32)) |
| 286 | net = Simple(a) |
| 287 | optim = optimizer.SGD(net.parameters(), lr=1.0) |
| 288 | gm = ad.GradManager().attach(net.parameters()) |
| 289 | optim.clear_grad() |
| 290 | |
| 291 | with gm: |
| 292 | loss = net() |
| 293 | gm.backward(loss.sum()) |
| 294 | optim.step() |
| 295 | np.testing.assert_almost_equal( |
| 296 | net.a.numpy(), np.array([1.0 - 4.0], dtype=np.float32), |
| 297 | ) |
| 298 | |
| 299 | |
| 300 | def test_throw_on_non_tensor_argument(): |
nothing calls this directly
no test coverage detected