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.

serialization.py 4.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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 pickle
  10. import megengine._internal as mgb
  11. from ..utils.max_recursion_limit import max_recursion_limit
  12. from .device import get_default_device
  13. def save(obj, f, pickle_module=pickle, pickle_protocol=pickle.HIGHEST_PROTOCOL):
  14. r"""Save an object to disk file.
  15. :type obj: object
  16. :param obj: object to save. Only ``module`` or ``state_dict`` are allowed.
  17. :type f: text file object
  18. :param f: a string of file name or a text file object to which ``obj`` is saved to.
  19. :type pickle_module:
  20. :param pickle_module: Default: ``pickle``.
  21. :type pickle_protocol:
  22. :param pickle_protocol: Default: ``pickle.HIGHEST_PROTOCOL``.
  23. """
  24. if isinstance(f, str):
  25. with open(f, "wb") as fout:
  26. save(
  27. obj, fout, pickle_module=pickle_module, pickle_protocol=pickle_protocol
  28. )
  29. return
  30. with max_recursion_limit():
  31. assert hasattr(f, "write"), "{} does not support write".format(f)
  32. pickle_module.dump(obj, f, pickle_protocol)
  33. class dmap:
  34. def __init__(self, map_location):
  35. self.map_location = map_location
  36. def __enter__(self):
  37. mgb.add_device_map(self.map_location)
  38. return self
  39. def __exit__(self, type, value, traceback):
  40. mgb.del_device_map()
  41. def _get_callable_map_location(map_location):
  42. if map_location is None:
  43. def callable_map_location(state):
  44. return str(get_default_device())
  45. elif isinstance(map_location, str):
  46. def callable_map_location(state):
  47. return map_location
  48. elif isinstance(map_location, dict):
  49. locator_map = {}
  50. for key, value in map_location.items():
  51. locator_key = mgb.config.parse_locator(key)[:2]
  52. locator_map[locator_key] = value
  53. def callable_map_location(state):
  54. orig = mgb.config.parse_locator(state)[:2]
  55. if orig in locator_map.keys():
  56. state = locator_map[orig]
  57. return state
  58. else:
  59. assert callable(map_location), "map_location should be str, dict or function"
  60. callable_map_location = map_location
  61. return callable_map_location
  62. def load(f, map_location=None, pickle_module=pickle):
  63. r"""Load an object saved with save() from a file.
  64. :type f: text file object
  65. :param f: a string of file name or a text file object from which to load.
  66. :type map_location: str, dict or a function specifying the map rules
  67. :param map_location: Default: ``None``.
  68. .. note::
  69. map_location will change the logical locator when loading models,
  70. avoiding tensors be loading on non-existent device. If you want to
  71. add the mapping relationship between logical locator and physical
  72. locator in runtime, please call :func:`mge.set_device_map()`
  73. :type pickle_module:
  74. :param pickle_module: Default: ``pickle``.
  75. .. note::
  76. If you will call :func:`mge.set_default_device()`, please do it
  77. before :func:`mge.load()`.
  78. Examples:
  79. .. testcode:
  80. import megengine as mge
  81. mge.load('model.mge')
  82. # Load all tensors based on logical location.
  83. mge.load('model.mge', map_location='gpu0')
  84. # Load all tensors onto the device: GPU0
  85. mge.load('model.mge', map_location={'gpu0':'cpu0'})
  86. # Load all tensors based on logical location, but 'GPU0' will be renamed to 'CPU0'
  87. mge.load('model.mge', map_location=lambda dev: 'cpu0')
  88. # Load all tensors onto the device" CPU0
  89. """
  90. if isinstance(f, str):
  91. with open(f, "rb") as fin:
  92. return load(fin, map_location=map_location, pickle_module=pickle_module)
  93. map_location = _get_callable_map_location(map_location) # callable map_location
  94. with dmap(map_location):
  95. return pickle_module.load(f)

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