tree: ae7267d73b0cf6e743c8c9ffe5b8aa763eb4751c [path history] [tgz]
  1. functions/
  2. utils/
  3. anomaly_mode.cpp
  4. anomaly_mode.h
  5. autograd.h
  6. edge.h
  7. engine.cpp
  8. engine.h
  9. function.cpp
  10. function.h
  11. function_hook.cpp
  12. function_hook.h
  13. grad_mode.cpp
  14. grad_mode.h
  15. init.cpp
  16. input_buffer.cpp
  17. input_buffer.h
  18. input_metadata.h
  19. profiler.cpp
  20. profiler.h
  21. profiler_cuda.cpp
  22. python_anomaly_mode.cpp
  23. python_anomaly_mode.h
  24. python_cpp_function.cpp
  25. python_cpp_function.h
  26. python_engine.cpp
  27. python_engine.h
  28. python_function.cpp
  29. python_function.h
  30. python_hook.cpp
  31. python_hook.h
  32. python_legacy_variable.cpp
  33. python_legacy_variable.h
  34. python_variable.cpp
  35. python_variable.h
  36. python_variable_indexing.cpp
  37. python_variable_indexing.h
  38. README.md
  39. record_function.cpp
  40. record_function.h
  41. saved_variable.cpp
  42. saved_variable.h
  43. symbolic.h
  44. type_and_shape.h
  45. variable.cpp
  46. variable.h
  47. VariableTypeManual.cpp
  48. VariableTypeUtils.h
torch/csrc/autograd/README.md

Autograd

Autograd is a hotspot for PyTorch performance, so most of the heavy lifting is implemented in C++. This implies that we have to do some shuffling between Python and C++; and in general, we want data to be in a form that is convenient to manipulate from C++.

Our general model is that for any key data type that autograd manipulates, there are two implementations: a C++ type and a Python object type. For example, consider variables in autograd: we have both Variable in variable.h (the C++ type) and THPVariable in python_variable.h (the Python type.) (By the way, THP stands for TorcH Python, not to be confused with THPP, TorcH C++). Variable contains the payload of a variable, while THPVariable just contains a shared_ptr reference to Variable, as well as references to other Python objects which the Python runtime needs to know about. A lot of data accessor implementations in python_variable.cpp simply reach through to the underlying Variable and return the appropriate value.

The most complicated application of this principle is Function, which also supports users implementing custom behavior in Python. We have the following classes:

  • Function in function.h, the C++ type.
  • THPFunction in python_function.h, the Python object type. In python_function.cpp, you can see the boilerplate that tells the Python interpreter about this object.
  • PyFunction in python_function.h, a subclass of Function which forwards apply to a Python THPFunction. (NOT a Python object, despite its name!)

Outside of PyFunction, the C++ objects largely avoid referencing Python objects (there are a few exceptions, like pyobj in Variable, and PyFunction, whose whole point is to let C++ call into Python). And pyobj in Function to ensure uniqueness of the associated python wrapper (if it exists).