(affine)
| 792 | |
| 793 | @pytest.mark.parametrize("affine", [True, False]) |
| 794 | def test_instance_norm(affine): |
| 795 | num_channels = 4 |
| 796 | weight_np = np.random.uniform(-0.5, 0.5, (num_channels)) |
| 797 | bias_np = np.random.uniform(-0.5, 0.5, (num_channels)) |
| 798 | |
| 799 | class OriginInstanceNormFunc(Module): |
| 800 | def __init__(self, eps=1e-5, affine=True, **kwargs): |
| 801 | super().__init__(**kwargs) |
| 802 | self.num_channels = num_channels |
| 803 | self.eps = eps |
| 804 | self.affine = affine |
| 805 | if self.affine: |
| 806 | self.weight = Parameter(weight_np) |
| 807 | self.bias = Parameter(bias_np) |
| 808 | else: |
| 809 | self.weight = None |
| 810 | self.bias = None |
| 811 | |
| 812 | def forward(self, x): |
| 813 | N, C, H, W = x.shape |
| 814 | x = x.reshape(N, self.num_channels, -1) |
| 815 | mean = x.mean(axis=2, keepdims=True) |
| 816 | var = (x * x).mean(axis=2, keepdims=True) - mean * mean |
| 817 | x = (x - mean) / F.sqrt(var + self.eps) |
| 818 | x = x.reshape(N, C, H, W) |
| 819 | if self.affine: |
| 820 | x = self.weight.reshape(1, -1, 1, 1) * x + self.bias.reshape( |
| 821 | 1, -1, 1, 1 |
| 822 | ) |
| 823 | return x |
| 824 | |
| 825 | inp = np.random.uniform(-0.5, 0.5, (2, num_channels, 10, 16)).astype("float32") |
| 826 | mge_inp = Tensor(inp) |
| 827 | mge_m = InstanceNorm(num_channels, affine=affine) |
| 828 | mge_m.weight = Parameter(weight_np) |
| 829 | mge_m.bias = Parameter(bias_np) |
| 830 | |
| 831 | ori_inp = Tensor(inp) |
| 832 | ori_m = OriginInstanceNormFunc(affine=affine) |
| 833 | |
| 834 | mge_im = mge.autodiff.GradManager().attach((*mge_m.parameters(), mge_inp)) |
| 835 | ori_im = mge.autodiff.GradManager().attach((*ori_m.parameters(), ori_inp)) |
| 836 | dy = Tensor(np.random.uniform(-0.5, 0.5, inp.shape)) |
| 837 | |
| 838 | for i in range(2): |
| 839 | with mge_im: |
| 840 | mge_output = mge_m(mge_inp) |
| 841 | |
| 842 | mge_im.backward(mge_output, dy) |
| 843 | |
| 844 | with ori_im: |
| 845 | ori_output = ori_m(ori_inp) |
| 846 | |
| 847 | ori_im.backward(ori_output, dy) |
| 848 | |
| 849 | np.testing.assert_allclose(mge_output.numpy(), ori_output.numpy(), atol=1e-05) |
| 850 | np.testing.assert_allclose( |
| 851 | ori_inp.grad.numpy(), mge_inp.grad.numpy(), atol=1e-04 |
nothing calls this directly
no test coverage detected