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_tracing.py 1.8 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import numpy as np
  2. from megengine.core.ops import builtin as ops
  3. from megengine.core.tensor.core import apply
  4. from megengine.core.tensor.raw_tensor import as_raw_tensor
  5. from megengine.jit import exclude_from_trace, trace
  6. def test_trace():
  7. for symbolic in [False, True]:
  8. @trace(symbolic=symbolic)
  9. def f(x):
  10. op = ops.Elemwise(mode="negate")
  11. (y,) = apply(op, x)
  12. return y
  13. x = as_raw_tensor([1]).numpy()
  14. y = f.__wrapped__(as_raw_tensor(x)).numpy()
  15. for i in range(3):
  16. np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)
  17. def test_exclude_from_trace():
  18. for symbolic in [False, True]:
  19. @trace(symbolic=symbolic)
  20. def f(x):
  21. neg = ops.Elemwise(mode="negate")
  22. (x,) = apply(neg, x)
  23. with exclude_from_trace():
  24. if i % 2:
  25. (x,) = apply(neg, x)
  26. (x,) = apply(neg, x)
  27. return x
  28. x = as_raw_tensor([1]).numpy()
  29. for i in range(3):
  30. y = f.__wrapped__(as_raw_tensor(x)).numpy()
  31. np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)
  32. def test_print_in_trace():
  33. for symbolic in [False]: # cannot read value in symbolic mode
  34. @trace(symbolic=symbolic)
  35. def f(x):
  36. nonlocal buf
  37. neg = ops.Elemwise(mode="negate")
  38. (x,) = apply(neg, x)
  39. buf = x.numpy()
  40. (x,) = apply(neg, x)
  41. return x
  42. buf = None
  43. x = as_raw_tensor([1]).numpy()
  44. for i in range(3):
  45. y = f.__wrapped__(as_raw_tensor(x)).numpy()
  46. z = buf
  47. buf = None
  48. np.testing.assert_equal(f(as_raw_tensor(x)).numpy(), y)
  49. np.testing.assert_equal(z, buf)

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