Reputation: 215
I am torch Newbie.
when I was learning torch tutorial like below,
I was curious about where tensor.item() is defined.
import torch
a = torch.tensor([1])
print( a.item() ) # it works without problem.
In order to find what i dont know,
First, I used VScode. but I got this.
enter image description here
not like this
enter image description here
Second, I searched "def item()" at the torch Github
But, I could not find. T^T
Could you tell me where tensor.item() is defined at the Github?
Or
where Class_torch.tensor's Menber functions(Method function) are defined??
Upvotes: 1
Views: 1595
Reputation: 101
Short answer:
torch/csrc/autograd/python_variable_indexing.cpp:268
Long answer:
I hope you like C++. ;)
The first thing to know is that item()
isn't (usually) a method in most Python classes. Instead, Python converts calls to item()
into other underlying methods like __getitem__()
as a convenience. Knowing that:
class Tensor
is defined at torch/tensor.py:40.
Most of Torch's underlying, compute intensive functionality is implemented in C and C++, including Tensor
. "class Tensor" is based on Torch._C.TensorBase
which is provided to Python via a C API from torch/csrc/autograd/python_variable.cpp:812
THPVariableType
is a map given to Python describing the C++ functions available on the object from Python. It's defined at torch/csrc/autograd/python_variable. The part relevant to you is the tp_as_mapping
entry (line 752), which provides functions for objects implementing the mapping protocol - basically Pyton Array-like objects (Python Documentation)
The THPVariable_as_mapping
structure at line 725 provides the mapping methods.The second variable provides the a subscript function used to get items by index (Python documentation)
Therefore, The C++ function TPHVariable_getitem
provides the implementation of Torch.Tensor.item()
, and it is defined at torch/csrc/autograd/python_variable_indexing
Upvotes: 4