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.

utils.py 2.1 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 numpy as np
  10. import torch
  11. import megengine._internal as mgb
  12. _TORCH_NUMPY_MAPPING = {
  13. torch.float16: np.float16,
  14. torch.float32: np.float32,
  15. torch.float64: np.float64,
  16. torch.int8: np.int8,
  17. torch.int16: np.int16,
  18. torch.int32: np.int32,
  19. }
  20. def torch_dtype_to_numpy_dtype(torch_dtype: torch.dtype):
  21. """map torch dtype to numpy dtype
  22. :param torch_dtype: torch dtype
  23. :return: numpy dtype
  24. """
  25. if not isinstance(torch_dtype, torch.dtype):
  26. raise TypeError("Argument `torch_dtype` should be an instance of torch.dtype")
  27. if torch_dtype not in _TORCH_NUMPY_MAPPING:
  28. raise ValueError("Unknown PyTorch dtype: {}".format(torch_dtype))
  29. return _TORCH_NUMPY_MAPPING[torch_dtype]
  30. def torch_device_to_device(device: torch.device):
  31. """map torch device to device
  32. :param device: torch device
  33. :return: device
  34. """
  35. if not isinstance(device, torch.device):
  36. raise TypeError("Argument `device` should be an instance of torch.device")
  37. index = device.index
  38. if index is None:
  39. index = "x"
  40. if device.type == "cpu":
  41. return "cpu{}".format(index)
  42. elif device.type == "cuda":
  43. return "gpu{}".format(index)
  44. raise ValueError("Unknown PyTorch device: {}".format(device))
  45. def device_to_torch_device(device: mgb.CompNode):
  46. """map device to torch device
  47. :param device: megbrain compute node
  48. :return: corresponding torch device
  49. """
  50. t, d, _ = device.locator_physical
  51. if t == "CUDA":
  52. return torch.device("cuda", d)
  53. elif t == "CPU":
  54. return torch.device("cpu", d)
  55. else:
  56. raise Exception("Unsupported device type: {}".format(t))

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