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.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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. from .device import _valid_device, get_default_device
  11. from .tensor import Tensor
  12. from .utils.max_recursion_limit import max_recursion_limit
  13. def save(obj, f, pickle_module=pickle, pickle_protocol=pickle.HIGHEST_PROTOCOL):
  14. r"""
  15. Save an object to disk file.
  16. :type obj: object
  17. :param obj: object to save. Only ``module`` or ``state_dict`` are allowed.
  18. :type f: text file object
  19. :param f: a string of file name or a text file object to which ``obj`` is saved to.
  20. :type pickle_module:
  21. :param pickle_module: Default: ``pickle``.
  22. :type pickle_protocol:
  23. :param pickle_protocol: Default: ``pickle.HIGHEST_PROTOCOL``.
  24. """
  25. if isinstance(f, str):
  26. with open(f, "wb") as fout:
  27. save(
  28. obj, fout, pickle_module=pickle_module, pickle_protocol=pickle_protocol
  29. )
  30. return
  31. with max_recursion_limit():
  32. assert hasattr(f, "write"), "{} does not support write".format(f)
  33. pickle_module.dump(obj, f, pickle_protocol)
  34. class dmap:
  35. def __init__(self, map_location):
  36. self.map_location = map_location
  37. def __enter__(self):
  38. Tensor.dmap_callback = staticmethod(self.map_location)
  39. return self
  40. def __exit__(self, type, value, traceback):
  41. Tensor.dmap_callback = None
  42. def _get_callable_map_location(map_location):
  43. if map_location is None:
  44. def callable_map_location(state):
  45. return str(get_default_device())
  46. elif isinstance(map_location, str):
  47. def callable_map_location(state):
  48. return map_location
  49. elif isinstance(map_location, dict):
  50. for key, value in map_location.items():
  51. # dict key and values can only be "xpux", "cpux", "gpu0", etc.
  52. assert _valid_device(key), "Invalid locator_map key value {}".format(key)
  53. assert _valid_device(value), "Invalid locator_map key value {}".format(
  54. value
  55. )
  56. def callable_map_location(state):
  57. if state[:4] in map_location.keys():
  58. state = map_location[state[:4]]
  59. return state
  60. else:
  61. assert callable(map_location), "map_location should be str, dict or function"
  62. callable_map_location = map_location
  63. return callable_map_location
  64. def load(f, map_location=None, pickle_module=pickle):
  65. r"""
  66. Load an object saved with save() from a file.
  67. :type f: text file object
  68. :param f: a string of file name or a text file object from which to load.
  69. :type map_location: str, dict or a function specifying the map rules
  70. :param map_location: Default: ``None``.
  71. .. note::
  72. map_location defines device mapping. See examples for usage.
  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. # Load tensors to the same device as defined in model.mge
  82. mge.load('model.mge')
  83. # Load all tensors to gpu0.
  84. mge.load('model.mge', map_location='gpu0')
  85. # Load all tensors originally on gpu0 to cpu0
  86. mge.load('model.mge', map_location={'gpu0':'cpu0'})
  87. # Load all tensors to cpu0
  88. mge.load('model.mge', map_location=lambda dev: '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) as dm:
  95. return pickle_module.load(f)

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