pytorch/torch/csrc
soulitzer 8bda95228f [autograd] Avoid creating and recording event when unnecessary (#157503)
Today, we always create and record an events in two places:
1) Upon seeing the first producer, we record an event on the producer, and we wait for this event in two places: (1) when the engine goes to run the consumer, the consumer stream waits for this event. (2) prior to doing accumulation, the accumulation stream waits for this event.

2) After doing accumulation, we record an event on the accumulation stream and wait for this event in a single place: when the engine goes to run the consumer.

We do not actually need to record the event in the cases where the 1st producer stream is the same as the consumer and as the accumulation stream, and where the accumulation stream is the same as the consumer stream.

Removing this unnecessary create + record event should save a few us for each instance avoided.

Fixes https://github.com/pytorch/pytorch/issues/157407

----

Manual test plan:
- [x] @eqy to confirm perf is restored
- [x] Running the repro originally reported before/after the patch

Pull Request resolved: https://github.com/pytorch/pytorch/pull/157503
Approved by: https://github.com/eqy
ghstack dependencies: #155715
2025-07-09 03:36:14 +00:00
..
api Fix the Problems About Defining Static Variable in Inline Function (#147095) 2025-06-25 01:59:10 +00:00
autograd [autograd] Avoid creating and recording event when unnecessary (#157503) 2025-07-09 03:36:14 +00:00
cpu
cuda Revert "Add DeviceAllocator as the base device allocator (#138222)" 2025-06-25 00:11:35 +00:00
deploy [BE][9/16] fix typos in torch/ (torch/csrc/) (#156319) 2025-06-23 02:57:50 +00:00
distributed Work: block_current_stream API (#156883) 2025-07-08 23:55:46 +00:00
dynamo [Set] Support sets in VariableBuilder (#153150) 2025-07-04 00:45:03 +00:00
export [schema_upgrader] add C++ upgrader for json based upgrading (#156761) 2025-06-28 18:15:06 +00:00
functorch [dynamo] Guard serialization for FUNCTORCH_STACK_MATCH (#152616) 2025-05-05 18:05:56 +00:00
fx Fix clang-tidy bugprone* warnings (#148529) 2025-06-23 23:09:56 +00:00
inductor [AOTI] Split aoti_runtime/model.h to prepare for model static linking (#157592) 2025-07-07 22:13:22 +00:00
instruction_counter [BE]: Replace a couple of call sites with fmtlib printf (#154533) 2025-06-01 21:16:34 +00:00
jit Fix 'dllimport attribute ignored on inline function' (#157670) 2025-07-07 16:57:48 +00:00
lazy [attempt 2] Compute contiguity symbolically to avoid dde, and introduce c++ sym_is_contiguous (#157472) 2025-07-02 23:12:29 +00:00
monitor Fix 'dllimport attribute ignored on inline function' (#157670) 2025-07-07 16:57:48 +00:00
mps [BE][7/16] fix typos in torch/ (torch/csrc/) (#156317) 2025-06-23 02:57:41 +00:00
mtia Add getDeviceProperties api to torch mtia device (#153577) 2025-05-27 11:55:58 +00:00
multiprocessing
onnx
profiler Fix 'dllimport attribute ignored on inline function' (#157670) 2025-07-07 16:57:48 +00:00
stable Add a basic shim and stable::Tensor is_contiguous API (#156228) 2025-06-20 17:59:52 +00:00
tensor
utils Revert "Use std::string_view in torchgen (#157050)" 2025-06-30 18:08:54 +00:00
xpu Add device_id to XPU device properties (#156481) 2025-07-03 01:22:11 +00:00
copy_utils.h
CudaIPCTypes.cpp
CudaIPCTypes.h
DataLoader.cpp [Lint] Update clang-format to 19.1.4 (#153889) 2025-05-20 14:12:46 +00:00
DataLoader.h
Device.cpp
Device.h
DeviceAccelerator.cpp Revert "Add unified memory APIs for torch.accelerator (#152932)" 2025-06-25 00:11:35 +00:00
DeviceAccelerator.h
Dtype.cpp
Dtype.h
DynamicTypes.cpp
DynamicTypes.h
empty.c
Event.cpp Fix clang-tidy bugprone* warnings (#148529) 2025-06-23 23:09:56 +00:00
Event.h
Exceptions.cpp Remove AttributeError constructor (#154808) 2025-06-03 03:49:09 +00:00
Exceptions.h [BE][7/16] fix typos in torch/ (torch/csrc/) (#156317) 2025-06-23 02:57:41 +00:00
Export.h
Generator.cpp
Generator.h
itt_wrapper.cpp
itt_wrapper.h
itt.cpp [1/N] Use internal linkage in torch/csrc C++ files. (#150930) 2025-04-11 02:19:31 +00:00
itt.h [1/N] Use internal linkage in torch/csrc C++ files. (#150930) 2025-04-11 02:19:31 +00:00
Layout.cpp
Layout.h
MemoryFormat.cpp
MemoryFormat.h
Module.cpp fix storage use_count (#157694) 2025-07-08 05:53:12 +00:00
Module.h
PyInterpreter.cpp Fix broken URLs (#152237) 2025-04-27 09:56:42 +00:00
PyInterpreter.h
python_dimname.cpp
python_dimname.h
python_headers.h
QScheme.cpp
QScheme.h
README.md
serialization.cpp
serialization.h
Size.cpp Implemented Size.__radd__ (#152554) 2025-06-23 15:38:37 +00:00
Size.h
Storage.cpp [BE][7/16] fix typos in torch/ (torch/csrc/) (#156317) 2025-06-23 02:57:41 +00:00
Storage.h
StorageMethods.cpp
StorageMethods.h
StorageSharing.cpp [2/N] Fix cppcoreguidelines-init-variables suppression (#146237) 2025-06-19 23:26:42 +00:00
StorageSharing.h
Stream.cpp
Stream.h
stub.c
THConcat.h
THP.h
TypeInfo.cpp
TypeInfo.h
Types.h
utils.cpp [BE][7/16] fix typos in torch/ (torch/csrc/) (#156317) 2025-06-23 02:57:41 +00:00
utils.h [Lint] Update clang-format to 19.1.4 (#153889) 2025-05-20 14:12:46 +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.)