()
| 88 | |
| 89 | |
| 90 | def test_multi_output(): |
| 91 | data_shape = (9, 2, 6) |
| 92 | av = np.random.random(data_shape).astype(np.float32) |
| 93 | bv = np.random.random(data_shape).astype(np.float32) |
| 94 | |
| 95 | class MulFunc(Function): |
| 96 | def forward(self, a, b): |
| 97 | self.a = a |
| 98 | self.b = b |
| 99 | return a * b, a + b |
| 100 | |
| 101 | def backward(self, grad_1, grad_2): |
| 102 | return grad_1 * (self.b + 1), grad_2 * (self.a + 1) |
| 103 | |
| 104 | class Simple(Module): |
| 105 | def __init__(self, a, b): |
| 106 | super().__init__() |
| 107 | self.a = Parameter(a, dtype=np.float32) |
| 108 | self.b = Parameter(b, dtype=np.float32) |
| 109 | self.layer1 = MulFunc() |
| 110 | |
| 111 | def forward(self): |
| 112 | x, y = self.layer1(self.a, self.b) |
| 113 | return x + y |
| 114 | |
| 115 | net = Simple(av, bv) |
| 116 | gm = ad.GradManager().attach(net.parameters()) |
| 117 | opt = optimizer.SGD(net.parameters(), lr=1.0) |
| 118 | |
| 119 | opt.clear_grad() |
| 120 | with gm: |
| 121 | loss = net() |
| 122 | gm.backward(loss.sum()) |
| 123 | opt.step() |
| 124 | |
| 125 | np.testing.assert_almost_equal(loss.numpy(), (av * bv + av + bv), decimal=6) |
| 126 | np.testing.assert_almost_equal(net.a.numpy(), (av - bv - 1), decimal=6) |
| 127 | np.testing.assert_almost_equal(net.b.numpy(), (bv - av - 1), decimal=6) |
| 128 | |
| 129 | |
| 130 | def test_skip_invalid_grad(): |
nothing calls this directly
no test coverage detected