pytorch/torch/csrc
David Berard 82edc8b5d5 [NT] Make NestedTensor register as having symbolic sizes/strides (#124687)
Fixes #123698

This PR makes TensorImpl::has_symbolic_sizes_strides return false for NestedTensors.

1. It passes in the actual sizes when we call `_make_wrapper_subclass` - this is the change that makes the subclass register as `has_symbolic_sizes_strides() == True`
2. It adds a field to `_make_wrapper_subclass` where an explicit `numel` can be provided. This allows us to skip the numel computation for the storage, which previously fails due to arithmetic on NestedInts.
3. Implements `aten::numel` for NJT - this is separate from the overridden numel in `make_wrapper_subclass` for now. Note also that this means that we leave `dispatch_sizes_strides_policy="sizes"`, so that we call into the custom `numel` implementation (as well as `sizes` and `strides`), because `numel` cannot currently be computed from `sizes` for NJT.

Note also that this depends on #121361, because calling TensorImpl::set_sizes_and_strides() tries to clone the sizes into the tensor, which means that we need `clone` to be implemented on NestedInt.

Differential Revision: [D57225736](https://our.internmc.facebook.com/intern/diff/D57225736)
Pull Request resolved: https://github.com/pytorch/pytorch/pull/124687
Approved by: https://github.com/albanD
2024-05-13 16:50:25 +00:00
..
api fix loading optimizer options from archive (#125215) 2024-05-06 23:58:40 +00:00
autograd [NT] Make NestedTensor register as having symbolic sizes/strides (#124687) 2024-05-13 16:50:25 +00:00
cpu Revert "[inductor] add cpp builder code. (#124045)" 2024-05-08 15:33:20 +00:00
cuda [ROCm] enforce ROCM_VERSION >= 6.0 (#125646) 2024-05-12 18:01:28 +00:00
deploy
distributed [Distributed] [7/N] Fix clang-tidy warnings in torch/csrc/distributed/c10d (#124987) 2024-05-11 00:03:52 +00:00
dynamo [guards][cpp-guards] Optimize NN module getattr guards (#124522) 2024-05-04 22:08:56 +00:00
functorch Ensure that vmap is restored properly if an exception is thrown during frame eval (#122074) 2024-05-07 19:36:52 +00:00
inductor [AOTI][torchgen] Minor improvements to C shim torchgen (#125928) 2024-05-11 18:12:46 +00:00
jit [ROCm] enforce ROCM_VERSION >= 6.0 (#125646) 2024-05-12 18:01:28 +00:00
lazy [BE]: Update ruff to 0.4.1 (#124549) 2024-04-21 14:06:23 +00:00
monitor
mps
mtia torch.mtia module for MTIA device backend (#123612) 2024-04-26 16:17:54 +00:00
multiprocessing
onnx
profiler [NT] Make NestedTensor register as having symbolic sizes/strides (#124687) 2024-05-13 16:50:25 +00:00
tensor Fix refcount handling for dtype, layout and memory format (#125271) 2024-05-02 02:34:34 +00:00
utils Add registration API for torch.compile-eager (#121387) 2024-05-10 00:30:27 +00:00
xpu Add attributes to xpu device prop (#121898) 2024-03-30 00:25:39 +00:00
copy_utils.h
CudaIPCTypes.cpp
CudaIPCTypes.h
DataLoader.cpp
DataLoader.h
Device.cpp
Device.h
Dtype.cpp Fix ref leak in dtype.to_complex()/to_real() (#125154) 2024-04-29 23:59:27 +00:00
Dtype.h
DynamicTypes.cpp
DynamicTypes.h Fix refcount handling for dtype, layout and memory format (#125271) 2024-05-02 02:34:34 +00:00
empty.c
Event.cpp Support generic stream/event on CUDA/HIP backend (#125757) 2024-05-10 13:34:09 +00:00
Event.h Build device generic torch.Stream and torch.Event based on c10::Stream/Event (#123611) 2024-04-24 20:51:17 +00:00
Exceptions.cpp Support Accelerator OOM Error (#121200) (#121702) 2024-04-15 21:41:46 +00:00
Exceptions.h Check for releasing GIL at compiletime (#116695) 2024-03-11 22:04:56 +00:00
Export.h
Generator.cpp Graph-Safe RNG State Exchange for Tensor Parallelism (#114068) 2024-03-27 01:14:38 +00:00
Generator.h Graph-Safe RNG State Exchange for Tensor Parallelism (#114068) 2024-03-27 01:14:38 +00:00
itt_wrapper.cpp
itt_wrapper.h
itt.cpp
Layout.cpp
Layout.h
MemoryFormat.cpp
MemoryFormat.h
Module.cpp Fix ref leak in dtype.to_complex()/to_real() (#125154) 2024-04-29 23:59:27 +00:00
Module.h
PyInterpreter.cpp Support custom layout call under torch dispatch mode (#125379) 2024-05-02 23:44:12 +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
Size.h
Storage.cpp rename ort to maia (#123265) 2024-04-23 00:33:25 +00:00
Storage.h
StorageMethods.cpp
StorageMethods.h
StorageSharing.cpp
StorageSharing.h
Stream.cpp Build device generic torch.Stream and torch.Event based on c10::Stream/Event (#123611) 2024-04-24 20:51:17 +00:00
Stream.h
stub.c
THConcat.h
THP.h
TypeInfo.cpp
TypeInfo.h
Types.h
utils.cpp
utils.h

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.)