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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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"""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. Tensor.dmap_callback = staticmethod(self.map_location)
  38. return self
  39. def __exit__(self, type, value, traceback):
  40. Tensor.dmap_callback = None
  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. for key, value in map_location.items():
  50. # dict key and values can only be "xpux", "cpux", "gpu0", etc.
  51. assert _valid_device(key), "Invalid locator_map key value {}".format(key)
  52. assert _valid_device(value), "Invalid locator_map key value {}".format(
  53. value
  54. )
  55. def callable_map_location(state):
  56. if state[:4] in map_location.keys():
  57. state = map_location[state[:4]]
  58. return state
  59. else:
  60. assert callable(map_location), "map_location should be str, dict or function"
  61. callable_map_location = map_location
  62. return callable_map_location
  63. def load(f, map_location=None, pickle_module=pickle):
  64. r"""Load an object saved with save() from a file.
  65. :type f: text file object
  66. :param f: a string of file name or a text file object from which to load.
  67. :type map_location: str, dict or a function specifying the map rules
  68. :param map_location: Default: ``None``.
  69. .. note::
  70. map_location defines device mapping. See examples for usage.
  71. :type pickle_module:
  72. :param pickle_module: Default: ``pickle``.
  73. .. note::
  74. If you will call :func:`mge.set_default_device()`, please do it
  75. before :func:`mge.load()`.
  76. Examples:
  77. .. testcode:
  78. import megengine as mge
  79. # Load tensors to the same device as defined in model.mge
  80. mge.load('model.mge')
  81. # Load all tensors to gpu0.
  82. mge.load('model.mge', map_location='gpu0')
  83. # Load all tensors originally on gpu0 to cpu0
  84. mge.load('model.mge', map_location={'gpu0':'cpu0'})
  85. # Load all tensors to cpu0
  86. mge.load('model.mge', map_location=lambda dev: 'cpu0')
  87. """
  88. if isinstance(f, str):
  89. with open(f, "rb") as fin:
  90. return load(fin, map_location=map_location, pickle_module=pickle_module)
  91. map_location = _get_callable_map_location(map_location) # callable map_location
  92. with dmap(map_location) as dm:
  93. return pickle_module.load(f)

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