MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / test_multi_output

Function test_multi_output

imperative/python/test/unit/core/test_function.py:90–127  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

88
89
90def 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
130def test_skip_invalid_grad():

Callers

nothing calls this directly

Calls 11

parametersMethod · 0.80
SimpleClass · 0.70
astypeMethod · 0.45
attachMethod · 0.45
GradManagerMethod · 0.45
SGDMethod · 0.45
clear_gradMethod · 0.45
backwardMethod · 0.45
sumMethod · 0.45
stepMethod · 0.45
numpyMethod · 0.45

Tested by

no test coverage detected