pytorch/torch/csrc
Scott Wolchok c083489f46 [kineto] Optimize getStepCallbacks for common case of no active callbacks
Pull Request resolved: https://github.com/pytorch/pytorch/pull/77804

IIUC, the result of this function will be empty and unused if there are no sampled callbacks, which is the common case. We can accelerate this case by wrapping the result in an optional to save initializing an empty SmallVector.

Differential Revision: [D36497279](https://our.internmc.facebook.com/intern/diff/D36497279/)

**NOTE FOR REVIEWERS**: This PR has internal Facebook specific changes or comments, please review them on [Phabricator](https://our.internmc.facebook.com/intern/diff/D36497279/)!

Approved by: https://github.com/robieta
2022-05-24 19:38:01 +00:00
..
api Add linalg.lu 2022-05-05 09:17:05 +00:00
autograd [kineto] Optimize getStepCallbacks for common case of no active callbacks 2022-05-24 19:38:01 +00:00
cuda expose fast get_current_stream (#78165) 2022-05-24 15:54:47 +00:00
deploy expose torch_python_obj as a static library 2022-05-11 02:35:00 +00:00
distributed Revert RPC Meta device support 2022-05-19 23:47:47 +00:00
generic Revert "Move THPStorage definitions out of torch/csrc/generic (#78032)" 2022-05-24 16:37:35 +00:00
jit [kineto] Optimize getStepCallbacks for common case of no active callbacks 2022-05-24 19:38:01 +00:00
lazy Codegen Non-Native IR Nodes (#76535) 2022-05-24 19:29:23 +00:00
monitor
multiprocessing
onnx [ONNX] Support optional type (#68793) (#73284) 2022-05-04 20:24:30 +00:00
profiler [Profiler][Trivial] Switch to nanoseconds for Result's internal representation 2022-05-22 22:39:13 +00:00
tensor
utils Fix a few issues on assert/double error/legacy constructor (#77966) 2022-05-20 20:25:12 +00:00
copy_utils.h
CudaIPCTypes.cpp
CudaIPCTypes.h
DataLoader.cpp
DataLoader.h
Device.cpp
Device.h
dl.c
Dtype.cpp
Dtype.h
DynamicTypes.cpp Add missing decref to createStorageGetType (#77860) 2022-05-20 00:53:19 +00:00
DynamicTypes.h Merge torch.cuda._UntypedStorage into torch._UntypedStorage (#75459) 2022-05-19 13:54:39 +00:00
empty.c
Exceptions.cpp
Exceptions.h
Export.h
Generator.cpp
Generator.h
init_flatbuffer_module.cpp Support saving extra files in pytorch flat buffer format via python (#77870) 2022-05-19 22:15:17 +00:00
Layout.cpp
Layout.h
MemoryFormat.cpp
MemoryFormat.h
Module.cpp [MPS] Fix torch.mps.is_available() (#78121) 2022-05-24 05:10:38 +00:00
Module.h
python_dimname.cpp
python_dimname.h
python_headers.h
PythonTypes.h
QScheme.cpp
QScheme.h
README.md
serialization.cpp Revert "Move THPStorage definitions out of torch/csrc/generic (#78032)" 2022-05-24 16:37:35 +00:00
serialization.h Revert "Move THPStorage definitions out of torch/csrc/generic (#78032)" 2022-05-24 16:37:35 +00:00
Size.cpp
Size.h
Storage.cpp Revert "Move THPStorage definitions out of torch/csrc/generic (#78032)" 2022-05-24 16:37:35 +00:00
Storage.h Revert "Move THPStorage definitions out of torch/csrc/generic (#78032)" 2022-05-24 16:37:35 +00:00
StorageDefs.h Revert "Move THPStorage definitions out of torch/csrc/generic (#78032)" 2022-05-24 16:37:35 +00:00
Stream.cpp
Stream.h
stub_with_flatbuffer.c
stub.c
THCGenerateByteType.h
THConcat.h
THGenerateByteType.h
THP.h
TypeInfo.cpp ENH: Convert finfo.tiny to finfo.smallest_normal (#76292) 2022-05-20 00:59:48 +00:00
TypeInfo.h
Types.h
utils.cpp
utils.h Merge torch.cuda._UntypedStorage into torch._UntypedStorage (#75459) 2022-05-19 13:54:39 +00:00

csrc

The csrc directory contains all of the code concerned with integration with Python. This is in contrast to lib, which contains the Torch libraries that are Python agnostic. csrc depends on lib, but not vice versa.

There are a number of utilities for easing integration with Python which are worth knowing about, which we briefly describe here. But the most important gotchas:

  • DO NOT forget to take out the GIL with pybind11::gil_scoped_acquire before calling Python API or bringing a THPObjectPtr into scope.

  • Make sure you include Python.h first in your header files, before any system headers; otherwise, you will get error: "_XOPEN_SOURCE" redefined error. If you pay attention to warnings, you will see where you need to do this.

Notes

Note [Storage is not nullptr]

Historically, Torch supported nullptr storage, as a minor optimization to avoid having to allocate a storage object when it would be empty. However, this is actually a confusing special case to deal with, so by-in-large, PyTorch assumes that, in fact, storage is never nullptr.

One important case where this assumption is important is when tracking the CUDA device a tensor is stored in: this information is stored solely in the storage, so if a storage is nullptr, we lose this information.

Although storage is never nullptr, the data field of c10::StorageImpl may be nullptr. This mostly occurs when we want to pre-allocate an output tensor struct, but then have it be resized and filled with data by some operator: there's no point in allocating data for it in this case!

Files

Exceptions.h

Frequently when working with the Python API, you may call a function which returns an error. In this case, we want to return directly to the Python interpreter, so that this exception can be propagated accordingly; however, because the Python API is C-based, what actually will happen is it will return control to whatever C++ code called it. Similarly, if we raise a C++ exception, prior to returning to the Python interpreter, we must set the Python error flags, so it turns into a C++ exception.

Moreover, when using the following macros, the generated warnings will be converted into python warnings that can be caught by the user.

Exceptions define helpers for two main cases:

  • For code where you write the python binding by hand, HANDLE_TH_ERRORS, END_HANDLE_TH_ERRORS and an exception class python_error. You call them like this:
// Entry point from Python interpreter
PyObject* run(PyObject* arg) {
  HANDLE_TH_ERRORS
  ...
  if (!x) throw python_error();
  // From c10/Exception.h
  TORCH_CHECK(cond, "cond was false here");
  TORCH_WARN("Warning message");
  ...
  END_HANDLE_TH_ERRORS
}

The HANDLE_TH_ERRORS macro will catch all exceptions and convert them into an appropriate Python signal. python_error is a special exception which doesn't contain any info, instead it says, "An error occurred in the Python API; if you return to the interpreter, Python will raise that exception, nothing else needs to be done."

  • For code that you bind using pybind, HANDLE_TH_ERRORS and END_HANDLE_TH_ERRORS_PYBIND can be used. They will work jointly with pybind error handling to raise pytorch errors and warnings natively and let pybind handle other errors. It can be used as:
// Function given to the pybind binding
at::Tensor foo(at::Tensor x) {
  HANDLE_TH_ERRORS
  ...
  if (!x) throw python_error();
  // pybind native error
  if (!x) throw py::value_error();
  // From c10/Exception.h
  TORCH_CHECK(cond, "cond was false here");
  TORCH_WARN("Warning message");
  ...
  END_HANDLE_TH_ERRORS_PYBIND
}

GIL

Whenever you make any calls to the Python API, you must have taken out the Python GIL, as none of these calls are thread safe. pybind11::gil_scoped_acquire is a RAII struct which handles taking and releasing the GIL. Use it like this:

void iWantToUsePython() {
  pybind11::gil_scoped_acquire gil;
  ...
}

In general, the compiler will NOT warn you if you use Python functionality without taking out the GIL, so DO NOT FORGET this call.

utils/object_ptr.h

THPPointer is a smart pointer class analogous to std::shared_ptr, but which is overloaded to handle reference counting scheme of various objects which are not based on shared_ptr. The most important overloads are:

  • PyObject (so important we've aliased it as THPObjectPtr), which hooks into Python reference counting. (By the way, that means you MUST take out the GIL before bringing one of these into scope!)

  • The various TH tensor and storage types (e.g., THTensor), which hook into TH's reference counting. (TH's reference counting IS thread safe, no locks necessary.)