Added a docstring for torch.Size.numel. (#124186)

Fixes #61231. Fixes #124167.

This PR documents a rather long-standing issue w.r.t. unexpected behavior of `torch.Size.numel`, first reported almost 5 years ago.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/124186
Approved by: https://github.com/janeyx99
This commit is contained in:
Tobias Ringwald 2024-04-19 09:22:58 +00:00 committed by PyTorch MergeBot
parent 520bc1080e
commit 58e403c739
4 changed files with 66 additions and 2 deletions

View File

@ -108,6 +108,7 @@ Features described in this documentation are classified by release status:
torch.random <random>
masked
torch.nested <nested>
size
sparse
storage
torch.testing <testing>

25
docs/source/size.rst Normal file
View File

@ -0,0 +1,25 @@
torch.Size
===================================
:class:`torch.Size` is the result type of a call to :func:`torch.Tensor.size`. It describes the size of all dimensions
of the original tensor. As a subclass of :class:`tuple`, it supports common sequence operations like indexing and
length.
Example::
>>> x = torch.ones(10, 20, 30)
>>> s = x.size()
>>> s
torch.Size([10, 20, 30])
>>> s[1]
20
>>> len(s)
3
.. autoclass:: torch.Size
:members:
:undoc-members:
:inherited-members:

View File

@ -1624,8 +1624,8 @@ import torch.nn.intrinsic
_C._init_names(list(torch._storage_classes))
# attach docstrings to torch and tensor functions
from . import _torch_docs, _tensor_docs, _storage_docs
del _torch_docs, _tensor_docs, _storage_docs
from . import _torch_docs, _tensor_docs, _storage_docs, _size_docs
del _torch_docs, _tensor_docs, _storage_docs, _size_docs
def compiled_with_cxx11_abi() -> builtins.bool:

38
torch/_size_docs.py Normal file
View File

@ -0,0 +1,38 @@
"""Adds docstrings to torch.Size functions"""
import torch._C
from torch._C import _add_docstr as add_docstr
def add_docstr_all(method, docstr):
add_docstr(getattr(torch._C.Size, method), docstr)
add_docstr_all(
"numel",
"""
numel() -> int
Returns the number of elements a :class:`torch.Tensor` with the given size would contain.
More formally, for a tensor ``x = tensor.ones(10, 10)`` with size ``s = torch.Size([10, 10])``,
``x.numel() == x.size().numel() == s.numel() == 100`` holds true.
Example::
>>> x=torch.ones(10, 10)
>>> s=x.size()
>>> s
torch.Size([10, 10])
>>> s.numel()
100
>>> x.numel() == s.numel()
True
.. warning::
This function does not return the number of dimensions described by :class:`torch.Size`, but instead the number
of elements a :class:`torch.Tensor` with that size would contain.
""",
)