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.

trace.cpp 2.4 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * \file imperative/python/src/trace.cpp
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or
  10. * implied.
  11. */
  12. #include "./trace.h"
  13. #include "./helper.h"
  14. #include "megbrain/imperative/ops/autogen.h"
  15. namespace py = pybind11;
  16. namespace mgb::imperative::python {
  17. apply_result_t apply_trace(ApplyContext& ctx) {
  18. apply_result_t outputs;
  19. if (ctx.backward) {
  20. // reach here when compiled=True
  21. // call megbrain_graph.py apply(BackwardGraph, *args)
  22. auto args = py::tuple(ctx.nargs + 1);
  23. args[0] = py::cast(ctx.op);
  24. for (size_t i = 0; i < ctx.nargs; i++) {
  25. args[i + 1] = py::cast(ctx.args[i]->m_var);
  26. }
  27. py::object ret = py::reinterpret_steal<py::object>(
  28. PyObject_Call(cpp_apply_backward_varnode, args.ptr(), nullptr));
  29. if (!ret) {
  30. throw py::value_error("invalid py object call");
  31. }
  32. // assumption: python function always returns PyList
  33. auto tup = py::reinterpret_borrow<py::list>(ret);
  34. for (auto i = 0; i < tup.size(); i++) {
  35. auto pitem = tup[i].cast<cg::VarNode*>();
  36. outputs.emplace_back(std::make_shared<Tensor>(pitem));
  37. }
  38. return outputs;
  39. }
  40. PyObject* pyf;
  41. if (is_compiled) {
  42. // run apply in compiled mode, step 2, 3, etc
  43. pyf = cpp_apply_compiled_mode;
  44. } else {
  45. // run first step, both symbolic and non symbolic
  46. pyf = cpp_apply_with_tracing;
  47. }
  48. auto args = py::tuple(ctx.nargs + 1);
  49. args[0] = py::cast(ctx.op);
  50. py::tuple args(ctx.nargs);
  51. for (size_t i = 0; i < ctx.nargs; i++) {
  52. args[i + 1] = TensorWrapper::make(ctx.args[i]->shared_from_this());
  53. }
  54. auto ret = py::reinterpret_steal<py::object>(
  55. PyObject_Call(pyf, args.ptr(), nullptr));
  56. // assumption: python function always returns PyList
  57. auto tup = py::reinterpret_borrow<py::list>(ret);
  58. for (auto i = 0; i < tup.size(); i++) {
  59. auto tw = TensorWrapper::try_cast(tup[i].ptr());
  60. outputs.emplace_back(tw->m_tensor);
  61. }
  62. return outputs;
  63. }
  64. } // namespace mgb::imperative::python

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