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

Function test_grou_norm

imperative/python/test/unit/module/test_module.py:724–790  ·  view source on GitHub ↗
(affine)

Source from the content-addressed store, hash-verified

722@pytest.mark.skip(reason="pytest aborted")
723@pytest.mark.parametrize("affine", [True, False])
724def test_grou_norm(affine):
725 num_groups = 256
726 num_channels = 256
727 weight_np = np.random.uniform(-0.5, 0.5, (num_channels))
728 bias_np = np.random.uniform(-0.5, 0.5, (num_channels))
729
730 class OriginGroupNormFunc(Module):
731 def __init__(self, eps=1e-5, affine=True, **kwargs):
732 super().__init__(**kwargs)
733 assert num_channels % num_groups == 0
734 self.num_groups = num_groups
735 self.num_channels = num_channels
736 self.eps = eps
737 self.affine = affine
738 if self.affine:
739 self.weight = Parameter(weight_np)
740 self.bias = Parameter(bias_np)
741 else:
742 self.weight = None
743 self.bias = None
744
745 def forward(self, x):
746 N, C, H, W = x.shape
747 x = x.reshape(N, self.num_groups, -1)
748 mean = x.mean(axis=2, keepdims=True)
749 var = (x * x).mean(axis=2, keepdims=True) - mean * mean
750 x = (x - mean) / F.sqrt(var + self.eps)
751 x = x.reshape(N, C, H, W)
752 if self.affine:
753 x = self.weight.reshape(1, -1, 1, 1) * x + self.bias.reshape(
754 1, -1, 1, 1
755 )
756 return x
757
758 inp = np.random.uniform(-0.5, 0.5, (2, num_channels, 10, 16)).astype("float32")
759 mge_inp = Tensor(inp)
760 mge_m = GroupNorm(num_groups, num_channels, affine=affine)
761 mge_m.weight = Parameter(weight_np)
762 mge_m.bias = Parameter(bias_np)
763 ori_inp = Tensor(inp)
764 ori_m = OriginGroupNormFunc(affine=affine)
765
766 mge_gm = mge.autodiff.GradManager().attach((*mge_m.parameters(), mge_inp))
767 ori_gm = mge.autodiff.GradManager().attach((*ori_m.parameters(), ori_inp))
768 dy = Tensor(np.random.uniform(-0.5, 0.5, inp.shape))
769 for i in range(2):
770 with mge_gm:
771 mge_output = mge_m(mge_inp)
772
773 mge_gm.backward(mge_output, dy)
774
775 with ori_gm:
776 ori_output = ori_m(ori_inp)
777
778 ori_gm.backward(ori_output, dy)
779
780 np.testing.assert_allclose(mge_output.numpy(), ori_output.numpy(), atol=1e-05)
781 np.testing.assert_allclose(

Callers

nothing calls this directly

Calls 11

TensorClass · 0.90
GroupNormClass · 0.90
ParameterClass · 0.90
OriginGroupNormFuncClass · 0.85
uniformMethod · 0.80
parametersMethod · 0.80
astypeMethod · 0.45
attachMethod · 0.45
GradManagerMethod · 0.45
backwardMethod · 0.45
numpyMethod · 0.45

Tested by

no test coverage detected