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.

quantize.py 2.6 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. from megengine import module as Float
  9. from megengine.module import qat as QAT
  10. from megengine.quantization.quantize import _get_quantable_module_names, quantize_qat
  11. def test_get_quantable_module_names():
  12. # need to make sure names from Quantized and QAT are the same
  13. def _get_qat_module_names():
  14. def is_qat(key: str):
  15. value = getattr(QAT, key)
  16. return (
  17. isinstance(value, type)
  18. and issubclass(value, QAT.QATModule)
  19. and value != QAT.QATModule
  20. )
  21. # source should have all quantable modules' names
  22. quantable_module_names = [key for key in dir(QAT) if is_qat(key)]
  23. return quantable_module_names
  24. qat_module_names = _get_qat_module_names()
  25. quantized_module_names = _get_quantable_module_names()
  26. assert set(qat_module_names) == set(quantized_module_names)
  27. for key in qat_module_names:
  28. value = getattr(Float, key)
  29. assert (
  30. isinstance(value, type)
  31. and issubclass(value, Float.Module)
  32. and value != Float.Module
  33. )
  34. def test_disable_quantize():
  35. class Net(Float.Module):
  36. def __init__(self):
  37. super().__init__()
  38. self.conv = Float.ConvBnRelu2d(3, 3, 3)
  39. self.conv.disable_quantize()
  40. def forward(self, x):
  41. return self.conv(x)
  42. net = Net()
  43. qat_net = quantize_qat(net, inplace=False)
  44. assert isinstance(qat_net.conv, Float.ConvBnRelu2d)
  45. assert isinstance(qat_net.conv.conv, Float.Conv2d)
  46. def test_convert_with_custom_mapping():
  47. class FloatExample(Float.Module):
  48. def forward(self, x):
  49. return x
  50. class QATExample(QAT.QATModule):
  51. def forward(self, x):
  52. return x
  53. @classmethod
  54. def from_float_module(cls, float_module):
  55. return cls()
  56. class Net(Float.Module):
  57. def __init__(self):
  58. super().__init__()
  59. self.example = FloatExample()
  60. def forward(self, x):
  61. return self.example(x)
  62. net = Net()
  63. qat_net = quantize_qat(net, inplace=False, mapping={FloatExample: QATExample})
  64. assert isinstance(qat_net.example, QATExample)

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台