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 3.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 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. Args:
  16. obj: object to save. Only ``module`` or ``state_dict`` are allowed.
  17. f: a string of file name or a text file object to which ``obj`` is saved to.
  18. pickle_module: Default: ``pickle``.
  19. pickle_protocol: Default: ``pickle.HIGHEST_PROTOCOL``.
  20. """
  21. if isinstance(f, str):
  22. with open(f, "wb") as fout:
  23. save(
  24. obj, fout, pickle_module=pickle_module, pickle_protocol=pickle_protocol
  25. )
  26. return
  27. with max_recursion_limit():
  28. assert hasattr(f, "write"), "{} does not support write".format(f)
  29. pickle_module.dump(obj, f, pickle_protocol)
  30. class dmap:
  31. def __init__(self, map_location):
  32. self.map_location = map_location
  33. def __enter__(self):
  34. Tensor.dmap_callback = staticmethod(self.map_location)
  35. return self
  36. def __exit__(self, type, value, traceback):
  37. Tensor.dmap_callback = None
  38. def _get_callable_map_location(map_location):
  39. if map_location is None:
  40. def callable_map_location(state):
  41. return state
  42. elif isinstance(map_location, str):
  43. def callable_map_location(state):
  44. return map_location
  45. elif isinstance(map_location, dict):
  46. for key, value in map_location.items():
  47. # dict key and values can only be "xpux", "cpux", "gpu0", etc.
  48. assert _valid_device(key), "Invalid locator_map key value {}".format(key)
  49. assert _valid_device(value), "Invalid locator_map key value {}".format(
  50. value
  51. )
  52. def callable_map_location(state):
  53. if state[:4] in map_location.keys():
  54. state = map_location[state[:4]]
  55. return state
  56. else:
  57. assert callable(map_location), "map_location should be str, dict or function"
  58. callable_map_location = map_location
  59. return callable_map_location
  60. def load(f, map_location=None, pickle_module=pickle):
  61. r"""Load an object saved with :func:~.megengine.save` from a file.
  62. Args:
  63. f: a string of file name or a text file object from which to load.
  64. map_location: Default: ``None``.
  65. pickle_module: Default: ``pickle``.
  66. Note:
  67. * ``map_location`` defines device mapping. See examples for usage.
  68. * If you will call :func:`~.megengine.set_default_device()`, please do it
  69. before :func:`~.megengine.load()`.
  70. Examples:
  71. .. code-block::
  72. import megengine as mge
  73. # Load tensors to the same device as defined in model.pkl
  74. mge.load('model.pkl')
  75. # Load all tensors to gpu0.
  76. mge.load('model.pkl', map_location='gpu0')
  77. # Load all tensors originally on gpu0 to cpu0
  78. mge.load('model.pkl', map_location={'gpu0':'cpu0'})
  79. # Load all tensors to cpu0
  80. mge.load('model.pkl', map_location=lambda dev: 'cpu0')
  81. """
  82. if isinstance(f, str):
  83. with open(f, "rb") as fin:
  84. return load(fin, map_location=map_location, pickle_module=pickle_module)
  85. map_location = _get_callable_map_location(map_location) # callable map_location
  86. with dmap(map_location) as dm:
  87. return pickle_module.load(f)

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