Caffe2 - C++ API
A deep learning, cross platform ML framework
tensor_list.cpp
1 #include <torch/csrc/utils/tensor_list.h>
2 
3 #include <torch/csrc/Exceptions.h>
4 #include <torch/csrc/utils/auto_gil.h>
5 #include <torch/csrc/utils/python_scalars.h>
6 
7 using namespace at;
8 
9 namespace torch { namespace utils {
10 
11 static PyObject* recursive_to_list(
12  char* data, IntArrayRef sizes, IntArrayRef strides, int64_t dim,
13  ScalarType scalarType, int64_t elementSize)
14 {
15  int64_t ndim = sizes.size();
16  if (dim == ndim) {
17  return torch::utils::load_scalar(data, scalarType);
18  }
19  auto n = sizes[dim];
20  auto list = THPObjectPtr(PyList_New(n));
21  if (!list) throw python_error();
22  for (int64_t i = 0; i < n; i++) {
23  PyObject* obj = recursive_to_list(data, sizes, strides, dim + 1, scalarType, elementSize);
24  if (!obj) throw python_error();
25  PyList_SET_ITEM(list.get(), i, obj);
26  data += strides[dim] * elementSize;
27  }
28  return list.release();
29 }
30 
31 PyObject* tensor_to_list(const Tensor& tensor) {
32  Tensor data = tensor;
33  if (data.type().backend() != Backend::CPU) {
34  with_no_gil([&]() {
35  data = data.toBackend(Backend::CPU);
36  });
37  }
38  return recursive_to_list(
39  (char*)data.data_ptr(), data.sizes(), data.strides(), 0,
40  data.scalar_type(), data.dtype().itemsize());
41 }
42 
43 }} // namespace torch::utils
constexpr size_t itemsize() const noexcept
Returns the size of the item.
Definition: typeid.h:365
caffe2::TypeMeta dtype() const noexcept
Returns a Tensor&#39;s dtype (TypeMeta). Defined in TensorMethods.h.
constexpr size_t size() const
size - Get the array size.
Definition: ArrayRef.h:138
Definition: jit_type.h:17
Flush-To-Zero and Denormals-Are-Zero mode.