You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_init.py 2.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import numpy as np
  10. import pytest
  11. from megengine import tensor
  12. from megengine.module import Conv1d, Conv2d, Conv3d, Linear
  13. from megengine.module.init import calculate_fan_in_and_fan_out, fill_
  14. def test_fill_():
  15. x = tensor(np.zeros((2, 3, 4)), dtype=np.float32)
  16. fill_(x, 5.0)
  17. np.testing.assert_array_equal(
  18. x.numpy(), np.full(shape=(2, 3, 4), fill_value=5.0, dtype=np.float32)
  19. )
  20. def test_calculate_fan_in_and_fan_out():
  21. l = Linear(in_features=3, out_features=8)
  22. fanin, fanout = calculate_fan_in_and_fan_out(l.weight)
  23. assert fanin == 3
  24. assert fanout == 8
  25. with pytest.raises(ValueError):
  26. calculate_fan_in_and_fan_out(l.bias)
  27. l = Conv1d(in_channels=2, out_channels=3, kernel_size=5)
  28. fanin, fanout = calculate_fan_in_and_fan_out(l.weight)
  29. assert fanin == 2 * 5
  30. assert fanout == 3 * 5
  31. # FIXME: will be wrong for group conv1d
  32. # l = Conv1d(in_channels=2, out_channels=4, kernel_size=5, groups=2)
  33. # fanin, fanout = calculate_fan_in_and_fan_out(l.weight)
  34. # assert fanin == 2 // 2 * 5
  35. # assert fanout == 4 // 2 * 5
  36. l = Conv2d(in_channels=2, out_channels=3, kernel_size=(5, 7))
  37. fanin, fanout = calculate_fan_in_and_fan_out(l.weight)
  38. assert fanin == 2 * 5 * 7
  39. assert fanout == 3 * 5 * 7
  40. l = Conv2d(in_channels=2, out_channels=4, kernel_size=(5, 7), groups=2)
  41. fanin, fanout = calculate_fan_in_and_fan_out(l.weight)
  42. assert fanin == 2 // 2 * 5 * 7
  43. assert fanout == 4 // 2 * 5 * 7
  44. # FIXME: will be wrong for conv3d
  45. # l = Conv3d(in_channels=2, out_channels=3, kernel_size=(5, 7, 9))
  46. # fanin, fanout = calculate_fan_in_and_fan_out(l.weight)
  47. # assert fanin == 2 * 5 * 7 * 9
  48. # assert fanout == 3 * 5 * 7 * 9
  49. l = Conv3d(in_channels=2, out_channels=4, kernel_size=(5, 7, 9), groups=2)
  50. fanin, fanout = calculate_fan_in_and_fan_out(l.weight)
  51. assert fanin == 2 // 2 * 5 * 7 * 9
  52. assert fanout == 4 // 2 * 5 * 7 * 9