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.

test_serialization.py 2.5 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 tempfile import TemporaryFile
  11. import numpy as np
  12. import megengine as mge
  13. from megengine import Buffer, Parameter, tensor
  14. def test_tensor_serialization():
  15. def tensor_eq(a, b):
  16. assert a.dtype == b.dtype
  17. assert a.device == b.device
  18. assert a.requires_grad == b.requires_grad
  19. np.testing.assert_equal(a.numpy(), b.numpy())
  20. with TemporaryFile() as f:
  21. data = np.random.randint(low=0, high=7, size=[233])
  22. a = tensor(data, device="xpux", dtype=np.int32)
  23. pickle.dump(a, f)
  24. f.seek(0)
  25. b = pickle.load(f)
  26. np.testing.assert_equal(a.numpy(), b.numpy())
  27. with TemporaryFile() as f:
  28. a = Parameter(np.random.random(size=(233, 2)).astype(np.float32))
  29. pickle.dump(a, f)
  30. f.seek(0)
  31. b = pickle.load(f)
  32. assert isinstance(b, Parameter)
  33. np.testing.assert_equal(a.numpy(), b.numpy())
  34. with TemporaryFile() as f:
  35. a = Buffer(np.random.random(size=(2, 233)).astype(np.float32))
  36. pickle.dump(a, f)
  37. f.seek(0)
  38. b = pickle.load(f)
  39. assert isinstance(b, Buffer)
  40. np.testing.assert_equal(a.numpy(), b.numpy())
  41. with TemporaryFile() as f:
  42. a = Buffer(np.random.random(size=(2, 233)).astype(np.float32))
  43. mge.save(a, f)
  44. f.seek(0)
  45. b = mge.load(f, map_location="cpux")
  46. assert isinstance(b, Buffer)
  47. assert "cpu" in str(b.device)
  48. np.testing.assert_equal(a.numpy(), b.numpy())
  49. with TemporaryFile() as f:
  50. if mge.is_cuda_available():
  51. device_org = mge.get_default_device()
  52. mge.set_default_device("gpu0")
  53. a = Buffer(np.random.random(size=(2, 233)).astype(np.float32))
  54. mge.save(a, f)
  55. f.seek(0)
  56. mge.set_default_device("cpux")
  57. b = mge.load(f, map_location={"gpu0": "cpu0"})
  58. assert isinstance(b, Buffer)
  59. assert "cpu0" in str(b.device)
  60. np.testing.assert_equal(a.numpy(), b.numpy())
  61. mge.set_default_device(device_org)

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