pytorch/torch/csrc
Meghan Lele 28c5d90b67 [JIT] Allow implicit boolean conversion of containers (#51683)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/51683

**Summary**
This commit enables implicit boolean conversion of lists, strings, and
dictionaries in conditional expressions. Like Python, empty lists,
strings and dictionaries evaluate to `False` and their non-empty
counterparts evaluate to `True`. This allows users to write code like

```
torch.jit.script
def fn(l: List[int]):
  if l:
    ...
  else:
    ...
```

This has been requested by some users and would be a good usability
improvement.

**Test Plan**
This commit adds unit tests to `TestList`, `TestDict` and
`test_jit_string.py` to test this new feature.

Test Plan: Imported from OSS

Reviewed By: pbelevich

Differential Revision: D26264410

Pulled By: SplitInfinity

fbshipit-source-id: b764c18fd766cfc128ea98a02b7c6c3fa49f8632
2021-02-05 00:34:35 -08:00
..
api Generate header with version #defines for LibTorch (#50073) 2021-02-03 22:18:53 -08:00
autograd Add division overload with rounding_mode selection (#51706) 2021-02-04 13:08:36 -08:00
cuda Introducing TORCH_CUDA_CPP_API and TORCH_CUDA_CU_API to the code (#50627) 2021-01-21 19:09:11 -08:00
deploy Back out "Revert D26077905: Back out "Revert D25850783: Add torch::deploy, an embedded torch-python interpreter"" (#51267) 2021-01-28 19:30:45 -08:00
distributed [RPC] Add option to make rref.get_type not block. (#50977) 2021-02-04 20:18:50 -08:00
generic PyLong_{As/From}{Long/UnsignedLong} lint checks (#49280) 2020-12-17 09:32:08 -08:00
jit [JIT] Allow implicit boolean conversion of containers (#51683) 2021-02-05 00:34:35 -08:00
multiprocessing
onnx
tensor
utils [PyTorch] IWYU in torch/csrc/utils/future.h (#51293) 2021-02-01 19:18:12 -08:00
copy_utils.h
CudaIPCTypes.cpp Refactor build targets for torch::deploy (#50288) 2021-01-22 09:16:32 -08:00
CudaIPCTypes.h Add build option to split torch_cuda library into torch_cuda_cu and torch_cuda_cpp (#49050) 2021-02-01 18:42:35 -08:00
DataLoader.cpp
DataLoader.h
Device.cpp [fix] repr(torch.device) (#48655) 2020-12-02 15:48:17 -08:00
Device.h
dl.c
Dtype.cpp
Dtype.h
DynamicTypes.cpp pass TypeMeta by value (#45026) 2020-10-30 10:14:17 -07:00
DynamicTypes.h pass TypeMeta by value (#45026) 2020-10-30 10:14:17 -07:00
empty.c
Exceptions.cpp
Exceptions.h
Generator.cpp Move generator state APIs to ATen (#49589) 2021-01-06 18:26:56 -08:00
Generator.h
Layout.cpp
Layout.h
MemoryFormat.cpp
MemoryFormat.h
Module.cpp Back out "Revert D26077905: Back out "Revert D25850783: Add torch::deploy, an embedded torch-python interpreter"" (#51267) 2021-01-28 19:30:45 -08:00
Module.h
python_dimname.cpp
python_dimname.h
python_headers.h Upgrade oneDNN (mkl-dnn) to v1.7 (#47853) 2020-12-03 11:54:31 -08:00
PythonTypes.h
QScheme.cpp
QScheme.h
README.md
serialization.cpp
serialization.h
Size.cpp PyLong_{As/From}{Long/UnsignedLong} lint checks (#49280) 2020-12-17 09:32:08 -08:00
Size.h
Storage.cpp Reorganize and refine the Windows.h import in C++ files (#48009) 2020-11-20 14:21:09 -08:00
Storage.h
StorageDefs.h
Stream.cpp
Stream.h
stub.c
THP_export.h
THP.h Remove THPWrapper (#49871) 2020-12-30 03:01:52 -08:00
TypeInfo.cpp
TypeInfo.h
Types.h
utils.cpp
utils.h
WindowsTorchApiMacro.h Renaming CAFFE2_API to TORCH_API (#49496) 2020-12-18 10:54:50 -08: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 THStorage 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.)