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

Function test_ste

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

Source from the content-addressed store, hash-verified

166
167
168def test_ste():
169 class STE(Function):
170 def forward(self, x):
171 maxv, minv = x.max(), x.min()
172 scale = F.maximum(maxv, -minv) / 127
173 return F.round(x / scale) * scale
174
175 def backward(self, grad_y):
176 return grad_y
177
178 class Simple(Module):
179 def __init__(self, a):
180 super().__init__()
181 self.a = Parameter(a, dtype=np.float32)
182 self.layer1 = STE()
183
184 def forward(self):
185 x = self.layer1(self.a)
186 x = (x * 2.0).sum()
187 return x
188
189 data_shape = (1, 9, 2, 6)
190 av = np.random.random(data_shape).astype(np.float32)
191 net = Simple(av)
192 optim = optimizer.SGD(net.parameters(), lr=1.0)
193 gm = ad.GradManager().attach(net.parameters())
194 optim.clear_grad()
195
196 with gm:
197 loss = net()
198 gm.backward(loss.sum())
199 optim.step()
200
201 np.testing.assert_almost_equal(
202 net.a.numpy(),
203 av - np.broadcast_to(np.array([2.0], dtype=np.float32), data_shape),
204 )
205
206
207def test_deepcopy():

Callers

nothing calls this directly

Calls 13

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

Tested by

no test coverage detected