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.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 implied.
  10. */
  11. #include "./trace.h"
  12. #include "./helper.h"
  13. #include "megbrain/imperative/ops/autogen.h"
  14. namespace py = pybind11;
  15. namespace mgb::imperative::python {
  16. apply_result_t apply_trace(ApplyContext& ctx) {
  17. apply_result_t outputs;
  18. if (ctx.backward) {
  19. // reach here when symbolic=True or compiled=True
  20. // call megbrain_graph.py apply(BackwardGraph, *args)
  21. auto args = py::tuple(ctx.nargs);
  22. for (size_t i = 0; i < ctx.nargs; i++) {
  23. args[i] = py::cast(ctx.args[i]->m_var);
  24. }
  25. py::object ret = cpp_apply_backward_varnode(py::cast(ctx.op), *args);
  26. if (!ret) {
  27. throw py::value_error("invalid py object call");
  28. }
  29. // assumption: python function always returns PyList
  30. auto tup = py::reinterpret_borrow<py::list>(ret);
  31. for (auto i = 0; i < tup.size(); i++) {
  32. auto pitem = tup[i].cast<cg::VarNode *>();
  33. outputs.emplace_back(std::make_shared<Tensor>(pitem));
  34. }
  35. return outputs;
  36. }
  37. py::object pyf;
  38. if (is_compiled) {
  39. // run apply in compiled mode, step 2, 3, etc
  40. pyf = cpp_apply_compiled_mode;
  41. } else {
  42. // run first step, both symbolic and non symbolic
  43. pyf = cpp_apply_with_tracing;
  44. }
  45. auto args = py::tuple(ctx.nargs);
  46. for (size_t i = 0; i < ctx.nargs; i++) {
  47. args[i] = TensorWrapper::make(std::move(std::shared_ptr<Tensor>(ctx.args[i]))).release();
  48. }
  49. auto ret = pyf(py::cast(ctx.op), *args);
  50. // assumption: python function always returns PyList
  51. auto tup = py::reinterpret_borrow<py::list>(ret);
  52. for (auto i = 0; i < tup.size(); i++) {
  53. auto tw = TensorWrapper::try_cast(tup[i].ptr());
  54. outputs.emplace_back(tw->m_tensor);
  55. }
  56. return outputs;
  57. }
  58. } // namespace mgb::imperative::python

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