Upload folder using huggingface_hub (part 29)
Browse filesFiles changed (21)
- .gitattributes+1
- .venv/lib/python3.12/site-packages/torch/signal/__init__.pyAdded+4
- .venv/lib/python3.12/site-packages/torch/signal/__pycache__/__init__.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/torch/signal/windows/__init__.pyAdded+28
- .venv/lib/python3.12/site-packages/torch/signal/windows/__pycache__/__init__.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/torch/signal/windows/__pycache__/windows.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/torch/signal/windows/windows.pyAdded+890
- .venv/lib/python3.12/site-packages/torch/sparse/__init__.pyAdded+703
- .venv/lib/python3.12/site-packages/torch/sparse/__pycache__/__init__.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/torch/sparse/__pycache__/_semi_structured_conversions.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/torch/sparse/__pycache__/_semi_structured_ops.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/torch/sparse/__pycache__/semi_structured.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/torch/sparse/_semi_structured_conversions.pyAdded+356
- .venv/lib/python3.12/site-packages/torch/sparse/_semi_structured_ops.pyAdded+197
- .venv/lib/python3.12/site-packages/torch/sparse/_triton_ops.pyAdded+2529
- .venv/lib/python3.12/site-packages/torch/sparse/_triton_ops_meta.pyAdded
- .venv/lib/python3.12/site-packages/torch/sparse/semi_structured.pyAdded+658
- .venv/lib/python3.12/site-packages/torch/special/__init__.pyAdded+1559
- .venv/lib/python3.12/site-packages/torch/special/__pycache__/__init__.cpython-312.pycAdded
- .venv/lib/python3.12/site-packages/torch/storage.pyAdded+1551
- .venv/lib/python3.12/site-packages/torch/test/CppSignature_testAdded+3
244 unmodified lines245246247244 unmodified lines.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/module.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/torch/nn/parallel/__pycache__/distributed.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/torch/onnx/__pycache__/symbolic_opset9.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text244 unmodified lines245246247248244 unmodified lines.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/module.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/torch/nn/parallel/__pycache__/distributed.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/torch/onnx/__pycache__/symbolic_opset9.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.12/site-packages/torch/test/CppSignature_test filter=lfs diff=lfs merge=lfs -text
1234from . import windows
__all__ = ["windows"]12345678910111213141516171819202122232425262728from .windows import ( bartlett, blackman, cosine, exponential, gaussian, general_cosine, general_hamming, hamming, hann, kaiser, nuttall,)
__all__ = [ "bartlett", "blackman", "cosine", "exponential", "gaussian", "general_cosine", "general_hamming", "hamming", "hann", "kaiser", "nuttall",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890# mypy: allow-untyped-defsfrom collections.abc import Iterablefrom math import sqrtfrom typing import Callable, Optional, TypeVar
import torchfrom torch import Tensorfrom torch._torch_docs import factory_common_args, merge_dicts, parse_kwargs
__all__ = [ "bartlett", "blackman", "cosine", "exponential", "gaussian", "general_cosine", "general_hamming", "hamming", "hann", "kaiser", "nuttall",]
_T = TypeVar("_T")
window_common_args = merge_dicts( parse_kwargs( """ M (int): the length of the window. In other words, the number of points of the returned window. sym (bool, optional): If `False`, returns a periodic window suitable for use in spectral analysis. If `True`, returns a symmetric window suitable for use in filter design. Default: `True`.""" ), factory_common_args, { "normalization": "The window is normalized to 1 (maximum value is 1). However, the 1 doesn't appear if " ":attr:`M` is even and :attr:`sym` is `True`.", },)
def _add_docstr(*args: str) -> Callable[[_T], _T]: r"""Adds docstrings to a given decorated function.
Specially useful when then docstrings needs string interpolation, e.g., with str.format(). REMARK: Do not use this function if the docstring doesn't need string interpolation, just write a conventional docstring.
Args: args (str): """
def decorator(o: _T) -> _T: o.__doc__ = "".join(args) return o
return decorator
def _window_function_checks( function_name: str, M: int, dtype: torch.dtype, layout: torch.layout) -> None: r"""Performs common checks for all the defined windows. This function should be called before computing any window.
Args: function_name (str): name of the window function. M (int): length of the window. dtype (:class:`torch.dtype`): the desired data type of returned tensor. layout (:class:`torch.layout`): the desired layout of returned tensor. """ if M < 0: raise ValueError( f"{function_name} requires non-negative window length, got M={M}" ) if layout is not torch.strided: raise ValueError( f"{function_name} is implemented for strided tensors only, got: {layout}" ) if dtype not in [torch.float32, torch.float64]: raise ValueError( f"{function_name} expects float32 or float64 dtypes, got: {dtype}" )
@_add_docstr( r"""Computes a window with an exponential waveform.Also known as Poisson window.
The exponential window is defined as follows:
.. math:: w_n = \exp{\left(-\frac{|n - c|}{\tau}\right)}
where `c` is the ``center`` of the window. """, r"""
{normalization}
Args: {M}
Keyword args: center (float, optional): where the center of the window will be located. Default: `M / 2` if `sym` is `False`, else `(M - 1) / 2`. tau (float, optional): the decay value. Tau is generally associated with a percentage, that means, that the value should vary within the interval (0, 100]. If tau is 100, it is considered the uniform window. Default: 1.0. {sym} {dtype} {layout} {device} {requires_grad}
Examples::
>>> # Generates a symmetric exponential window of size 10 and with a decay value of 1.0. >>> # The center will be at (M - 1) / 2, where M is 10. >>> torch.signal.windows.exponential(10) tensor([0.0111, 0.0302, 0.0821, 0.2231, 0.6065, 0.6065, 0.2231, 0.0821, 0.0302, 0.0111])
>>> # Generates a periodic exponential window and decay factor equal to .5 >>> torch.signal.windows.exponential(10, sym=False,tau=.5) tensor([4.5400e-05, 3.3546e-04, 2.4788e-03, 1.8316e-02, 1.3534e-01, 1.0000e+00, 1.3534e-01, 1.8316e-02, 2.4788e-03, 3.3546e-04]) """.format( **window_common_args ),)def exponential( M: int, *, center: Optional[float] = None, tau: float = 1.0, sym: bool = True, dtype: Optional[torch.dtype] = None, layout: torch.layout = torch.strided, device: Optional[torch.device] = None, requires_grad: bool = False,) -> Tensor: if dtype is None: dtype = torch.get_default_dtype()
_window_function_checks("exponential", M, dtype, layout)
if tau <= 0: raise ValueError(f"Tau must be positive, got: {tau} instead.")
if sym and center is not None: raise ValueError("Center must be None for symmetric windows")
if M == 0: return torch.empty( (0,), dtype=dtype, layout=layout, device=device, requires_grad=requires_grad )
if center is None: center = (M if not sym and M > 1 else M - 1) / 2.0
constant = 1 / tau
k = torch.linspace( start=-center * constant, end=(-center + (M - 1)) * constant, steps=M, dtype=dtype, layout=layout, device=device, requires_grad=requires_grad, )
return torch.exp(-torch.abs(k))
@_add_docstr( r"""Computes a window with a simple cosine waveform, following the same implementation as SciPy.This window is also known as the sine window.
The cosine window is defined as follows:
.. math:: w_n = \sin\left(\frac{\pi (n + 0.5)}{M}\right)
This formula differs from the typical cosine window formula by incorporating a 0.5 term in the numerator,which shifts the sample positions. This adjustment results in a window that starts and ends with non-zero values.
""", r"""
{normalization}
Args: {M}
Keyword args: {sym} {dtype} {layout} {device} {requires_grad}
Examples::
>>> # Generates a symmetric cosine window. >>> torch.signal.windows.cosine(10) tensor([0.1564, 0.4540, 0.7071, 0.8910, 0.9877, 0.9877, 0.8910, 0.7071, 0.4540, 0.1564])
>>> # Generates a periodic cosine window. >>> torch.signal.windows.cosine(10, sym=False) tensor([0.1423, 0.4154, 0.6549, 0.8413, 0.9595, 1.0000, 0.9595, 0.8413, 0.6549, 0.4154])""".format( **window_common_args, ),)def cosine( M: int, *, sym: bool = True, dtype: Optional[torch.dtype] = None, layout: torch.layout = torch.strided, device: Optional[torch.device] = None, requires_grad: bool = False,) -> Tensor: if dtype is None: dtype = torch.get_default_dtype()
_window_function_checks("cosine", M, dtype, layout)
if M == 0: return torch.empty( (0,), dtype=dtype, layout=layout, device=device, requires_grad=requires_grad )
start = 0.5 constant = torch.pi / (M + 1 if not sym and M > 1 else M)
k = torch.linspace( start=start * constant, end=(start + (M - 1)) * constant, steps=M, dtype=dtype, layout=layout, device=device, requires_grad=requires_grad, )
return torch.sin(k)
@_add_docstr( r"""Computes a window with a gaussian waveform.
The gaussian window is defined as follows:
.. math:: w_n = \exp{\left(-\left(\frac{n}{2\sigma}\right)^2\right)} """, r"""
{normalization}
Args: {M}
Keyword args: std (float, optional): the standard deviation of the gaussian. It controls how narrow or wide the window is. Default: 1.0. {sym} {dtype} {layout} {device} {requires_grad}
Examples::
>>> # Generates a symmetric gaussian window with a standard deviation of 1.0. >>> torch.signal.windows.gaussian(10) tensor([4.0065e-05, 2.1875e-03, 4.3937e-02, 3.2465e-01, 8.8250e-01, 8.8250e-01, 3.2465e-01, 4.3937e-02, 2.1875e-03, 4.0065e-05])
>>> # Generates a periodic gaussian window and standard deviation equal to 0.9. >>> torch.signal.windows.gaussian(10, sym=False,std=0.9) tensor([1.9858e-07, 5.1365e-05, 3.8659e-03, 8.4658e-02, 5.3941e-01, 1.0000e+00, 5.3941e-01, 8.4658e-02, 3.8659e-03, 5.1365e-05])""".format( **window_common_args, ),)def gaussian( M: int, *, std: float = 1.0, sym: bool = True, dtype: Optional[torch.dtype] = None, layout: torch.layout = torch.strided, device: Optional[torch.device] = None, requires_grad: bool = False,) -> Tensor: if dtype is None: dtype = torch.get_default_dtype()
_window_function_checks("gaussian", M, dtype, layout)
if std <= 0: raise ValueError(f"Standard deviation must be positive, got: {std} instead.")
if M == 0: return torch.empty( (0,), dtype=dtype, layout=layout, device=device, requires_grad=requires_grad )
start = -(M if not sym and M > 1 else M - 1) / 2.0
constant = 1 / (std * sqrt(2))
k = torch.linspace( start=start * constant, end=(start + (M - 1)) * constant, steps=M, dtype=dtype, layout=layout, device=device, requires_grad=requires_grad, )
return torch.exp(-(k**2))
@_add_docstr( r"""Computes the Kaiser window.
The Kaiser window is defined as follows:
.. math:: w_n = I_0 \left( \beta \sqrt{1 - \left( {\frac{n - N/2}{N/2}} \right) ^2 } \right) / I_0( \beta )
where ``I_0`` is the zeroth order modified Bessel function of the first kind (see :func:`torch.special.i0`), and``N = M - 1 if sym else M``. """, r"""
{normalization}
Args: {M}
Keyword args: beta (float, optional): shape parameter for the window. Must be non-negative. Default: 12.0 {sym} {dtype} {layout} {device} {requires_grad}
Examples::
>>> # Generates a symmetric gaussian window with a standard deviation of 1.0. >>> torch.signal.windows.kaiser(5) tensor([4.0065e-05, 2.1875e-03, 4.3937e-02, 3.2465e-01, 8.8250e-01, 8.8250e-01, 3.2465e-01, 4.3937e-02, 2.1875e-03, 4.0065e-05]) >>> # Generates a periodic gaussian window and standard deviation equal to 0.9. >>> torch.signal.windows.kaiser(5, sym=False,std=0.9) tensor([1.9858e-07, 5.1365e-05, 3.8659e-03, 8.4658e-02, 5.3941e-01, 1.0000e+00, 5.3941e-01, 8.4658e-02, 3.8659e-03, 5.1365e-05])""".format( **window_common_args, ),)def kaiser( M: int, *, beta: float = 12.0, sym: bool = True, dtype: Optional[torch.dtype] = None, layout: torch.layout = torch.strided, device: Optional[torch.device] = None, requires_grad: bool = False,) -> Tensor: if dtype is None: dtype = torch.get_default_dtype()
_window_function_checks("kaiser", M, dtype, layout)
if beta < 0: raise ValueError(f"beta must be non-negative, got: {beta} instead.")
if M == 0: return torch.empty( (0,), dtype=dtype, layout=layout, device=device, requires_grad=requires_grad )
if M == 1: return torch.ones( (1,), dtype=dtype, layout=layout, device=device, requires_grad=requires_grad )
# Avoid NaNs by casting `beta` to the appropriate dtype. beta = torch.tensor(beta, dtype=dtype, device=device)
start = -beta constant = 2.0 * beta / (M if not sym else M - 1) end = torch.minimum(beta, start + (M - 1) * constant)
k = torch.linspace( start=start, end=end, steps=M, dtype=dtype, layout=layout, device=device, requires_grad=requires_grad, )
return torch.i0(torch.sqrt(beta * beta - torch.pow(k, 2))) / torch.i0(beta)
@_add_docstr( r"""Computes the Hamming window.
The Hamming window is defined as follows:
.. math:: w_n = \alpha - \beta\ \cos \left( \frac{2 \pi n}{M - 1} \right) """, r"""
{normalization}
Arguments: {M}
Keyword args: {sym} alpha (float, optional): The coefficient :math:`\alpha` in the equation above. beta (float, optional): The coefficient :math:`\beta` in the equation above. {dtype} {layout} {device} {requires_grad}
Examples::
>>> # Generates a symmetric Hamming window. >>> torch.signal.windows.hamming(10) tensor([0.0800, 0.1876, 0.4601, 0.7700, 0.9723, 0.9723, 0.7700, 0.4601, 0.1876, 0.0800])
>>> # Generates a periodic Hamming window. >>> torch.signal.windows.hamming(10, sym=False) tensor([0.0800, 0.1679, 0.3979, 0.6821, 0.9121, 1.0000, 0.9121, 0.6821, 0.3979, 0.1679])""".format( **window_common_args ),)def hamming( M: int, *, sym: bool = True, dtype: Optional[torch.dtype] = None, layout: torch.layout = torch.strided, device: Optional[torch.device] = None, requires_grad: bool = False,) -> Tensor: return general_hamming( M, sym=sym, dtype=dtype, layout=layout, device=device, requires_grad=requires_grad, )
@_add_docstr( r"""Computes the Hann window.
The Hann window is defined as follows:
.. math:: w_n = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{M - 1} \right)\right] = \sin^2 \left( \frac{\pi n}{M - 1} \right) """, r"""
{normalization}
Arguments: {M}
Keyword args: {sym} {dtype} {layout} {device} {requires_grad}
Examples::
>>> # Generates a symmetric Hann window. >>> torch.signal.windows.hann(10) tensor([0.0000, 0.1170, 0.4132, 0.7500, 0.9698, 0.9698, 0.7500, 0.4132, 0.1170, 0.0000])
>>> # Generates a periodic Hann window. >>> torch.signal.windows.hann(10, sym=False) tensor([0.0000, 0.0955, 0.3455, 0.6545, 0.9045, 1.0000, 0.9045, 0.6545, 0.3455, 0.0955])""".format( **window_common_args ),)def hann( M: int, *, sym: bool = True, dtype: Optional[torch.dtype] = None, layout: torch.layout = torch.strided, device: Optional[torch.device] = None, requires_grad: bool = False,) -> Tensor: return general_hamming( M, alpha=0.5, sym=sym, dtype=dtype, layout=layout, device=device, requires_grad=requires_grad, )
@_add_docstr( r"""Computes the Blackman window.
The Blackman window is defined as follows:
.. math:: w_n = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{M - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{M - 1} \right) """, r"""
{normalization}
Arguments: {M}
Keyword args: {sym} {dtype} {layout} {device} {requires_grad}
Examples::
>>> # Generates a symmetric Blackman window. >>> torch.signal.windows.blackman(5) tensor([-1.4901e-08, 3.4000e-01, 1.0000e+00, 3.4000e-01, -1.4901e-08])
>>> # Generates a periodic Blackman window. >>> torch.signal.windows.blackman(5, sym=False) tensor([-1.4901e-08, 2.0077e-01, 8.4923e-01, 8.4923e-01, 2.0077e-01])""".format( **window_common_args ),)def blackman( M: int, *, sym: bool = True, dtype: Optional[torch.dtype] = None, layout: torch.layout = torch.strided, device: Optional[torch.device] = None, requires_grad: bool = False,) -> Tensor: if dtype is None: dtype = torch.get_default_dtype()
_window_function_checks("blackman", M, dtype, layout)
return general_cosine( M, a=[0.42, 0.5, 0.08], sym=sym, dtype=dtype, layout=layout, device=device, requires_grad=requires_grad, )
@_add_docstr( r"""Computes the Bartlett window.
The Bartlett window is defined as follows:
.. math:: w_n = 1 - \left| \frac{2n}{M - 1} - 1 \right| = \begin{cases} \frac{2n}{M - 1} & \text{if } 0 \leq n \leq \frac{M - 1}{2} \\ 2 - \frac{2n}{M - 1} & \text{if } \frac{M - 1}{2} < n < M \\ \end{cases} """, r"""
{normalization}
Arguments: {M}
Keyword args: {sym} {dtype} {layout} {device} {requires_grad}
Examples::
>>> # Generates a symmetric Bartlett window. >>> torch.signal.windows.bartlett(10) tensor([0.0000, 0.2222, 0.4444, 0.6667, 0.8889, 0.8889, 0.6667, 0.4444, 0.2222, 0.0000])
>>> # Generates a periodic Bartlett window. >>> torch.signal.windows.bartlett(10, sym=False) tensor([0.0000, 0.2000, 0.4000, 0.6000, 0.8000, 1.0000, 0.8000, 0.6000, 0.4000, 0.2000])""".format( **window_common_args ),)def bartlett( M: int, *, sym: bool = True, dtype: Optional[torch.dtype] = None, layout: torch.layout = torch.strided, device: Optional[torch.device] = None, requires_grad: bool = False,) -> Tensor: if dtype is None: dtype = torch.get_default_dtype()
_window_function_checks("bartlett", M, dtype, layout)
if M == 0: return torch.empty( (0,), dtype=dtype, layout=layout, device=device, requires_grad=requires_grad )
if M == 1: return torch.ones( (1,), dtype=dtype, layout=layout, device=device, requires_grad=requires_grad )
start = -1 constant = 2 / (M if not sym else M - 1)
k = torch.linspace( start=start, end=start + (M - 1) * constant, steps=M, dtype=dtype, layout=layout, device=device, requires_grad=requires_grad, )
return 1 - torch.abs(k)
@_add_docstr( r"""Computes the general cosine window.
The general cosine window is defined as follows:
.. math:: w_n = \sum^{M-1}_{i=0} (-1)^i a_i \cos{ \left( \frac{2 \pi i n}{M - 1}\right)} """, r"""
{normalization}
Arguments: {M}
Keyword args: a (Iterable): the coefficients associated to each of the cosine functions. {sym} {dtype} {layout} {device} {requires_grad}
Examples::
>>> # Generates a symmetric general cosine window with 3 coefficients. >>> torch.signal.windows.general_cosine(10, a=[0.46, 0.23, 0.31], sym=True) tensor([0.5400, 0.3376, 0.1288, 0.4200, 0.9136, 0.9136, 0.4200, 0.1288, 0.3376, 0.5400])
>>> # Generates a periodic general cosine window with 2 coefficients. >>> torch.signal.windows.general_cosine(10, a=[0.5, 1 - 0.5], sym=False) tensor([0.0000, 0.0955, 0.3455, 0.6545, 0.9045, 1.0000, 0.9045, 0.6545, 0.3455, 0.0955])""".format( **window_common_args ),)def general_cosine( M, *, a: Iterable, sym: bool = True, dtype: Optional[torch.dtype] = None, layout: torch.layout = torch.strided, device: Optional[torch.device] = None, requires_grad: bool = False,) -> Tensor: if dtype is None: dtype = torch.get_default_dtype()
_window_function_checks("general_cosine", M, dtype, layout)
if M == 0: return torch.empty( (0,), dtype=dtype, layout=layout, device=device, requires_grad=requires_grad )
if M == 1: return torch.ones( (1,), dtype=dtype, layout=layout, device=device, requires_grad=requires_grad )
if not isinstance(a, Iterable): raise TypeError("Coefficients must be a list/tuple")
if not a: raise ValueError("Coefficients cannot be empty")
constant = 2 * torch.pi / (M if not sym else M - 1)
k = torch.linspace( start=0, end=(M - 1) * constant, steps=M, dtype=dtype, layout=layout, device=device, requires_grad=requires_grad, )
a_i = torch.tensor( [(-1) ** i * w for i, w in enumerate(a)], device=device, dtype=dtype, requires_grad=requires_grad, ) i = torch.arange( a_i.shape[0], dtype=a_i.dtype, device=a_i.device, requires_grad=a_i.requires_grad, ) return (a_i.unsqueeze(-1) * torch.cos(i.unsqueeze(-1) * k)).sum(0)
@_add_docstr( r"""Computes the general Hamming window.
The general Hamming window is defined as follows:
.. math:: w_n = \alpha - (1 - \alpha) \cos{ \left( \frac{2 \pi n}{M-1} \right)} """, r"""
{normalization}
Arguments: {M}
Keyword args: alpha (float, optional): the window coefficient. Default: 0.54. {sym} {dtype} {layout} {device} {requires_grad}
Examples::
>>> # Generates a symmetric Hamming window with the general Hamming window. >>> torch.signal.windows.general_hamming(10, sym=True) tensor([0.0800, 0.1876, 0.4601, 0.7700, 0.9723, 0.9723, 0.7700, 0.4601, 0.1876, 0.0800])
>>> # Generates a periodic Hann window with the general Hamming window. >>> torch.signal.windows.general_hamming(10, alpha=0.5, sym=False) tensor([0.0000, 0.0955, 0.3455, 0.6545, 0.9045, 1.0000, 0.9045, 0.6545, 0.3455, 0.0955])""".format( **window_common_args ),)def general_hamming( M, *, alpha: float = 0.54, sym: bool = True, dtype: Optional[torch.dtype] = None, layout: torch.layout = torch.strided, device: Optional[torch.device] = None, requires_grad: bool = False,) -> Tensor: return general_cosine( M, a=[alpha, 1.0 - alpha], sym=sym, dtype=dtype, layout=layout, device=device, requires_grad=requires_grad, )
@_add_docstr( r"""Computes the minimum 4-term Blackman-Harris window according to Nuttall.
.. math:: w_n = 1 - 0.36358 \cos{(z_n)} + 0.48917 \cos{(2z_n)} - 0.13659 \cos{(3z_n)} + 0.01064 \cos{(4z_n)}
where :math:`z_n = \frac{2 \pi n}{M}`. """, """
{normalization}
Arguments: {M}
Keyword args: {sym} {dtype} {layout} {device} {requires_grad}
References::
- A. Nuttall, "Some windows with very good sidelobe behavior," IEEE Transactions on Acoustics, Speech, and Signal Processing, vol. 29, no. 1, pp. 84-91, Feb 1981. https://doi.org/10.1109/TASSP.1981.1163506
- Heinzel G. et al., "Spectrum and spectral density estimation by the Discrete Fourier transform (DFT), including a comprehensive list of window functions and some new flat-top windows", February 15, 2002 https://holometer.fnal.gov/GH_FFT.pdf
Examples::
>>> # Generates a symmetric Nutall window. >>> torch.signal.windows.general_hamming(5, sym=True) tensor([3.6280e-04, 2.2698e-01, 1.0000e+00, 2.2698e-01, 3.6280e-04])
>>> # Generates a periodic Nuttall window. >>> torch.signal.windows.general_hamming(5, sym=False) tensor([3.6280e-04, 1.1052e-01, 7.9826e-01, 7.9826e-01, 1.1052e-01])""".format( **window_common_args ),)def nuttall( M: int, *, sym: bool = True, dtype: Optional[torch.dtype] = None, layout: torch.layout = torch.strided, device: Optional[torch.device] = None, requires_grad: bool = False,) -> Tensor: return general_cosine( M, a=[0.3635819, 0.4891775, 0.1365995, 0.0106411], sym=sym, dtype=dtype, layout=layout, device=device, requires_grad=requires_grad, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703# mypy: allow-untyped-defs# The Tensor classes are added to this module by python_tensor.cpp# A workaround to support both TorchScript and MyPy:from typing import Any, Optional, TYPE_CHECKING, Union
import torchfrom torch import Tensorfrom torch._C import _add_docstr, _sparse # type: ignore[attr-defined]
# Semi structured sparsity supportfrom .semi_structured import ( SparseSemiStructuredTensor, SparseSemiStructuredTensorCUSPARSELT, SparseSemiStructuredTensorCUTLASS, to_sparse_semi_structured,)
if TYPE_CHECKING: from torch.types import _dtype as DType
DimOrDims = Optional[Union[int, tuple[int, ...], list[int]]]else: # The JIT doesn't understand Union, nor torch.dtype here DType = int DimOrDims = Optional[tuple[int]]
__all__ = [ "addmm", "check_sparse_tensor_invariants", "mm", "sum", "softmax", "solve", "log_softmax", "SparseSemiStructuredTensor", "SparseSemiStructuredTensorCUTLASS", "SparseSemiStructuredTensorCUSPARSELT", "to_sparse_semi_structured", "as_sparse_gradcheck",]
addmm = _add_docstr( _sparse._sparse_addmm, r"""sparse.addmm(mat, mat1, mat2, *, beta=1., alpha=1.) -> Tensor
This function does exact same thing as :func:`torch.addmm` in the forward,except that it supports backward for sparse COO matrix :attr:`mat1`.When :attr:`mat1` is a COO tensor it must have `sparse_dim = 2`.When inputs are COO tensors, this function also supports backward for both inputs.
Supports both CSR and COO storage formats.
.. note:: This function doesn't support computing derivatives with respect to CSR matrices.
Args: mat (Tensor): a dense matrix to be added mat1 (Tensor): a sparse matrix to be multiplied mat2 (Tensor): a dense matrix to be multiplied beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`)""",)
mm = _add_docstr( _sparse._sparse_mm, r""" Performs a matrix multiplication of the sparse matrix :attr:`mat1` and the (sparse or strided) matrix :attr:`mat2`. Similar to :func:`torch.mm`, if :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a :math:`(m \times p)` tensor, out will be a :math:`(n \times p)` tensor. When :attr:`mat1` is a COO tensor it must have `sparse_dim = 2`. When inputs are COO tensors, this function also supports backward for both inputs.
Supports both CSR and COO storage formats.
.. note:: This function doesn't support computing derivatives with respect to CSR matrices.
This function also additionally accepts an optional :attr:`reduce` argument that allows specification of an optional reduction operation, mathematically performs the following operation:
.. math::
z_{ij} = \bigoplus_{k = 0}^{K - 1} x_{ik} y_{kj}
where :math:`\bigoplus` defines the reduce operator. :attr:`reduce` is implemented only forCSR storage format on CPU device.
Args: mat1 (Tensor): the first sparse matrix to be multiplied mat2 (Tensor): the second matrix to be multiplied, which could be sparse or dense reduce (str, optional): the reduction operation to apply for non-unique indices (:obj:`"sum"`, :obj:`"mean"`, :obj:`"amax"`, :obj:`"amin"`). Default :obj:`"sum"`.
Shape: The format of the output tensor of this function follows: - sparse x sparse -> sparse - sparse x dense -> dense
Example::
>>> a = torch.tensor([[1., 0, 2], [0, 3, 0]]).to_sparse().requires_grad_() >>> a tensor(indices=tensor([[0, 0, 1], [0, 2, 1]]), values=tensor([1., 2., 3.]), size=(2, 3), nnz=3, layout=torch.sparse_coo, requires_grad=True) >>> b = torch.tensor([[0, 1.], [2, 0], [0, 0]], requires_grad=True) >>> b tensor([[0., 1.], [2., 0.], [0., 0.]], requires_grad=True) >>> y = torch.sparse.mm(a, b) >>> y tensor([[0., 1.], [6., 0.]], grad_fn=<SparseAddmmBackward0>) >>> y.sum().backward() >>> a.grad tensor(indices=tensor([[0, 0, 1], [0, 2, 1]]), values=tensor([1., 0., 2.]), size=(2, 3), nnz=3, layout=torch.sparse_coo) >>> c = a.detach().to_sparse_csr() >>> c tensor(crow_indices=tensor([0, 2, 3]), col_indices=tensor([0, 2, 1]), values=tensor([1., 2., 3.]), size=(2, 3), nnz=3, layout=torch.sparse_csr) >>> y1 = torch.sparse.mm(c, b, 'sum') >>> y1 tensor([[0., 1.], [6., 0.]], grad_fn=<SparseMmReduceImplBackward0>) >>> y2 = torch.sparse.mm(c, b, 'max') >>> y2 tensor([[0., 1.], [6., 0.]], grad_fn=<SparseMmReduceImplBackward0>)""",)
sampled_addmm = _add_docstr( _sparse.sparse_sampled_addmm, r"""sparse.sampled_addmm(input, mat1, mat2, *, beta=1., alpha=1., out=None) -> Tensor
Performs a matrix multiplication of the dense matrices :attr:`mat1` and :attr:`mat2` at the locationsspecified by the sparsity pattern of :attr:`input`. The matrix :attr:`input` is added to the final result.
Mathematically this performs the following operation:
.. math::
\text{out} = \alpha\ (\text{mat1} \mathbin{@} \text{mat2})*\text{spy}(\text{input}) + \beta\ \text{input}
where :math:`\text{spy}(\text{input})` is the sparsity pattern matrix of :attr:`input`, :attr:`alpha`and :attr:`beta` are the scaling factors.:math:`\text{spy}(\text{input})` has value 1 at the positions where :attr:`input` has non-zero values, and 0 elsewhere.
.. note:: :attr:`input` must be a sparse CSR tensor. :attr:`mat1` and :attr:`mat2` must be dense tensors.
Args: input (Tensor): a sparse CSR matrix of shape `(m, n)` to be added and used to compute the sampled matrix multiplication mat1 (Tensor): a dense matrix of shape `(m, k)` to be multiplied mat2 (Tensor): a dense matrix of shape `(k, n)` to be multiplied
Keyword args: beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`) alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) out (Tensor, optional): output tensor. Ignored if `None`. Default: `None`.
Examples::
>>> input = torch.eye(3, device='cuda').to_sparse_csr() >>> mat1 = torch.randn(3, 5, device='cuda') >>> mat2 = torch.randn(5, 3, device='cuda') >>> torch.sparse.sampled_addmm(input, mat1, mat2) tensor(crow_indices=tensor([0, 1, 2, 3]), col_indices=tensor([0, 1, 2]), values=tensor([ 0.2847, -0.7805, -0.1900]), device='cuda:0', size=(3, 3), nnz=3, layout=torch.sparse_csr) >>> torch.sparse.sampled_addmm(input, mat1, mat2).to_dense() tensor([[ 0.2847, 0.0000, 0.0000], [ 0.0000, -0.7805, 0.0000], [ 0.0000, 0.0000, -0.1900]], device='cuda:0') >>> torch.sparse.sampled_addmm(input, mat1, mat2, beta=0.5, alpha=0.5) tensor(crow_indices=tensor([0, 1, 2, 3]), col_indices=tensor([0, 1, 2]), values=tensor([ 0.1423, -0.3903, -0.0950]), device='cuda:0', size=(3, 3), nnz=3, layout=torch.sparse_csr)""",)
def sum(input: Tensor, dim: DimOrDims = None, dtype: Optional[DType] = None) -> Tensor: r"""Return the sum of each row of the given sparse tensor.
Returns the sum of each row of the sparse tensor :attr:`input` in the given dimensions :attr:`dim`. If :attr:`dim` is a list of dimensions, reduce over all of them. When sum over all ``sparse_dim``, this method returns a dense tensor instead of a sparse tensor.
All summed :attr:`dim` are squeezed (see :func:`torch.squeeze`), resulting an output tensor having :attr:`dim` fewer dimensions than :attr:`input`.
During backward, only gradients at ``nnz`` locations of :attr:`input` will propagate back. Note that the gradients of :attr:`input` is coalesced.
Args: input (Tensor): the input sparse tensor dim (int or tuple of ints): a dimension or a list of dimensions to reduce. Default: reduce over all dims. dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. Default: dtype of :attr:`input`.
Example::
>>> nnz = 3 >>> dims = [5, 5, 2, 3] >>> I = torch.cat([torch.randint(0, dims[0], size=(nnz,)), torch.randint(0, dims[1], size=(nnz,))], 0).reshape(2, nnz) >>> V = torch.randn(nnz, dims[2], dims[3]) >>> size = torch.Size(dims) >>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> S = torch.sparse_coo_tensor(I, V, size) >>> S tensor(indices=tensor([[2, 0, 3], [2, 4, 1]]), values=tensor([[[-0.6438, -1.6467, 1.4004], [ 0.3411, 0.0918, -0.2312]],
[[ 0.5348, 0.0634, -2.0494], [-0.7125, -1.0646, 2.1844]],
[[ 0.1276, 0.1874, -0.6334], [-1.9682, -0.5340, 0.7483]]]), size=(5, 5, 2, 3), nnz=3, layout=torch.sparse_coo)
# when sum over only part of sparse_dims, return a sparse tensor >>> torch.sparse.sum(S, [1, 3]) tensor(indices=tensor([[0, 2, 3]]), values=tensor([[-1.4512, 0.4073], [-0.8901, 0.2017], [-0.3183, -1.7539]]), size=(5, 2), nnz=3, layout=torch.sparse_coo)
# when sum over all sparse dim, return a dense tensor # with summed dims squeezed >>> torch.sparse.sum(S, [0, 1, 3]) tensor([-2.6596, -1.1450]) """ if dtype is None: if dim is not None: return torch._sparse_sum(input, dim) else: return torch._sparse_sum(input) else: if dim is not None: return torch._sparse_sum(input, dim, dtype=dtype) else: return torch._sparse_sum(input, dtype=dtype)
softmax = _add_docstr( _sparse._sparse_softmax, r"""sparse.softmax(input, dim, *, dtype=None) -> Tensor
Applies a softmax function.
Softmax is defined as:
:math:`\text{Softmax}(x_{i}) = \frac{exp(x_i)}{\sum_j exp(x_j)}`
where :math:`i, j` run over sparse tensor indices and unspecifiedentries are ignores. This is equivalent to defining unspecifiedentries as negative infinity so that :math:`exp(x_k) = 0` when theentry with index :math:`k` has not specified.
It is applied to all slices along `dim`, and will re-scale them sothat the elements lie in the range `[0, 1]` and sum to 1.
Args: input (Tensor): input dim (int): A dimension along which softmax will be computed. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. If specified, the input tensor is casted to :attr:`dtype` before the operation is performed. This is useful for preventing data type overflows. Default: None""",)
spsolve = _add_docstr( _sparse._spsolve, r"""sparse.spsolve(input, other, *, left=True) -> Tensor
Computes the solution of a square system of linear equations witha unique solution. Its purpose is similar to :func:`torch.linalg.solve`,except that the system is defined by a sparse CSR matrix with layout`sparse_csr`.
Args: input (Tensor): a sparse CSR matrix of shape `(n, n)` representing the coefficients of the linear system. other (Tensor): a dense matrix of shape `(n, )` representing the right-hand side of the linear system. left (bool, optional): whether to solve the system for `input @ out = other` (default) or `out @ input = other`. Only `left=True` is supported.""",)
log_softmax = _add_docstr( _sparse._sparse_log_softmax, r"""sparse.log_softmax(input, dim, *, dtype=None) -> Tensor
Applies a softmax function followed by logarithm.
See :class:`~torch.sparse.softmax` for more details.
Args: input (Tensor): input dim (int): A dimension along which softmax will be computed. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. If specified, the input tensor is casted to :attr:`dtype` before the operation is performed. This is useful for preventing data type overflows. Default: None""",)
spdiags = _add_docstr( _sparse._spdiags, r"""sparse.spdiags(diagonals, offsets, shape, layout=None) -> Tensor
Creates a sparse 2D tensor by placing the values from rows of:attr:`diagonals` along specified diagonals of the output
The :attr:`offsets` tensor controls which diagonals are set.
- If :attr:`offsets[i]` = 0, it is the main diagonal- If :attr:`offsets[i]` < 0, it is below the main diagonal- If :attr:`offsets[i]` > 0, it is above the main diagonal
The number of rows in :attr:`diagonals` must match the length of :attr:`offsets`,and an offset may not be repeated.
Args: diagonals (Tensor): Matrix storing diagonals row-wise offsets (Tensor): The diagonals to be set, stored as a vector shape (2-tuple of ints): The desired shape of the resultKeyword args: layout (:class:`torch.layout`, optional): The desired layout of the returned tensor. ``torch.sparse_coo``, ``torch.sparse_csc`` and ``torch.sparse_csr`` are supported. Default: ``torch.sparse_coo``
Examples:
Set the main and first two lower diagonals of a matrix::
>>> diags = torch.arange(9).reshape(3, 3) >>> diags tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> s = torch.sparse.spdiags(diags, torch.tensor([0, -1, -2]), (3, 3)) >>> s tensor(indices=tensor([[0, 1, 2, 1, 2, 2], [0, 1, 2, 0, 1, 0]]), values=tensor([0, 1, 2, 3, 4, 6]), size=(3, 3), nnz=6, layout=torch.sparse_coo) >>> s.to_dense() tensor([[0, 0, 0], [3, 1, 0], [6, 4, 2]])
Change the output layout::
>>> diags = torch.arange(9).reshape(3, 3) >>> diags tensor([[0, 1, 2],[3, 4, 5], [6, 7, 8]) >>> s = torch.sparse.spdiags(diags, torch.tensor([0, -1, -2]), (3, 3), layout=torch.sparse_csr) >>> s tensor(crow_indices=tensor([0, 1, 3, 6]), col_indices=tensor([0, 0, 1, 0, 1, 2]), values=tensor([0, 3, 1, 6, 4, 2]), size=(3, 3), nnz=6, layout=torch.sparse_csr) >>> s.to_dense() tensor([[0, 0, 0], [3, 1, 0], [6, 4, 2]])
Set partial diagonals of a large output::
>>> diags = torch.tensor([[1, 2], [3, 4]]) >>> offsets = torch.tensor([0, -1]) >>> torch.sparse.spdiags(diags, offsets, (5, 5)).to_dense() tensor([[1, 0, 0, 0, 0], [3, 2, 0, 0, 0], [0, 4, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])
.. note::
When setting the values along a given diagonal the index into the diagonal and the index into the row of :attr:`diagonals` is taken as the column index in the output. This has the effect that when setting a diagonal with a positive offset `k` the first value along that diagonal will be the value in position `k` of the row of :attr:`diagonals`
Specifying a positive offset::
>>> diags = torch.tensor([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) >>> torch.sparse.spdiags(diags, torch.tensor([0, 1, 2]), (5, 5)).to_dense() tensor([[1, 2, 3, 0, 0], [0, 2, 3, 0, 0], [0, 0, 3, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])""",)
class check_sparse_tensor_invariants: """A tool to control checking sparse tensor invariants.
The following options exists to manage sparsr tensor invariants checking in sparse tensor construction:
1. Using a context manager:
.. code:: python
with torch.sparse.check_sparse_tensor_invariants(): run_my_model()
2. Using a procedural approach:
.. code:: python
prev_checks_enabled = torch.sparse.check_sparse_tensor_invariants.is_enabled() torch.sparse.check_sparse_tensor_invariants.enable()
run_my_model()
if not prev_checks_enabled: torch.sparse.check_sparse_tensor_invariants.disable()
3. Using function decoration:
.. code:: python
@torch.sparse.check_sparse_tensor_invariants() def run_my_model(): ...
run_my_model()
4. Using ``check_invariants`` keyword argument in sparse tensor constructor call. For example:
>>> torch.sparse_csr_tensor([0, 1, 3], [0, 1], [1, 2], check_invariants=True) Traceback (most recent call last): File "<stdin>", line 1, in <module> RuntimeError: `crow_indices[..., -1] == nnz` is not satisfied. """
@staticmethod def is_enabled(): r"""Return True if the sparse tensor invariants checking is enabled.
.. note::
Use :func:`torch.sparse.check_sparse_tensor_invariants.enable` or :func:`torch.sparse.check_sparse_tensor_invariants.disable` to manage the state of the sparse tensor invariants checks. """ return torch._C._check_sparse_tensor_invariants()
@staticmethod def enable(): r"""Enable sparse tensor invariants checking in sparse tensor constructors.
.. note::
By default, the sparse tensor invariants checks are disabled. Use :func:`torch.sparse.check_sparse_tensor_invariants.is_enabled` to retrieve the current state of sparse tensor invariants checking.
.. note::
The sparse tensor invariants check flag is effective to all sparse tensor constructors, both in Python and ATen.
The flag can be locally overridden by the ``check_invariants`` optional argument of the sparse tensor constructor functions. """ torch._C._set_check_sparse_tensor_invariants(True)
@staticmethod def disable(): r"""Disable sparse tensor invariants checking in sparse tensor constructors.
See :func:`torch.sparse.check_sparse_tensor_invariants.enable` for more information. """ torch._C._set_check_sparse_tensor_invariants(False)
# context manager support def __init__(self, enable=True): self.state = enable self.saved_state: Optional[bool] = None
def __enter__(self): if self.saved_state is not None: raise RuntimeError( "This context manager instance is already activated." " Use a different context manager instance for context nesting." ) self.saved_state = self.is_enabled() torch._C._set_check_sparse_tensor_invariants(self.state)
def __exit__(self, type, value, traceback): assert self.saved_state is not None torch._C._set_check_sparse_tensor_invariants(self.saved_state) self.saved_state = None
# decorator support def __call__(self, mth): def test_mth(*args, **kwargs): with type(self)(self.state): return mth(*args, **kwargs)
return test_mth
def as_sparse_gradcheck(gradcheck): """Decorate function, to extend gradcheck for sparse tensors.
Decorator for torch.autograd.gradcheck or its functools.partial variants that extends the gradcheck function with support to input functions that operate on or/and return sparse tensors.
The specified gradcheck function itself is guaranteed to operate on strided tensors only.
For example:
>>> gradcheck = torch.sparse.as_sparse_gradcheck(torch.autograd.gradcheck) >>> x = torch.tensor([[0, 1], [2, 3]], dtype=torch.float64).to_sparse_coo().requires_grad_(True) >>> gradcheck(lambda x: x.to_sparse_csr(), x) True """
def gradcheck_with_sparse_support(func, inputs, **kwargs): """ Create gradcheck with support for sparse tensors.
Same as :func:`torch.autograd.gradcheck` but with sparse tensors inputs and outputs support. """ masked = kwargs.pop("masked", False) sparse_layouts = { torch.sparse_coo, torch.sparse_csr, torch.sparse_csc, torch.sparse_bsr, torch.sparse_bsc, } sparse_compressed_layouts = { torch.sparse_csr, torch.sparse_csc, torch.sparse_bsr, torch.sparse_bsc, } sparse_block_layouts = {torch.sparse_bsr, torch.sparse_bsc} STRIDED_REPRESENTATION = "__STRIDED_REPRESENTATION__"
def convert_to_strided_representation(args): """Convert differentiable non-strided tensors to a representation containing differentiable strided tensors.""" if not isinstance(args, (list, tuple)): args = (args,) new_args: list[Any] = [] for obj in args: if ( isinstance(obj, torch.Tensor) and obj.requires_grad and obj.layout in sparse_layouts ): d = dict(layout=obj.layout, shape=obj.shape) if not masked: # Materialize unspecified elements with zero values batch_dim = obj.ndim - obj.dense_dim() - obj.sparse_dim() blocksize = ( obj.values().shape[batch_dim + 1 : batch_dim + 3] if obj.layout in sparse_block_layouts else None ) full_mask = torch.ones( obj.shape, device=obj.device, dtype=torch.bool ).to_sparse( layout=obj.layout, blocksize=blocksize, dense_dim=obj.dense_dim(), ) obj = obj.to_dense().sparse_mask(full_mask) if obj.layout is torch.sparse_coo: d.update( indices=obj._indices(), is_coalesced=obj.is_coalesced() ) values = obj._values() elif obj.layout in {torch.sparse_csr, torch.sparse_bsr}: d.update( compressed_indices=obj.crow_indices(), plain_indices=obj.col_indices(), ) values = obj.values() else: d.update( compressed_indices=obj.ccol_indices(), plain_indices=obj.row_indices(), ) values = obj.values() new_args.extend( (STRIDED_REPRESENTATION, d, values.requires_grad_(True)) ) else: new_args.append(obj) return tuple(new_args)
def restore_from_strided_representation(args): """Restore non-strided differentiable tensosr from their strided representations.""" new_args = [] args = list(args) while args: a = args.pop(0) if a == STRIDED_REPRESENTATION: d, values = args.pop(0), args.pop(0) if d["layout"] is torch.sparse_coo: a = torch.sparse_coo_tensor( d["indices"], values, size=d["shape"], is_coalesced=d["is_coalesced"], ) elif d["layout"] in sparse_compressed_layouts: a = torch.sparse_compressed_tensor( d["compressed_indices"], d["plain_indices"], values, size=d["shape"], layout=d["layout"], ) else: raise NotImplementedError( f'conversion of {d["layout"]} strided representation to tensor' ) new_args.append(a) return tuple(new_args)
def func_wrapper(*args, **kwargs): restored_args = restore_from_strided_representation(args)
# convert differentiable output sparse tensors to strided # tensors: outputs = func(*restored_args, **kwargs)
strided_outputs = ( tuple(outputs) if isinstance(outputs, (list, tuple)) else (outputs,) ) strided_outputs = tuple( ( o.to_dense(masked_grad=masked) if isinstance(o, torch.Tensor) and o.requires_grad and o.layout in sparse_layouts else o ) for o in strided_outputs )
return ( strided_outputs if isinstance(outputs, (list, tuple)) else strided_outputs[0] )
args = (func_wrapper, convert_to_strided_representation(inputs))
return gradcheck(*args, **kwargs)
return gradcheck_with_sparse_support123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356# mypy: allow-untyped-defsimport torch
def _calculate_meta_reordering_scatter_offsets(m, meta_ncols, meta_dtype, device): """ This is PyTorch implementation of main part of reorder_meta() function, from tools/util/include/cutlass/util/host_reorder.h file of CUTLASS source tree. Furthermore, CUTLASS template for sparse GEMM decides upon layout of this matrix, and at the moment for the sparse GEMM executed on tensor cores, this is layout described by ColumnMajorInterleaved<2> data structure, in include/cutlass/layout/matrix.h of CUTLASS source tree. The reordering of meta matrix into meta_reordered matrix calculated according to these segments of CUTLASS code is re-implemented here. Note that this calculation produces offsets for scattering metadata matrix elements into reordered metadata matrix elements (or, equivalently, for gathering reordered metadata matrix element back into metadata matrix elements). """ dst_rows = torch.arange(0, m, device=device)[:, None].repeat(1, meta_ncols) dst_cols = torch.arange(0, meta_ncols, device=device).repeat(m, 1)
# Reorder the rows, then swizzle the 2x2 blocks. group = 32 if meta_dtype.itemsize == 2 else 16 interweave = 4 if meta_dtype.itemsize == 2 else 2 dst_rows = ( dst_rows // group * group + (dst_rows % 8) * interweave + (dst_rows % group) // 8 )
topright = ((dst_rows % 2 == 0) & (dst_cols % 2 == 1)).to(torch.int8) bottomleft = ((dst_rows % 2 == 1) & (dst_cols % 2 == 0)).to(torch.int8) dst_rows += topright - bottomleft dst_cols -= topright - bottomleft
# Assumed that meta tensor is to be stored in CUTLASS # InterleavedColumnMajor layout, and reverse engineered # corresponding code to store values into this tensor. interleave = 2 cols_maj = dst_cols // interleave cols_min = dst_cols % interleave return (cols_maj * m * interleave + dst_rows * interleave + cols_min).view(-1)
def sparse_semi_structured_from_dense_cutlass(dense): """ This function converts dense matrix into sparse semi-structured representation, producing "compressed" matrix, in the layout used by CUTLASS backend, and corresponding metadata matrix. """ if dense.dim() != 2: raise RuntimeError( f"Expected 2-dimensional dense tensor, got {dense.dim()}-dimensional tensor" )
m, k = dense.shape device = dense.device
meta_dtype = torch.int8 if dense.dtype == torch.int8: meta_dtype = torch.int32 elif dense.dtype in [torch.half, torch.bfloat16, torch.float]: meta_dtype = torch.int16 else: raise RuntimeError(f"Invalid datatype {dense.dtype} of dense matrix") quadbits_per_meta_elem = meta_dtype.itemsize * 8 // 4 if quadbits_per_meta_elem not in (4, 8): raise RuntimeError("Invalid number of elements per meta element calculated")
if meta_dtype == torch.int32: if m % 16 != 0: raise RuntimeError( f"Number of rows of dense matrix {m} must be divisible by 16" ) else: if m % 32 != 0: raise RuntimeError( f"Number of rows of dense matrix {m} must be divisible by 32" ) if k % (4 * quadbits_per_meta_elem) != 0: raise RuntimeError( f"Number of columns of dense matrix {k} must be divisible by {4 * quadbits_per_meta_elem}" )
if dense.dtype != torch.float: ksparse = 4 dense_4 = dense.view(-1, k // ksparse, ksparse) m0, m1, _m2, m3 = (dense_4 != 0).unbind(-1) else: ksparse = 2 dense_2 = dense.view(-1, k // ksparse, ksparse) m0, _m2 = m1, m3 = (dense_2 != 0).unbind(-1) meta_ncols = k // (ksparse * quadbits_per_meta_elem)
# Encoding quadruples of True/False values as follows: # [True, True, False, False] -> 0b0100 # [True, False, True, False] -> 0b1000 # [False, True, True, False] -> 0b1001 # [True, False, False, True ] -> 0b1100 # [False, True, False, True ] -> 0b1101 # [False, False, True, True ] -> 0b1110 # Thus, lower two bits in the encoding are index of the True value # at the lowest index in the quadruple, and the higher two bits in # the encoding are index of the other True value in the quadruple. # In case there are less than two True values, than False value or # values at some index or indices are considered True for the # encoding. In case there are more than two True values, then the # excess True value(s) at some indices are considered False for # the encoding. The exact encodings used for these cases are as # follows: # [False, False, False, False] -> 0b1110 # [False, False, False, True ] -> 0b1110 # [False, False, True, False] -> 0b1110 # [False, True, False, False] -> 0b1001 # [False, True, True, True ] -> 0b1101 # [True, False, False, False] -> 0b1000 # [True, False, True, True ] -> 0b1100 # [True, True, False, True ] -> 0b0100 # [True, True, True, False] -> 0b0100 # [True, True, True, True ] -> 0b0100 # These particular encodings are chosen, with the help of Espresso # logic minimizer software, for the purpose of minimization of # corresponding Boolean functions, that translate non-zero flags # into encoding bits. Note also possible choices for the first # and last of these encodings were limited only to (0b0100, # 0b1110), in order to produce valid encodings for 1:2 sparsity # case.
expr0 = m0 & m1 expr1 = ~m0 & m1 expr2 = ~m0 & ~m1 bit0 = expr1 bit1 = expr2 bit2 = expr0 | expr2 | m3 bit3 = expr1 | ~m1 idxs0 = bit0 | (bit1.to(torch.int64) << 1) idxs1 = bit2 | (bit3.to(torch.int64) << 1)
if dense.dtype != torch.float: sparse0 = dense_4.gather(-1, idxs0.unsqueeze(-1)) # type: ignore[possibly-undefined] sparse1 = dense_4.gather(-1, idxs1.unsqueeze(-1)) sparse = torch.stack((sparse0, sparse1), dim=-1).view(m, k // 2) else: sparse = dense_2.gather(-1, idxs0.unsqueeze(-1) // 2).view(m, k // 2) # type: ignore[possibly-undefined]
meta_4 = idxs0 | (idxs1 << 2) meta_n = meta_4.view((-1, meta_ncols, quadbits_per_meta_elem)).to(meta_dtype)
if quadbits_per_meta_elem == 4: meta = ( meta_n[:, :, 0] | (meta_n[:, :, 1] << 4) | (meta_n[:, :, 2] << 8) | (meta_n[:, :, 3] << 12) ) elif quadbits_per_meta_elem == 8: meta = ( meta_n[:, :, 0] | (meta_n[:, :, 1] << 4) | (meta_n[:, :, 2] << 8) | (meta_n[:, :, 3] << 12) | (meta_n[:, :, 4] << 16) | (meta_n[:, :, 5] << 20) | (meta_n[:, :, 6] << 24) | (meta_n[:, :, 7] << 28) )
# Reorder meta tensor elements. meta_reordered = meta.new_empty((m * meta_ncols,)) # type: ignore[possibly-undefined] meta_offsets = _calculate_meta_reordering_scatter_offsets( m, meta_ncols, meta_dtype, device ) meta_reordered.scatter_(0, meta_offsets, meta.view(-1))
return (sparse, meta_reordered.view(m, meta_ncols))
def sparse_semi_structured_to_dense_cutlass(sparse, meta_reordered): """ This function performs reverse of the function above - it reconstructs dense matrix from a pair of "compressed" matrix, given in the layout used by CUTLASS backend, and accompanying metadata matrix. """ if sparse.dim() != 2: raise RuntimeError( f"Expected 2-dimensional sparse tensor, got {sparse.dim()}-dimensional tensor" )
m, k = sparse.shape device = sparse.device
if meta_reordered.dim() != 2: raise RuntimeError( f"Expected 2-dimensional meta tensor, got {meta_reordered.dim()}-dimensional tensor" ) if meta_reordered.device != device: raise RuntimeError( f"Expected meta matrix to be on {device} device, got matrix on {meta_reordered.device} device" )
meta_dtype = meta_reordered.dtype if meta_dtype not in (torch.int16, torch.int32): raise RuntimeError(f"Invalid datatype {meta_dtype} of meta matrix") quadbits_per_meta_elem = meta_dtype.itemsize * 8 // 4
if sparse.dtype != torch.float: ksparse = 4 else: ksparse = 2
meta_nrows, meta_ncols = meta_reordered.shape if meta_nrows != m: raise RuntimeError( f"Number of rows of meta matrix {meta_nrows} must be equal to number of columns of spase matrix {m}" ) if meta_ncols * ksparse * quadbits_per_meta_elem != 2 * k: raise RuntimeError( f"Number of columns of sparse matrix {k} different from the {meta_ncols * ksparse * quadbits_per_meta_elem // 2}, " "expected according to the number of columns of meta matrix" )
# Undo meta tensor elements reordering. meta_offsets = _calculate_meta_reordering_scatter_offsets( m, meta_ncols, meta_dtype, device ) meta = torch.gather(meta_reordered.view(-1), 0, meta_offsets).view(m, meta_ncols)
# Unpack sparse tensor back to original dense tensor, using # information provided by meta tensor. Note that torch.float # datatype is handled pretty much the same as # torch.half/torch.bfloat16, as metadata for a pair of torch.float # value is encoded as if underlying 8 bytes contain four # torch.half/torch.bfloat16 values, where either first two or last # two are zeros. meta_2 = torch.empty( (m, meta_ncols, 2 * quadbits_per_meta_elem), dtype=meta_dtype, device=device, ) if quadbits_per_meta_elem == 4: meta_2[:, :, 0] = meta & 0b11 meta_2[:, :, 1] = (meta >> 2) & 0b11 meta_2[:, :, 2] = (meta >> 4) & 0b11 meta_2[:, :, 3] = (meta >> 6) & 0b11 meta_2[:, :, 4] = (meta >> 8) & 0b11 meta_2[:, :, 5] = (meta >> 10) & 0b11 meta_2[:, :, 6] = (meta >> 12) & 0b11 meta_2[:, :, 7] = (meta >> 14) & 0b11 elif quadbits_per_meta_elem == 8: meta_2[:, :, 0] = meta & 0b11 meta_2[:, :, 1] = (meta >> 2) & 0b11 meta_2[:, :, 2] = (meta >> 4) & 0b11 meta_2[:, :, 3] = (meta >> 6) & 0b11 meta_2[:, :, 4] = (meta >> 8) & 0b11 meta_2[:, :, 5] = (meta >> 10) & 0b11 meta_2[:, :, 6] = (meta >> 12) & 0b11 meta_2[:, :, 7] = (meta >> 14) & 0b11 meta_2[:, :, 8] = (meta >> 16) & 0b11 meta_2[:, :, 9] = (meta >> 18) & 0b11 meta_2[:, :, 10] = (meta >> 20) & 0b11 meta_2[:, :, 11] = (meta >> 22) & 0b11 meta_2[:, :, 12] = (meta >> 24) & 0b11 meta_2[:, :, 13] = (meta >> 26) & 0b11 meta_2[:, :, 14] = (meta >> 28) & 0b11 meta_2[:, :, 15] = (meta >> 30) & 0b11
dense_offsets = meta_2.view(-1) + ( torch.arange(0, 2 * m * k // ksparse, device=device) * 4 ).view(-1, 1).repeat(1, 2).view(-1)
dense = torch.zeros((m * 2 * k,), dtype=sparse.dtype, device=device) if sparse.dtype != torch.float: dense.scatter_(0, dense_offsets, sparse.view(-1)) else: dense.view(torch.half).scatter_( 0, dense_offsets, sparse.view(torch.half).view(-1) )
return dense.view(m, 2 * k)
def _sparse_semi_structured_tile(dense): """ This function computes a 2:4 sparse tile by greedily taking the largest values.
Since we take the largest values greedily, how the sorting algorithm handles duplicates affects the ultimate sparsity pattern.
Note that this function does not have the same sorting semantics as our CUDA backend, which is exposed via `torch._sparse_semi_structured_tile` and thus returns a different pattern. """
def greedy_prune_tile(tile): num_kept_row = [0, 0, 0, 0] num_kept_col = [0, 0, 0, 0]
for x in tile.flatten().sort(descending=True, stable=True).indices: r, c = x // 4, x % 4 if num_kept_row[r] < 2 and num_kept_col[c] < 2: num_kept_row[r] += 1 num_kept_col[c] += 1 else: tile[r, c] = 0
for batch in dense.unfold(0, 4, 4).unfold(1, 4, 4): for tile in batch: greedy_prune_tile(tile)
return dense
def _compute_compressed_swizzled_bitmask(dense): """ Calculates the compressed swizzled bitmask from a dense tensor """
# first we need to convert the dense tensor to a bitmask int_bitmask = dense.bool().to(torch.uint8)
# Each thread is responsible for an 8x8 tile, which contains 4 4x4 tiles: # A, B, C and D, as displayed in the following schema: # +---+---+ # | A | B | # +---+---+ # | C | D | # +---+---+
# we first need to split into the 8x8 tiles bitmask_8x8_chunks = int_bitmask.unfold(0, 8, 8).unfold(1, 8, 8)
# then we unfold again to get our individual 4x4 tiles bitmask_4x4_chunks = bitmask_8x8_chunks.unfold(2, 4, 4).unfold(3, 4, 4)
# Each 4x4 bitmask defines two 8-bit integers, which encode the sparsity pattern # of that tile. Note that the least significant bit is stored first. # [1 1 0 0] # [1 1 0 0] -> 0011 0011 -> 51 # [0 0 1 1] 1100 1100 204 # [0 0 1 1]
# reshape tensor to expand tiles into 8-bit vectors bitmask_binary_representation = bitmask_4x4_chunks.reshape( *bitmask_4x4_chunks.shape[:2], 4, 2, 8 )
# to convert from binary representation, we can do a matmul with powers of two powers_of_two = 2 ** torch.arange(8, dtype=torch.float, device="cuda") # To run on GPU: cast to float to do matmul and then cast back compressed_swizzled_bitmask = ( bitmask_binary_representation.to(torch.float) @ powers_of_two ).to(torch.uint8)
return compressed_swizzled_bitmask123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197# mypy: allow-untyped-defsimport contextlib
import torch
__all__ = [ "fallback_dispatcher", "semi_sparse_values", "semi_sparse_indices", "semi_sparse_t", "semi_sparse_view", "semi_sparse_detach", "semi_sparse_mm", "semi_sparse_addmm", "semi_sparse_linear", "semi_sparse_scaled_mm",]
@contextlib.contextmanagerdef no_dispatch(): guard = torch._C._DisableTorchDispatch() try: yield finally: del guard
def fallback_dispatcher(func, types, args, kwargs): with no_dispatch(): return func(*args)
def semi_sparse_values(func, types, args=(), kwargs=None) -> torch.Tensor: assert len(args) == 1 A = args[0] assert isinstance(A, torch.sparse.SparseSemiStructuredTensor) assert A.packed is not None if A.meta is None: m, k = A.shape num_kept_elements = m * k // 2 return A.packed[:num_kept_elements:].view(m, -1) else: return A.packed.detach()
def semi_sparse_indices(func, types, args=(), kwargs=None) -> torch.Tensor: assert len(args) == 1 A = args[0] assert isinstance(A, torch.sparse.SparseSemiStructuredTensor) assert A.packed is not None if A.meta is None: m, k = A.shape num_kept_elements = m * k // 2 metadata = A.packed[num_kept_elements:].view(m, -1) return metadata.view(torch.int32 if A.dtype == torch.int32 else torch.int16) else: return A.meta
def semi_sparse_t(func, types, args=(), kwargs=None) -> torch.Tensor: assert len(args) == 1 self = args[0] assert isinstance(self, torch.sparse.SparseSemiStructuredTensor) assert len(self.shape) == 2 # Because we cannot go from the compressed representation back to the dense representation currently, # we just keep track of how many times we have been transposed. Depending on whether the sparse matrix # is the first or second argument, we expect an even / odd number of calls to transpose respectively. return self.__class__( torch.Size([self.shape[-1], self.shape[0]]), packed=self.packed_t, meta=self.meta_t, packed_t=self.packed, meta_t=self.meta, compressed_swizzled_bitmask=( self.compressed_swizzled_bitmask.transpose(0, 1) if self.compressed_swizzled_bitmask is not None else None ), fuse_transpose_cusparselt=args[0].fuse_transpose_cusparselt, alg_id_cusparselt=args[0].alg_id_cusparselt, )
def semi_sparse_view(func, types, args=(), kwargs=None) -> torch.Tensor: assert len(args) == 2 self, shape = args if tuple(shape) != self.shape: raise NotImplementedError( f"`view` is not implemented for SparseSemiStructuredTensor, except for the dummy case (shape={shape})" ) return self
def semi_sparse_detach(func, types, args, kwargs) -> torch.Tensor: assert len(args) == 1 self = args[0] return self.__class__( shape=self.shape, packed=self.packed, meta=self.meta, packed_t=self.packed_t, meta_t=self.meta_t, compressed_swizzled_bitmask=self.compressed_swizzled_bitmask, fuse_transpose_cusparselt=self.fuse_transpose_cusparselt, alg_id_cusparselt=self.alg_id_cusparselt, requires_grad=False, )
def semi_sparse_mm(func, types, args=(), kwargs=None) -> torch.Tensor: assert len(args) == 2 A, B = args if A.ndim != 2 or B.ndim != 2: raise NotImplementedError( "`SparseSemiStructuredTensor` matmul: Broadcasting is not implemented" ) if isinstance(A, torch.sparse.SparseSemiStructuredTensor): row, col = B.shape B_padded = A._pad_dense_input(B) res = A._mm(B_padded) return res[:, :col] else: B_t = B.t() assert isinstance(B_t, torch.sparse.SparseSemiStructuredTensor) row, col = A.shape A_padded = B._pad_dense_input(A) res = B_t._mm(A_padded.t()).t() return res[:row, :]
def semi_sparse_addmm(func, types, args=(), kwargs=None) -> torch.Tensor: assert len(args) == 3 bias, A, B = args if A.ndim != 2 or B.ndim != 2: raise NotImplementedError( "`SparseSemiStructuredTensor` matmul: Broadcasting is not implemented" ) if bias.ndim != 1: raise NotImplementedError( f"`SparseSemiStructuredTensor` matmul: only bias dim=1 supported. Shape={bias.shape}" ) if isinstance(A, torch.sparse.SparseSemiStructuredTensor): raise NotImplementedError( "`SparseSemiStructuredTensor` matmul: only operand B of `addmm` can be sparse" ) B_t = B.t() assert isinstance(B_t, torch.sparse.SparseSemiStructuredTensor) row, _col = A.shape A_padded = B_t._pad_dense_input(A) result = B_t._mm(A_padded.t(), bias=bias).t() return result[:row, :]
def semi_sparse_linear(func, types, args=(), kwargs=None) -> torch.Tensor: assert len(args) in [2, 3] A, B = args[:2] bias = args[2] if len(args) == 3 else None
shape = A.shape A_2d = A.view(-1, shape[-1])
if bias is None: res = A_2d @ B.t() else: res = semi_sparse_addmm( func=None, types=None, args=[bias, A_2d, B.t()], )
return res.view(*shape[:-1], -1)
def semi_sparse_scaled_mm(func, types, args=(), kwargs=None) -> torch.Tensor: # pull all args, excluding use_fast_accum flag if set. A, B, A_scale, B_scale, bias, scale_result, out_dtype = args[:7]
assert A.dtype == torch.float8_e4m3fn assert B.dtype == torch.float8_e4m3fn # only cuSPARSELt supports float8_e4m3fn currently assert isinstance(A, torch.sparse.SparseSemiStructuredTensorCUSPARSELT) assert A.packed is not None # Currently we only support per-tensor scaling, with float32 scales assert A_scale.numel() == 1 and B_scale.numel() == 1 assert A_scale.dtype == torch.float32 and B_scale.dtype == torch.float32
# cuSPARSELt lacks the A and B operand scaling support, so instead we use alpha to scale the result. # Note that this limits us to per-tensor scalig only. sparse_result = torch._cslt_sparse_mm( A.packed, B, alpha=A_scale * B_scale, out_dtype=out_dtype, ) return sparse_result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529# mypy: allow-untyped-decorators# mypy: allow-untyped-defsimport mathimport osimport weakreffrom functools import lru_cachefrom typing import Optional
import torchfrom torch._dynamo.utils import warn_oncefrom torch.utils._triton import has_triton
from ._triton_ops_meta import get_meta
TORCH_SPARSE_BSR_SCATTER_MM_LRU_CACHE_SIZE = int( os.getenv("TORCH_SPARSE_BSR_SCATTER_MM_LRU_CACHE_SIZE", 2))
def check(cond, msg): if not cond: raise ValueError(msg)
def check_bsr_layout(f_name, t): check( t.layout == torch.sparse_bsr, f"{f_name}(): only BSR sparse format is supported for the sparse argument.", )
def check_device(f_name, t, device): check( t.device == device and t.device.type == "cuda", f"{f_name}(): all inputs are expected to be on the same GPU device.", )
def check_mm_compatible_shapes(f_name, lhs, rhs): check( lhs.dim() >= 2 and rhs.dim() >= 2, f"{f_name}(): all inputs involved in the matrix product are expected to be at least 2D, " f"but got lhs.dim() == {lhs.dim()} and rhs.dim() == {rhs.dim()}.", )
_m, kl = lhs.shape[-2:] kr, _n = rhs.shape[-2:]
check( kl == kr, f"{f_name}(): arguments' sizes involved in the matrix product are not compatible for matrix multiplication, " f"got lhs.shape[-1] == {kl} which is not equal to rhs.shape[-2] == {kr}.", )
def check_dtype(f_name, t, dtype, *additional_dtypes): check( t.dtype == dtype and t.dtype in ((torch.half, torch.bfloat16, torch.float) + tuple(*additional_dtypes)), f"{f_name}(): all inputs are expected to be of the same dtype " f"and one of (half, bfloat16, float32) or {additional_dtypes}, " f"but got dtype == {t.dtype}.", )
def check_blocksize(f_name, blocksize): assert len(blocksize) == 2
def is_power_of_two(v): return not (v & (v - 1))
def is_compatible_blocksize(b): res = True for blocksize in b: # Triton loads only blocks which are at least 16 and powers of 2. res = (blocksize >= 16 and is_power_of_two(blocksize)) and res return res
check( is_compatible_blocksize(blocksize), f"{f_name}(): sparse inputs' blocksize ({blocksize[0]}, {blocksize[1]}) " "should be at least 16 and a power of 2 in each dimension.", )
def make_triton_contiguous(t): """Return input as a triton-contiguous tensor.
A triton-contiguous tensor is defined as a tensor that has strides with minimal value smaller than or equal to 1.
While triton kernels support triton-non-contiguous tensors (all strides being greater than 1) arguments, a considerable slow-down occurs because tensor data is copied element-wise rather than chunk-wise. Zero strides is assumed to not have this defect. """ if min(t.stride()) > 1: # TODO: investigate if contiguity along other axes than the # last one can be beneficial for performance return t.contiguous() else: return t
def broadcast_batch_dims(f_name, *tensors): try: return torch.broadcast_shapes(*(t.shape[:-2] for t in tensors)) except Exception: check(False, f"{f_name}(): inputs' batch dimensions are not broadcastable!")
def slicer(dim, slice_range, *tensors): for t in tensors: slices = [slice(None)] * t.dim() slices[dim] = slice_range yield t[slices]
def multidim_slicer(dims, slices, *tensors): for t in tensors: s = [slice(None)] * t.dim() for d, d_slice in zip(dims, slices): if d is not None: s[d] = d_slice yield t[tuple(s)]
def ptr_stride_extractor(*tensors): for t in tensors: yield t yield from t.stride()
def grid_partitioner(full_grid, grid_blocks, tensor_dims_map): assert 0 <= len(full_grid) <= 3 assert 0 <= len(grid_blocks) <= 3
import itertools
def generate_grid_points(): for fg, mg in zip(full_grid, grid_blocks): yield range(0, fg, mg)
def generate_sliced_tensors(slices): for t, t_dims in tensor_dims_map.items(): yield next(multidim_slicer(t_dims, slices, t))
for grid_point in itertools.product(*generate_grid_points()): grid = [ min(fg - gp, mg) for fg, gp, mg in zip(full_grid, grid_point, grid_blocks) ] slices = [slice(gp, gp + g) for gp, g in zip(grid_point, grid)] # grid_points are iterated in a "contiguous" order, i.e. # left dimensions traversed slower than right dimensions. # This order is reversed for CUDA grids. yield grid[::-1], *generate_sliced_tensors(slices)
def launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks=None): # cuda_max_grid = (2 ** 31 - 1, 2 ** 16 - 1, 2 ** 16 - 1) cuda_max_grid = (2147483647, 65535, 65535)[::-1] if grid_blocks is None: grid_blocks = cuda_max_grid else:
def valid_grid_dim(g, mg): if g is None: return mg else: # grid must be at least 1 and no greater than mg return max(1, min(g, mg))
grid_blocks = tuple( valid_grid_dim(g, mg) for g, mg in zip(grid_blocks, cuda_max_grid) ) # type: ignore[assignment]
for grid, *sliced_tensors in grid_partitioner( full_grid, grid_blocks, tensor_dims_map ): kernel(grid, *sliced_tensors)
def prepare_inputs(bsr, *dense_tensors): # Introduce fake batch dimension if not present for convenience. crow_indices = bsr.crow_indices().unsqueeze(0) col_indices = bsr.col_indices().unsqueeze(0) values = make_triton_contiguous(bsr.values().unsqueeze(0)) tensors = [make_triton_contiguous(t.unsqueeze(0)) for t in dense_tensors]
# Compute broadcasted batch dimension batch_dims_broadcasted = torch.broadcast_shapes( values.shape[:-3], *(t.shape[:-2] for t in tensors) )
# Broadcast batch dimensions and squash. # The result can be either a view or a copy. def batch_broadcast_and_squash(t, batch_dims, invariant_dims): return t.broadcast_to(batch_dims + invariant_dims).flatten( 0, len(batch_dims) - 1 )
crow_indices = batch_broadcast_and_squash( crow_indices, batch_dims_broadcasted, (-1,) )
col_indices = batch_broadcast_and_squash(col_indices, batch_dims_broadcasted, (-1,)) values = batch_broadcast_and_squash( values, batch_dims_broadcasted, values.shape[-3:] ) tensors = [ batch_broadcast_and_squash(t, batch_dims_broadcasted, t.shape[-2:]) for t in tensors ]
return crow_indices, col_indices, values, *tensors
def broadcast_batch_dims_bsr(f_name, bsr, *tensors): batch_shape = broadcast_batch_dims(f_name, bsr, *tensors)
crow_indices = bsr.crow_indices().broadcast_to(batch_shape + (-1,)) col_indices = bsr.col_indices().broadcast_to(batch_shape + (-1,)) values = bsr.values().broadcast_to(batch_shape + bsr.values().shape[-3:]) size = batch_shape + bsr.shape[-2:] return torch.sparse_compressed_tensor( crow_indices, col_indices, values, size=size, layout=bsr.layout )
# NOTE: this function will ALWAYS create a viewdef tile_to_blocksize(t, blocksize): *rest, m, n = t.shape new_shape = rest + [ m // blocksize[0], blocksize[0], n // blocksize[1], blocksize[1], ] # using .view instead of .reshape to ensure that the result is # indeed a view: return t.view(new_shape).transpose(-3, -2)
def as1Dbatch(tensor): """Return tensor as 3D tensor by either prepending new dimensions to the tensor shape (when ``tensor.ndim < 3``), or by collapsing starting dimensions into the first dimension (when ``tensor.ndim > 3``). """ while tensor.ndim < 3: tensor = tensor.unsqueeze(0) if tensor.ndim > 3: tensor = tensor.flatten(0, tensor.ndim - 3) assert tensor.ndim == 3, tensor.shape return tensor
def scatter_mm(blocks, others, indices_data, *, accumulators=None): """Scattered matrix multiplication of tensors.
A scattered matrix multiplication is defined as a series of matrix multiplications applied to input tensors according to the input and output mappings specified by indices data.
The following indices data formats are supported for defining a scattered matrix multiplication operation (:attr:`indices_data[0]` holds the name of the indices data format as specified below):
- ``"scatter_mm"`` - matrix multiplications scattered in batches of tensors.
If :attr:`blocks` is a :math:`(* \times M \times K) tensor, :attr:`others` is a :math:`(* \times K \times N)` tensor, :attr:`accumulators` is a :math:`(* \times M \times N)` tensor, and :attr:`indices = indices_data['indices']` is a :math:`(* \times 3)` tensor, then the operation is equivalent to the following code::
c_offsets, pq = indices_data[1:] for r in range(len(c_offsets) - 1): for g in range(c_offsets[r], c_offsets[r + 1]): p, q = pq[g] accumulators[r] += blocks[p] @ others[q]
- ``"bsr_strided_mm"`` - matrix multiplications scattered in batches of tensors and a tensor.
If :attr:`blocks` is a :math:`(Ms \times Ks) tensor, :attr:`others` is a :math:`(* \times K \times N)` tensor, :attr:`accumulators` is a :math:`(* \times M \times N)` tensor, then the operation is equivalent to the following code::
c_indices, r_offsets, p_offsets, q_offsets, meta = indices_data[1:] for b in range(nbatches): for i, r in enumerate(r_offsets): r0, r1 = divmod(r, N) acc = accumulators[b, r0:r0 + Ms, r1:r1 + Ns] for g in range(c_indices[i], c_indices[i+1]): p = p_offsets[g] q0, q1 = divmod(q_offsets[g], N) acc += blocks[p] @ others[b, q0:q0 + Ks, q1:q1 + Ns]
where ``Ns = N // meta['SPLIT_N']``, and ``M`` and ``K`` are integer multiples of ``Ms`` and ``Ks``, respectively.
- ``"bsr_strided_mm_compressed"`` - matrix multiplications scattered in batches of tensors and a tensor. A memory and processor efficient version of ``"bsr_strided_mm"`` format. If :attr:`blocks` is a :math:`(Ms \times Ks) tensor, :attr:`others` is a :math:`(* \times K \times N)` tensor, :attr:`accumulators` is a :math:`(* \times M \times N)` tensor, then the operation is equivalent to the following code::
c_indices, r_offsets, q_offsets, meta = indices_data[1:] for b in range(nbatches): for r in r_offsets: m = (r // N) // Ms n = (r % N) // Ns r0, r1 = divmod(r, N) c0, c1 = c_indices[m], c_indices[m + 1] acc = accumulators[b, r0:r0 + Ms, r1:r1 + Ns] for i, p in enumerate(range(c0, c1)): q = q_offsets[n * c1 + (SPLIT_N - n) * c0 + i] q0, q1 = divmod(q, N) acc += blocks[p] @ others[b, q0:q0 + Ks, q1:q1 + Ns]
where ``Ns = N // meta['SPLIT_N']``, and ``M`` and ``K`` are integer multiples of ``Ms`` and ``Ks``, respectively.
Notice that the order of ``r_offsets`` items can be arbitrary; this property enables defining swizzle operators via rearrangements of ``r_offsets`` items..
Auxiliary functions are provided for pre-computing :attr:`indices_data`. For example, :func:`bsr_scatter_mm_indices_data` is used to define indices data for matrix multiplication of BSR and strided tensors.
Parameters ---------- blocks (Tensor): a 3-D tensor of first matrices to be multiplied
others (Tensor): a tensor of second matrices to be multiplied. If ``indices_data[0]=="scatter_mm"``, the tensor is a 1-D batch tensor of second input matrices to be multiplied. Otherwise, the second input matrices are slices of the :attr:`others` tensor. indices_data (tuple): a format data that defines the inputs and outputs of scattered matrix multiplications.
Keyword arguments -----------------
accumulators (Tensor, optional): a tensor of matrix product accumulators. If ``indices_data[0]=="scatter_mm"``, the tensor is a 1-D batch tensor of output matrices. Otherwise, output matrices are slices of the :attr:`accumulators` tensor. """ indices_format = indices_data[0]
assert blocks.ndim == 3 _P, Ms, Ks = blocks.shape
if indices_format == "scatter_mm": c_offsets, pq = indices_data[1:]
assert others.ndim == 3 _Q, Ks_, Ns = others.shape assert Ks == Ks_
if accumulators is None: R = c_offsets.shape[0] - 1 accumulators = torch.zeros( (R, Ms, Ns), dtype=blocks.dtype, device=blocks.device ) else: R, Ms_, Ns_ = accumulators.shape assert Ms_ == Ms assert Ns_ == Ns
if Ms % 16 or Ks % 16 or Ns % 16 or _scatter_mm2 is None: for r in range(c_offsets.shape[0] - 1): g0 = c_offsets[r] g1 = c_offsets[r + 1] for g in range(g0, g1): p, q = pq[g] accumulators[r] += blocks[p] @ others[q] else: _scatter_mm2(blocks, others, c_offsets, pq, accumulators) return accumulators
elif indices_format == "bsr_strided_mm": others_shape = others.shape others = as1Dbatch(others)
B, K, N = others.shape assert K % Ks == 0
c_indices, r_offsets, p_offsets, q_offsets, meta = indices_data[1:] SPLIT_N = meta["SPLIT_N"]
if accumulators is None: M = Ms + (r_offsets.max().item() + 1) // N accumulators = torch.zeros( (*others_shape[:-2], M, N), dtype=blocks.dtype, device=blocks.device ) else: M, N_ = accumulators.shape[-2:] assert N_ == N
accumulators_shape = accumulators.shape accumulators = as1Dbatch(accumulators)
Ns = N // SPLIT_N
if Ms % 16 or Ks % 16 or Ns % 16 or _scatter_mm6 is None: accumulators.zero_() for b in range(B): for r in range(r_offsets.shape[0]): r_ = r_offsets[r].item() g0 = c_indices[r].item() g1 = c_indices[r + 1].item() r0, r1 = divmod(r_, N) acc = accumulators[b, r0 : r0 + Ms, r1 : r1 + Ns] for g in range(g0, g1): p, q = p_offsets[g], q_offsets[g] q0, q1 = divmod(q.item(), N) acc += blocks[p] @ others[b, q0 : q0 + Ks, q1 : q1 + Ns] else: _scatter_mm6( blocks, others, c_indices, r_offsets, p_offsets, q_offsets, meta, accumulators, ) return accumulators.view(accumulators_shape)
elif indices_format == "bsr_strided_mm_compressed": others_shape = others.shape others = as1Dbatch(others)
B, K, N = others.shape assert K % Ks == 0
c_indices, r_offsets, q_offsets, meta = indices_data[1:] SPLIT_N = meta["SPLIT_N"]
if accumulators is None: M = Ms + (r_offsets.max().item() + 1) // N accumulators = torch.zeros( (*others_shape[:-2], M, N), dtype=blocks.dtype, device=blocks.device ) else: M, N_ = accumulators.shape[-2:] assert N_ == N
accumulators_shape = accumulators.shape accumulators = as1Dbatch(accumulators)
Ns = N // SPLIT_N
if Ms % 16 or Ks % 16 or Ns % 16 or _scatter_mm6 is None: for b in range(B): for j in range(len(r_offsets)): r0, r1 = divmod(r_offsets[j].item(), N) m = r0 // Ms n = r1 // Ns c0 = c_indices[m].item() c1 = c_indices[m + 1].item() acc = accumulators[b, r0 : r0 + Ms, r1 : r1 + Ns] for i, p in enumerate(range(c0, c1)): q = q_offsets[n * c1 + (SPLIT_N - n) * c0 + i].item() q0, q1 = divmod(q, N) acc += blocks[p] @ others[b, q0 : q0 + Ks, q1 : q1 + Ns] else: p_offsets = torch.empty( (0,), dtype=q_offsets.dtype, device=q_offsets.device ) _scatter_mm6( blocks, others, c_indices, r_offsets, p_offsets, q_offsets, meta, accumulators, ) return accumulators.view(accumulators_shape)
else: raise NotImplementedError(indices_format)
def scatter_mm_meta( M, K, N, Ms, Ks, GROUP_SIZE=None, TILE_M=None, TILE_N=None, SPLIT_N=None, num_warps=None, num_stages=None, **extra,): if {TILE_M, TILE_N, SPLIT_N, num_warps, num_stages, GROUP_SIZE} == {None}: device_name = torch.cuda.get_device_name() meta = get_meta( "scatter_mm", (M, K, N, Ms, Ks), device_name, version=(0, torch.float16, 0.5), ) if meta is not None: meta.update(**extra) return meta # The following parameters are optimized for the performance # equilibrium points of bsr-dense and dense-dense matrix # multiplications when using GPU card NVIDIA GeForce RTX 2060 # SUPER. For points far from the performance equilibrium # points as well as for other GPU cards, the optimal # parameters are likely different from what specified below. if (M, K, N) == (256,) * 3: if (Ms, Ks) == (16, 16): SPLIT_N = 1 TILE_M = 16 TILE_N = 16 GROUP_SIZE = 4 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702 elif (Ms, Ks) == (32, 32): SPLIT_N = 2 TILE_M = 32 TILE_N = 16 GROUP_SIZE = 4 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702 elif (Ms, Ks) == (64, 64): SPLIT_N = 1 TILE_M = 32 TILE_N = 32 GROUP_SIZE = 4 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702 elif (Ms, Ks) == (128, 128): SPLIT_N = 1 TILE_M = 32 TILE_N = 32 GROUP_SIZE = 2 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702 elif (M, K, N) == (512,) * 3: if (Ms, Ks) == (16, 16): SPLIT_N = 8 TILE_M = 16 TILE_N = 64 GROUP_SIZE = 2 num_stages = 1 num_warps = 2 # noqa: E225,E231,E702 elif (Ms, Ks) == (32, 32): SPLIT_N = 8 TILE_M = 32 TILE_N = 64 GROUP_SIZE = 4 num_stages = 1 num_warps = 2 # noqa: E225,E231,E702 elif (Ms, Ks) == (64, 64): SPLIT_N = 4 TILE_M = 32 TILE_N = 128 GROUP_SIZE = 4 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702 elif (Ms, Ks) == (128, 128): SPLIT_N = 8 TILE_M = 64 TILE_N = 64 GROUP_SIZE = 4 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702 elif (M, K, N) == (1024,) * 3: if (Ms, Ks) == (16, 16): SPLIT_N = 4 TILE_M = 16 TILE_N = 128 GROUP_SIZE = 2 num_stages = 1 num_warps = 1 # noqa: E225,E231,E702 elif (Ms, Ks) == (32, 32): SPLIT_N = 8 TILE_M = 32 TILE_N = 64 GROUP_SIZE = 2 num_stages = 1 num_warps = 1 # noqa: E225,E231,E702 elif (Ms, Ks) == (64, 64): SPLIT_N = 16 TILE_M = 64 TILE_N = 64 GROUP_SIZE = 4 num_stages = 1 num_warps = 2 # noqa: E225,E231,E702 elif (Ms, Ks) == (128, 128): SPLIT_N = 16 TILE_M = 64 TILE_N = 64 GROUP_SIZE = 4 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702 elif (Ms, Ks) == (256, 256): SPLIT_N = 16 TILE_M = 64 TILE_N = 64 GROUP_SIZE = 2 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702 elif (M, K, N) == (2048,) * 3: if (Ms, Ks) == (16, 16): SPLIT_N = 4 TILE_M = 16 TILE_N = 128 GROUP_SIZE = 8 num_stages = 1 num_warps = 1 # noqa: E225,E231,E702 elif (Ms, Ks) == (32, 32): SPLIT_N = 4 TILE_M = 32 TILE_N = 64 GROUP_SIZE = 4 num_stages = 1 num_warps = 1 # noqa: E225,E231,E702 elif (Ms, Ks) == (64, 64): SPLIT_N = 4 TILE_M = 64 TILE_N = 128 GROUP_SIZE = 4 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702 elif (Ms, Ks) == (128, 128): SPLIT_N = 8 TILE_M = 64 TILE_N = 64 GROUP_SIZE = 4 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702 elif (Ms, Ks) == (256, 256): SPLIT_N = 4 TILE_M = 64 TILE_N = 64 GROUP_SIZE = 2 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702 elif (M, K, N) == (4096,) * 3: if (Ms, Ks) == (16, 16): SPLIT_N = 2 TILE_M = 16 TILE_N = 256 GROUP_SIZE = 2 num_stages = 1 num_warps = 2 # noqa: E225,E231,E702 elif (Ms, Ks) == (32, 32): SPLIT_N = 2 TILE_M = 32 TILE_N = 64 GROUP_SIZE = 2 num_stages = 1 num_warps = 1 # noqa: E225,E231,E702 elif (Ms, Ks) == (64, 64): SPLIT_N = 2 TILE_M = 64 TILE_N = 128 GROUP_SIZE = 2 num_stages = 1 num_warps = 4 # noqa: E225,E231,E702
if SPLIT_N is None: # Assume NVIDIA GeForce RTX 2060 SUPER: # With the probality of 92% (99.9% when N > 512), the # performance will not be worse more than 2% from the # performance when using an optimal value. Otherwise, when N # <= 512, using the following heuristics may give upto 15% # lower performance. SPLIT_N = { 16: 1, 32: 2, 64: 4, 128: 8, 256: 16, 512: 8, 1024: 16, 4096: 32, 8192: 64, }.get(N, 16) if Ms >= 512 and N >= 2048: SPLIT_N = 1 Ns = N // SPLIT_N if TILE_M is None: TILE_M = min(64 if Ns < 512 else 32, Ms) if TILE_N is None: TILE_N = min(64 if Ns < 512 else 32, Ns) num_stages = num_stages or 1 if num_warps is None: if min(M, N) > 1024: num_warps = {16: 1, 32: 1, 64: 2}.get(Ms, 4) elif min(M, N) == 1024: num_warps = {16: 1, 32: 1, 64: 2}.get(Ms, 4) elif min(M, N) == 256: num_warps = {16: 1, 32: 4}.get(Ms, 4) else: num_warps = {16: 1, 32: 2}.get(Ms, 4) GROUP_SIZE = GROUP_SIZE or 4
assert TILE_M <= Ms, dict(TILE_M=TILE_M, Ms=Ms) assert TILE_N <= Ns, dict(TILE_N=TILE_N, Ns=Ns) assert Ms <= M, dict(M=M, Ms=Ms) assert Ns <= N, dict(N=N, Ns=Ns) assert Ks <= K, dict(K=K, Ks=Ks)
return dict( TILE_M=TILE_M, TILE_N=TILE_N, GROUP_SIZE=GROUP_SIZE, num_stages=num_stages, num_warps=num_warps, SPLIT_N=SPLIT_N, **extra, )
def bsr_dense_addmm_meta( M, K, N, Ms, Ks, beta, alpha, SPLIT_N=None, GROUP_SIZE_ROW=None, num_warps=None, num_stages=None, sparsity=None, dtype=None, out_dtype=None, _version=0, **extra,): # Specifying _version is useful for situations when one wants to # discard existing triton kernel tuning results, say, in testing # bsr_dense_addmm_meta functionality. if dtype is None: dtype = torch.float16 if out_dtype is None: out_dtype = dtype if sparsity is None: sparsity = 0.5 if {SPLIT_N, num_warps, num_stages, GROUP_SIZE_ROW} == {None}: device_name = torch.cuda.get_device_name() key = (M, K, N, Ms, Ks, beta == 0, beta == 1, alpha == 1) if dtype is out_dtype: version_dtype = dtype else: version_dtype = dtype, out_dtype meta = get_meta( "bsr_dense_addmm", key, device_name, version=(_version, version_dtype, sparsity), ) if meta is None and sparsity != 0.5: meta = get_meta( "bsr_dense_addmm", key, device_name, version=(_version, version_dtype, 0.5), ) if meta is None and dtype is not out_dtype: meta = get_meta( "bsr_dense_addmm", key, device_name, version=(_version, dtype, 0.5) ) if meta is None: # find approximate meta such that N % SPLIT_N == 0. matching_meta = get_meta( "bsr_dense_addmm", (*key[:2], "*", *key[3:]), device_name, version=(_version, version_dtype, 0.5), ) if matching_meta is None and dtype is not out_dtype: matching_meta = get_meta( "bsr_dense_addmm", (*key[:2], "*", *key[3:]), device_name, version=(_version, dtype, 0.5), ) for mkey in sorted(matching_meta or {}): meta_ = matching_meta[mkey] n = mkey[2] split_n = meta_["SPLIT_N"] c = n // split_n if N % c == 0 and n <= N: meta = dict(meta_) meta["SPLIT_N"] = N // c if meta is not None: meta.update(**extra) return meta else: # see [Computing optimal kernel parameters] in # _triton_ops_meta.py for ways to avoid this warning # message warn_once( "bsr_dense_addmm uses non-optimal triton kernel parameters" f" for {M=} {K=} {N=} {Ms=}, {Ks=} {beta=} {alpha=} {dtype=} {out_dtype=}" )
SPLIT_N = SPLIT_N or max(N // Ms, 1) GROUP_SIZE_ROW = GROUP_SIZE_ROW or 4 num_stages = num_stages or 1 num_warps = num_warps or 4 return dict( SPLIT_N=SPLIT_N, GROUP_SIZE_ROW=GROUP_SIZE_ROW, num_stages=num_stages, num_warps=num_warps, **extra, )
class TensorAsKey: """A light-weight wrapper of a tensor that enables storing tensors as keys with efficient memory reference based comparison as an approximation to data equality based keys.
Motivation: the hash value of a torch tensor is tensor instance based that does not use data equality and makes the usage of tensors as keys less useful. For instance, the result of ``len({a.crow_indices(), a.crow_indices()})`` is `2`, although, the tensor results from `crow_indices` method call are equal, in fact, these share the same data storage. On the other hand, for efficient caching of tensors we want to avoid calling torch.equal that compares tensors item-wise.
TensorAsKey offers a compromise in that it guarantees key equality of tensors that references data in the same storage in the same manner and without accessing underlying data. However, this approach does not always guarantee correctness. For instance, for a complex tensor ``x``, we have ``TensorAsKey(x) == TensorAsKey(x.conj())`` while ``torch.equal(x, x.conj())`` would return False. """
def __init__(self, obj): def get_tensor_key(obj): # Warning: TensorAsKey does not track negative nor # conjugate bits of its input object because in the use # case of wrapping compressed/plain indices of compressed # sparse tensors (that are always integer tensors with # non-negative items) these bits are never set. However, # when extending the use of TensorAsKey to float or # complex tensors, the values of these bits (see is_neg # and is_conj methods) must be included in the key as # well. assert not (obj.dtype.is_floating_point or obj.dtype.is_complex), obj.dtype return ( obj.data_ptr(), obj.storage_offset(), obj.shape, obj.stride(), obj.dtype, )
self._obj_ref = weakref.ref(obj) if obj.layout is torch.strided: self.key = get_tensor_key(obj) elif obj.layout in {torch.sparse_csr, torch.sparse_bsr}: self.key = ( get_tensor_key(obj.crow_indices()), get_tensor_key(obj.col_indices()), ) elif obj.layout in {torch.sparse_csc, torch.sparse_bsc}: self.key = ( get_tensor_key(obj.ccol_indices()), get_tensor_key(obj.row_indices()), ) else: raise NotImplementedError(obj.layout) self._hash = hash(self.key)
def __hash__(self): return self._hash
def __eq__(self, other): if not isinstance(other, TensorAsKey): return False if self.obj is None or other.obj is None: # dead objects always compare unequal unless these are # same objects return self is other return self.key == other.key
@property def obj(self): """Return object if alive, otherwise None.""" return self._obj_ref()
@lru_cache(maxsize=TORCH_SPARSE_BSR_SCATTER_MM_LRU_CACHE_SIZE)def _bsr_scatter_mm_indices_data( indices_format, M, K, N, Ms, Ks, nbatches, SPLIT_N, compressed_sparse_tensor_as_key): bsr = compressed_sparse_tensor_as_key.obj assert bsr is not None crow_indices, col_indices = bsr.crow_indices(), bsr.col_indices() device = crow_indices.device indices_dtype = torch.int32
if indices_format == "bsr_strided_mm_compressed": Ns = N // SPLIT_N q_offsets_lst = [] b = torch.arange(SPLIT_N, dtype=indices_dtype, device=device) * Ns for m in range(M // Ms): r0 = crow_indices[m].item() r1 = crow_indices[m + 1].item() if r1 == r0: continue q_offsets_lst.append( (col_indices[r0:r1] * (Ks * N)).repeat(SPLIT_N) + b.repeat_interleave(r1 - r0) ) q_offsets = torch.cat(q_offsets_lst) crow_indices_diff = crow_indices.diff() non_zero_row_indices = crow_indices_diff.nonzero() a = non_zero_row_indices * (Ms * N) r_offsets = (a + b).view(-1) c_indices = crow_indices # swizzle operation: mm elements with longer sums are computed first: nnz_per_row = crow_indices_diff[non_zero_row_indices].repeat_interleave(SPLIT_N) nnz_per_row, indices = nnz_per_row.sort(descending=True, stable=True) r_offsets = r_offsets[indices] return (indices_format, c_indices, r_offsets, q_offsets)
elif indices_format == "bsr_strided_mm": Ns = N // SPLIT_N p_offsets_lst = [] q_offsets_lst = [] b = torch.arange(SPLIT_N, dtype=indices_dtype, device=device) * Ns for m in range(M // Ms): r0 = crow_indices[m].item() r1 = crow_indices[m + 1].item() if r1 == r0: continue p_offsets_lst.append( torch.arange(r0, r1, dtype=indices_dtype, device=device).repeat(SPLIT_N) ) q_offsets_lst.append( (col_indices[r0:r1] * (Ks * N)).repeat(SPLIT_N) + b.repeat_interleave(r1 - r0) ) q_offsets = torch.cat(q_offsets_lst) crow_indices_diff = crow_indices.diff() non_zero_row_indices = crow_indices_diff.nonzero() a = non_zero_row_indices * (Ms * N) r_offsets = (a + b).view(-1) c_indices = torch.cat( ( crow_indices[:1], torch.cumsum( crow_indices_diff[non_zero_row_indices].repeat_interleave(SPLIT_N), 0, ), ) ) p_offsets = torch.cat(p_offsets_lst) return (indices_format, c_indices, r_offsets, p_offsets, q_offsets)
elif indices_format == "scatter_mm": Ns = Ms c_indices = [0] pq_offsets = [] # todo: eliminate inner for-loops for efficiency for b in range(nbatches): for m in range(M // Ms): r0 = crow_indices[m].item() r1 = crow_indices[m + 1].item() for n in range(N // Ns): c_indices.append(c_indices[-1] + r1 - r0) for t in range(r1 - r0): p = r0 + t q = (col_indices[p].item() + b * (K // Ks)) * (N // Ns) + n pq_offsets.append([p, q])
return ( indices_format, torch.tensor(c_indices, dtype=indices_dtype, device=device), torch.tensor(pq_offsets, dtype=indices_dtype, device=device), )
else: raise ValueError( f"Invalid {indices_format=}. Expected bsr_strided_mm_compressed|bsr_strided_mm|scatter_mm" )
def bsr_scatter_mm_indices_data( bsr, other, indices_format="bsr_strided_mm_compressed", **meta_input): """Computes indices data for :func:`scatter_mm` used in BSR and strided tensor matrix multiplication. """ assert bsr.dense_dim() == 0 assert bsr.ndim == 2 # no batch dims blocksize = bsr.values().shape[-2:] M, K = bsr.shape Ms, Ks = blocksize K_, N = other.shape[-2:] assert K_ == K nbatches = other.shape[:-2].numel()
meta = scatter_mm_meta(M, K, N, Ms, Ks, **meta_input) if "allow_tf32" not in meta_input: meta.update(allow_tf32=bsr.dtype in {torch.float16, torch.bfloat16}) SPLIT_N = meta["SPLIT_N"] indices_data = _bsr_scatter_mm_indices_data( indices_format, M, K, N, Ms, Ks, nbatches, SPLIT_N, TensorAsKey(bsr) )
if indices_format == "bsr_strided_mm_compressed": meta.update(is_compressed=True) return indices_data + (meta,) elif indices_format == "bsr_strided_mm": meta.update(is_compressed=False) return indices_data + (meta,) else: return indices_data
def bsr_scatter_mm(bsr, other, indices_data=None, out=None): """BSR @ strided -> strided"""
assert bsr.ndim == 2 assert other.ndim >= 2
Ms, Ks, Ns = bsr.shape[-2], bsr.shape[-1], other.shape[-1] blocksize = bsr.values().shape[-2:]
if indices_data is None: indices_data = bsr_scatter_mm_indices_data( bsr, other, indices_format="bsr_strided_mm_compressed" )
indices_format = indices_data[0]
if out is None: out = torch.empty( (*other.shape[:-2], Ms, Ns), dtype=bsr.dtype, device=bsr.device ) out_shape = out.shape out = as1Dbatch(out)
if bsr._nnz() == 0: out.zero_() elif indices_format in {"bsr_strided_mm_compressed", "bsr_strided_mm"}: out.zero_() scatter_mm(bsr.values(), other, indices_data, accumulators=out) elif indices_format == "scatter_mm": nbatches = other.shape[:-2].numel() accumulators = torch.zeros( ( nbatches * Ms // blocksize[0] * Ns // blocksize[0], blocksize[0], blocksize[0], ), dtype=bsr.dtype, device=bsr.device, ) others = ( as1Dbatch(other) .transpose(-2, -1) .view( nbatches, Ns // blocksize[0], blocksize[0], Ks // blocksize[1], blocksize[1], ) .movedim( (3, 1, 4, 2), (1, 2, 3, 4) ) # equivalent to .transpose(-3, -2).transpose(-2, -1).transpose(-4, -3) .flatten(0, 2) ) scatter_mm(bsr.values(), others, indices_data, accumulators=accumulators) out.copy_( accumulators.unflatten( 0, (nbatches, Ms // blocksize[0], Ns // blocksize[0]) ) .movedim( (1, 2, 3, 4), (3, 1, 4, 2) ) # equivalent to .transpose(-4, -3).transpose(-2, -1).transpose(-3, -2) .reshape(nbatches, Ns, Ms) .transpose(-2, -1) ) else: raise NotImplementedError(indices_format)
return out.view(out_shape)
def _int_bsr_dense_addmm( input: torch.Tensor, bsr: torch.Tensor, dense: torch.Tensor, *, beta=1, alpha=1, left_alpha: Optional[torch.Tensor] = None, right_alpha: Optional[torch.Tensor] = None, out: Optional[torch.Tensor] = None, skip_checks: bool = False, max_grid: Optional[tuple[Optional[int], Optional[int], Optional[int]]] = None, meta: Optional[dict] = None,): if out is None and dense.dtype is torch.int8: f_name = "_int_bsr_dense_addmm" crow_indices = bsr.crow_indices() batch_ndim = crow_indices.dim() - 1 M = bsr.shape[batch_ndim] N = dense.shape[-1] original_batch_dims_broadcasted = broadcast_batch_dims(f_name, bsr, dense) out = torch.empty( original_batch_dims_broadcasted + (M, N), dtype=torch.int32, device=dense.device, ) return bsr_dense_addmm( input, bsr, dense, beta=beta, alpha=alpha, left_alpha=left_alpha, right_alpha=right_alpha, out=out, skip_checks=skip_checks, max_grid=max_grid, meta=meta, )
def bsr_dense_addmm( input: torch.Tensor, bsr: torch.Tensor, dense: torch.Tensor, *, beta=1, alpha=1, left_alpha: Optional[torch.Tensor] = None, right_alpha: Optional[torch.Tensor] = None, out: Optional[torch.Tensor] = None, skip_checks: bool = False, max_grid: Optional[tuple[Optional[int], Optional[int], Optional[int]]] = None, meta: Optional[dict] = None,): """Compute
out = beta * input + left_alpha.reshape(-1, 1) * (alpha * (bsr @ dense)) * right_alpha.reshape(1, -1)
where left_alpha, right_alpha are (* + 1)-D tensors when specified, otherwise, these are treated as tensors filled with ones. """ f_name = "bsr_dense_addmm" values = bsr.values() crow_indices = bsr.crow_indices() col_indices = bsr.col_indices() batch_ndim = crow_indices.dim() - 1 M, K = bsr.shape[batch_ndim : batch_ndim + 2] blocksize = values.shape[batch_ndim + 1 : batch_ndim + 3] N = dense.shape[-1]
# todo: implement checks
original_batch_dims_broadcasted = broadcast_batch_dims(f_name, bsr, dense) if out is None: out = dense.new_empty(original_batch_dims_broadcasted + (M, N))
if bsr._nnz() == 0 or alpha == 0 or N == 0 or M == 0 or K == 0: if beta == 0: out.zero_() else: out.copy_(input) if beta != 1: out.mul_(beta) return out
left_alpha_is_one = False right_alpha_is_one = False if left_alpha is None: left_alpha_is_one = True left_alpha = dense.new_empty(()).expand( *original_batch_dims_broadcasted, M, N ) # not referenced else: left_alpha = left_alpha.view(*original_batch_dims_broadcasted, M, 1).expand( *original_batch_dims_broadcasted, M, N )
if right_alpha is None: right_alpha_is_one = True right_alpha = dense.new_empty(()).expand( *original_batch_dims_broadcasted, M, N ) # not referenced else: right_alpha = right_alpha.view(*original_batch_dims_broadcasted, 1, N).expand( *original_batch_dims_broadcasted, M, N ) assert left_alpha.stride()[-1] == 0 assert right_alpha.stride()[-2] == 0
if meta is None: sparsity = round(1 - bsr._nnz() * blocksize[0] * blocksize[1] / (M * K), 2) meta = bsr_dense_addmm_meta( M, K, N, blocksize[0], blocksize[1], beta, alpha, sparsity=sparsity, dtype=dense.dtype, out_dtype=out.dtype, ) out_backup = out
( crow_indices, col_indices, values, input, dense, left_alpha, right_alpha, out, ) = prepare_inputs(bsr, input, dense, left_alpha, right_alpha, out)
BM, BK = blocksize SPLIT_N = meta.get("SPLIT_N", N // BM) BN = N // SPLIT_N
out_untiled = out out = tile_to_blocksize(out, (BM, BN)) dense = tile_to_blocksize(dense, (BK, BN)) input = tile_to_blocksize(input, (BM, BN)) left_alpha = tile_to_blocksize(left_alpha, (BM, BN)) right_alpha = tile_to_blocksize(right_alpha, (BM, BN))
# tl.dot supports float16, float32, int32 as accumulator types. dot_out_dtype = { torch.float16: tl.float32, torch.bfloat16: tl.float32, torch.float32: tl.float64, torch.float64: tl.float64, torch.int8: tl.int32, torch.int32: tl.int32, }[out.dtype]
n_batches = dense.size(0) n_block_rows = crow_indices.size(-1) - 1 n_block_cols = dense.size(-3)
full_grid = (n_batches, n_block_cols, n_block_rows) if max_grid is not None: grid_blocks = tuple(max_grid[:3][::-1]) + (None,) * (3 - len(max_grid[:3])) else: grid_blocks = None
tensor_dims_map = { values: (0, None, None), crow_indices: (0, None, -1), col_indices: (0, None, None), input: (0, -3, -4), dense: (0, -3, None), left_alpha: (0, -3, -4), right_alpha: (0, -3, -4), out: (0, -3, -4), }
assert alpha != 0
def kernel(grid, *sliced_tensors): _bsr_strided_addmm_kernel[grid]( *ptr_stride_extractor(*sliced_tensors), beta, alpha, beta_is_one=beta == 1, beta_is_nonzero=beta != 0, alpha_is_one=alpha == 1, left_alpha_is_one=left_alpha_is_one, right_alpha_is_one=right_alpha_is_one, BLOCKSIZE_ROW=BM, BLOCKSIZE_INNER=BK, BLOCKSIZE_COL=BN, allow_tf32=dot_out_dtype == tl.float32, acc_dtype=dot_out_dtype, **meta, )
launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks)
if out.data_ptr() != out_backup.data_ptr(): # prepare_inputs has made a copy of out, copy its content back # to out_backup: out_backup.copy_(out_untiled.view(out_backup.shape))
return out_backup
if has_triton(): import triton import triton.language as tl
@triton.jit def _sampled_addmm_kernel( alpha, beta, IS_BETA_ZERO: tl.constexpr, BLOCKSIZE_ROW: tl.constexpr, BLOCKSIZE_COL: tl.constexpr, k, TILE_K: tl.constexpr, values_ptr, values_batch_stride, values_nnz_stride, values_row_block_stride, values_col_block_stride, crow_indices_ptr, crow_indices_batch_stride, crow_indices_stride, col_indices_ptr, col_indices_batch_stride, col_indices_stride, mat1_ptr, mat1_batch_stride, mat1_tiled_row_stride, mat1_tiled_col_stride, mat1_row_block_stride, mat1_col_block_stride, mat2_ptr, mat2_batch_stride, mat2_tiled_row_stride, mat2_tiled_col_stride, mat2_row_block_stride, mat2_col_block_stride, acc_dtype: tl.constexpr, allow_tf32: tl.constexpr, ): batch_pid = tl.program_id(axis=1) row_block_pid = tl.program_id(axis=0)
crow_indices_offset_ptr = ( crow_indices_ptr + crow_indices_batch_stride * batch_pid + crow_indices_stride * row_block_pid ) nnz_offset = tl.load(crow_indices_offset_ptr) nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride)
# Compute nnz for the row with number row_block_pid. # If it is zero, skip the row. row_nnz = nnz_offset_next - nnz_offset if row_nnz == 0: return
row_block_arange = tl.arange(0, BLOCKSIZE_ROW) col_block_arange = tl.arange(0, BLOCKSIZE_COL)
# Pointers are set to the first block of the current row. values_block_ptrs = ( values_ptr + values_batch_stride * batch_pid + values_nnz_stride * nnz_offset + values_row_block_stride * row_block_arange[:, None] + values_col_block_stride * col_block_arange[None, :] )
col_index_nnz_ptr = ( col_indices_ptr + col_indices_batch_stride * batch_pid + col_indices_stride * nnz_offset )
# Advance mat1 to the current tiled row, ignore columns. mat1_block_ptrs = ( mat1_ptr + mat1_batch_stride * batch_pid + mat1_tiled_row_stride * row_block_pid + mat1_row_block_stride * row_block_arange[:, None] )
# Advance mat2 in batch and block col dimension. mat2_block_ptrs = ( mat2_ptr + mat2_batch_stride * batch_pid + mat2_col_block_stride * col_block_arange[None, :] )
k_tile_arange = tl.arange(0, TILE_K) for _ in range(row_nnz): acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype)
# find column block index col_block = tl.load(col_index_nnz_ptr)
for k_tile in range(0, k, TILE_K): k_offsets = k_tile + k_tile_arange mask_k = k_offsets < k
mat1_block = tl.load( mat1_block_ptrs + mat1_col_block_stride * k_offsets[None, :], mask=mask_k[None, :], other=0.0, )
mat2_block = tl.load( mat2_block_ptrs + mat2_tiled_col_stride * col_block + mat2_row_block_stride * k_offsets[:, None], mask=mask_k[:, None], other=0.0, )
acc_block += tl.dot( mat1_block, mat2_block, allow_tf32=allow_tf32, out_dtype=acc_dtype )
if IS_BETA_ZERO: acc_block *= alpha else: acc_block = alpha * acc_block + beta * tl.load(values_block_ptrs)
# write result tl.store(values_block_ptrs, acc_block.to(values_ptr.dtype.element_ty))
# advance val/col_index ptrs to the next block in the row. values_block_ptrs += values_nnz_stride col_index_nnz_ptr += col_indices_stride
@triton.jit def _bsr_strided_dense_rowspace_kernel( # values prologue values_ptr, values_batch_stride, values_nnz_stride, values_row_block_stride, values_col_block_stride, # values epilogue # crow_indices prologue crow_indices_ptr, crow_indices_batch_stride, crow_indices_stride, # crow_indices epilogue # col_indices prologue col_indices_ptr, col_indices_batch_stride, col_indices_stride, # col_indices epilogue # dense prologue dense_ptr, dense_batch_stride, dense_tiled_row_stride, dense_tiled_col_stride, dense_row_block_stride, dense_col_block_stride, # dense epilogue # output prologue output_ptr, output_batch_stride, output_tiled_row_stride, output_tiled_col_stride, output_row_block_stride, output_col_block_stride, # output epilogue # # gh-113754: Always keep all constexpr arguments at the end of # triton kernel arguments list because with triton 2.1 or # earlier non-contiguous outputs will corrupt CUDA state due # to a triton bug (fixed in openai/triton#2262). BLOCKSIZE_ROW: tl.constexpr, BLOCKSIZE_COL: tl.constexpr, acc_dtype: tl.constexpr, allow_tf32: tl.constexpr, GROUP_SIZE_ROW: tl.constexpr, ): batch_pid = tl.program_id(axis=2) row_block_pid = tl.program_id(axis=0) col_block_pid = tl.program_id(axis=1) n_block_rows = tl.num_programs(axis=0) n_block_cols = tl.num_programs(axis=1)
row_block_pid, col_block_pid = tl.swizzle2d( row_block_pid, col_block_pid, n_block_rows, n_block_cols, GROUP_SIZE_ROW )
crow_indices_offset_ptr = ( crow_indices_ptr + crow_indices_batch_stride * batch_pid + crow_indices_stride * row_block_pid ) nnz_offset = tl.load(crow_indices_offset_ptr) nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride)
# Compute nnz for the row with number row_block_pid. # If it is zero, skip the row. row_nnz = nnz_offset_next - nnz_offset if row_nnz == 0: return
row_block_arange = tl.arange(0, BLOCKSIZE_ROW) col_block_arange = tl.arange(0, BLOCKSIZE_COL)
# Pointers are set to the first block of the current row. values_block_ptrs = ( values_ptr + values_batch_stride * batch_pid + values_nnz_stride * nnz_offset + values_row_block_stride * row_block_arange[:, None] + values_col_block_stride * col_block_arange[None, :] )
# NOTE: dense is advanced into all dimensions but the tiled row one. # That will be advanced in the loop according to values in col_indices. dense_block_ptrs = ( dense_ptr + dense_batch_stride * batch_pid + dense_tiled_col_stride * col_block_pid + dense_row_block_stride * col_block_arange[:, None] + dense_col_block_stride * row_block_arange[None, :] )
# Pointers are set to exact write-to locations output_ptrs = ( output_ptr + output_batch_stride * batch_pid + output_tiled_row_stride * row_block_pid + output_tiled_col_stride * col_block_pid + output_row_block_stride * row_block_arange[:, None] + output_col_block_stride * row_block_arange[None, :] )
# Set pointer to the first nonzero element in the current row col_index_nnz_ptr = ( col_indices_ptr + col_indices_batch_stride * batch_pid + col_indices_stride * nnz_offset )
output_acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype) for _ in range(row_nnz): values_block = tl.load(values_block_ptrs)
# find which row of dense needs to get loaded # for multiplication with values_block. dense_row_idx = tl.load(col_index_nnz_ptr) dense_block = tl.load( dense_block_ptrs + dense_tiled_row_stride * dense_row_idx )
# do block mm output_acc_block += tl.dot( values_block, dense_block, allow_tf32=allow_tf32, out_dtype=acc_dtype )
# move val/col_index ptrs to the next block in the row values_block_ptrs += values_nnz_stride col_index_nnz_ptr += col_indices_stride
# write back the result tl.store(output_ptrs, output_acc_block.to(output_ptr.dtype.element_ty))
def _run_sampled_addmm_kernel( alpha, beta, is_beta_zero, blocksize, k, tile_k, values, crow_indices, col_indices, mat1, mat2, max_grid, ): n_batches = values.size(0) n_block_rows = crow_indices.size(-1) - 1
full_grid = (n_batches, n_block_rows) if max_grid is not None: grid_blocks = tuple(max_grid[:2][::-1]) + (None,) * (2 - len(max_grid[:2])) else: grid_blocks = None tensor_dims_map = { values: (0, None), crow_indices: (0, -1), col_indices: (0, None), mat1: (0, -4), mat2: (0, None), } if values.dtype in (torch.half, torch.bfloat16): acc_dtype = tl.float32 allow_tf32 = True else: acc_dtype = tl.float64 allow_tf32 = False
def kernel(grid, *sliced_tensors): _sampled_addmm_kernel[grid]( alpha, beta, is_beta_zero, *blocksize, k, tile_k, *ptr_stride_extractor(*sliced_tensors), acc_dtype=acc_dtype, allow_tf32=allow_tf32, num_stages=1, num_warps=4, )
launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks)
def sampled_addmm( input: torch.Tensor, mat1: torch.Tensor, mat2: torch.Tensor, *, beta=1.0, alpha=1.0, out: Optional[torch.Tensor] = None, skip_checks: bool = False, max_grid: Optional[tuple[Optional[int], Optional[int], Optional[int]]] = None, ): f_name = "sampled_addmm"
check_bsr_layout(f_name, input) input_broadcasted = broadcast_batch_dims_bsr(f_name, input, mat1, mat2)
if not skip_checks: check_device(f_name, mat1, input.device) check_device(f_name, mat2, input.device) if beta != 0.0 and input.dtype is torch.bool: check( False, f"{f_name}(): having beta == {beta} not equal to 0.0 with boolean mask is not allowed.", ) if input.dtype is not torch.bool: check_dtype(f_name, mat1, input.dtype) check_dtype(f_name, mat2, input.dtype) else: check_dtype(f_name, mat1, mat2.dtype) check_mm_compatible_shapes(f_name, mat1, mat2) if out is not None: check_bsr_layout(f_name, out) check_device(f_name, out, mat1.device) check_dtype(f_name, out, input.dtype) check( out.shape == input_broadcasted.shape and out._nnz() == input._nnz(), f"{f_name}(): Expects `out` to be of shape {input_broadcasted.shape} " f"and with nnz equal to {input_broadcasted._nnz()} " f"but got out.shape = {out.shape} and out.nnz = {out._nnz()}", )
if out is None: out = input_broadcasted.to(mat1.dtype, copy=True) else: out.copy_(input_broadcasted)
if out.numel() == 0 or out._nnz() == 0: return out
blocksize = out.values().shape[-2:] k = mat1.size(-1)
# NOTE: (m, 0) @ (0, n) == zeros(m, n) if alpha == 0.0 or k == 0: out.values().mul_(beta) return out
# prepare inputs by reshaping them to be kernel-compatible out_backup = out crow_indices, col_indices, values, mat1, mat2 = prepare_inputs(out, mat1, mat2)
mat1 = tile_to_blocksize(mat1, (blocksize[0], k)) mat2 = tile_to_blocksize(mat2, (k, blocksize[1])) tile_k = max(*blocksize)
_run_sampled_addmm_kernel( alpha, beta, beta == 0.0, blocksize, k, tile_k, values, crow_indices, col_indices, mat1, mat2, max_grid, )
# If nnz x block strides are not the same in out_backup.values and values, # it means that out_backup.values and values are not the views of each other, # so we have to copy. if out_backup.values().stride()[-3:] != values.stride()[-3:]: out_backup.values().copy_(values.reshape(out_backup.values().shape)) return out_backup
def bsr_dense_mm( bsr: torch.Tensor, dense: torch.Tensor, *, out: Optional[torch.Tensor] = None, skip_checks: bool = False, max_grid: Optional[tuple[Optional[int], Optional[int], Optional[int]]] = None, meta: Optional[dict] = None, ): f_name = "bsr_dense_mm" m, _kl = bsr.shape[-2:] if not skip_checks: check_bsr_layout(f_name, bsr) check_device(f_name, bsr, dense.device) check_dtype(f_name, bsr, dense.dtype, (torch.int8,)) check_mm_compatible_shapes(f_name, bsr, dense)
n = dense.size(-1) row_block, col_block = bsr.values().shape[-2:] check_blocksize(f_name, (row_block, col_block)) check( not n % 16, f"{f_name}(): dense.size(-1) == {n} should be divisible by 16", ) else: _kr, n = dense.shape[-2:]
original_batch_dims_broadcasted = broadcast_batch_dims(f_name, bsr, dense)
if out is not None and not skip_checks: expected_out_shape = original_batch_dims_broadcasted + (m, n) check( out.shape == expected_out_shape, "bsr_dense_mm(): `out` argument has wrong shape, " f"expected {expected_out_shape}, but got {out.shape}.", ) check( out.is_contiguous() or out.transpose(-2, -1).is_contiguous(), "bsr_dense_mm(): only row-major/col-major `out` arguments are supported, " "i.e. (out.is_contiguous() or out.transpose(-2, -1).is_contiguous()) " "should be True.", )
# Allocate out if out is None: out = dense.new_empty(original_batch_dims_broadcasted + (m, n))
# Short circuit if lhs is zero if bsr._nnz() == 0: return out.zero_()
# with beta==0, addmm ignores input content, so we can use out # as a placeholder for input because their shapes match: return bsr_dense_addmm(out, bsr, dense, alpha=1, beta=0, out=out)
@triton.jit def _bsr_softmax_kernel( crow_indices_ptr, crow_indices_batch_stride, crow_indices_stride, values_ptr, values_batch_stride, values_row_block_stride, values_nnz_col_block_stride, row_block, col_block, MAX_ROW_NNZ: tl.constexpr, TILE: tl.constexpr, ): batch_pid = tl.program_id(axis=2) row_block_offset_pid = tl.program_id(axis=1) row_block_pid = tl.program_id(axis=0)
crow_indices_offset_ptr = ( crow_indices_ptr + crow_indices_batch_stride * batch_pid + crow_indices_stride * row_block_pid ) nnz_offset = tl.load(crow_indices_offset_ptr) nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride)
# Compute nnz for the row with number row_block_pid. # If it is zero, skip the row. row_nnz = nnz_offset_next - nnz_offset if row_nnz == 0: return
row_arange = tl.arange(0, TILE) mask = row_arange < row_nnz * col_block
curr_row_values_ptrs = ( values_ptr + values_batch_stride * batch_pid + values_row_block_stride * row_block_offset_pid + nnz_offset * col_block )
# find max in the row row_tile = tl.load( curr_row_values_ptrs + row_arange, mask=mask, other=-float("inf") ).to(tl.float32) max_row_value = tl.max(row_tile, axis=0) for _ in range(TILE, MAX_ROW_NNZ, TILE): row_arange += TILE mask = row_arange < row_nnz * col_block row_tile = tl.load( curr_row_values_ptrs + row_arange, mask=mask, other=-float("inf") ).to(tl.float32) curr_max_row_value = tl.max(row_tile, axis=0) max_row_value = tl.where( max_row_value > curr_max_row_value, max_row_value, curr_max_row_value )
# find denominator for stable softmax num = tl.exp(row_tile - max_row_value) denom = tl.sum(num, axis=0) for _ in range(TILE, MAX_ROW_NNZ, TILE): row_arange -= TILE mask = row_arange < row_nnz * col_block row_tile = tl.load( curr_row_values_ptrs + row_arange, mask=mask, other=-float("inf") ).to(tl.float32) num = tl.exp(row_tile - max_row_value) denom += tl.sum(num, axis=0)
# populate output tl.store( curr_row_values_ptrs + row_arange, (num / denom).to(values_ptr.dtype.element_ty), mask=mask, ) for _ in range(TILE, MAX_ROW_NNZ, TILE): row_arange += TILE mask = row_arange < row_nnz * col_block row_tile = tl.load( curr_row_values_ptrs + row_arange, mask=mask, other=-float("inf") ).to(tl.float32) num = tl.exp(row_tile - max_row_value) tl.store( curr_row_values_ptrs + row_arange, (num / denom).to(values_ptr.dtype.element_ty), mask=mask, )
def bsr_softmax(input, max_row_nnz=None): f_name = "bsr_softmax"
check_bsr_layout(f_name, input) check_dtype(f_name, input, input.dtype)
if input._nnz() == 0 or input.numel() == 0: return input.clone()
m, n = input.shape[-2:] nnz = input._nnz() row_block, col_block = input.values().shape[-2:]
if max_row_nnz is None: max_row_nnz = triton.next_power_of_2(n) else: max_row_nnz = triton.next_power_of_2(max_row_nnz)
crow_indices = input.crow_indices().unsqueeze(0).flatten(0, -2) # reshape values from # (b1, ..., bn, nnz, row_block, col_block) to # (b1 * ... * bn, row_block, nnz * col_block). # This simplifies batch dim manipulation and unlocks # the possibility to access all nnzs in any given row. if input.values().transpose(-3, -2).is_contiguous(): # Need to clone to avoid `contiguous` returning a view. values = input.values().clone() else: values = input.values() values = ( values.transpose(-3, -2) .contiguous() .unsqueeze(0) .flatten(0, -4) .reshape(-1, row_block, nnz * col_block) ) full_grid = (values.shape[0], row_block, m // row_block) grid_blocks = None tensor_dims_map = { # We span nnz number of blocks, not nnz + 1, # hence crow_indices[..., :-1] crow_indices[..., :-1]: (0, None, -1), values: (0, None, None), }
def kernel(grid, *sliced_tensors): _bsr_softmax_kernel[grid]( *ptr_stride_extractor(*sliced_tensors), row_block, col_block, max_row_nnz, # Triton's max numel is bounded by 2 ** 17. min(2**17, max_row_nnz), )
launch_kernel(kernel, tensor_dims_map, full_grid, grid_blocks)
values = ( values.reshape(-1, row_block, nnz, col_block) .transpose(-3, -2) .reshape(*input.values().shape) )
return torch.sparse_compressed_tensor( input.crow_indices().clone(), input.col_indices().clone(), values, size=input.shape, layout=input.layout, )
def _scaled_dot_product_attention( query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attn_mask: Optional[torch.Tensor], dropout_p: float = 0.0, is_causal: bool = False, scale: Optional[float] = None, ): f_name = "_scaled_dot_product_attention" check(not is_causal, f"{f_name}(): is_causal == True is not supported.") check(attn_mask is not None, f"{f_name}(): attn_mask == None is not supported.") assert attn_mask is not None
check( attn_mask.layout == torch.sparse_bsr, f"{f_name}(): " f"attn_mask.layout must be {torch.sparse_bsr}, but got " f"attn_mask.layout == {attn_mask.layout}.", )
check_device(f_name, key, query.device) check_device(f_name, value, query.device) check_device(f_name, attn_mask, query.device)
check_dtype(f_name, key, query.dtype) check_dtype(f_name, value, query.dtype) if attn_mask.dtype is not torch.bool: check_dtype(f_name, attn_mask, query.dtype)
sdpa = sampled_addmm( attn_mask, query, key.transpose(-2, -1), beta=0.0, skip_checks=False ) if scale is None and query.size(-1) == 0 or scale == 0.0: check( False, f"{f_name}(): current value of scale == {scale} " "results in division by zero.", ) scale_factor = 1 / math.sqrt(query.size(-1)) if scale is None else scale sdpa.values().mul_(scale_factor) sdpa = bsr_softmax(sdpa) torch.nn.functional.dropout(sdpa.values(), p=dropout_p, inplace=True) sdpa = bsr_dense_mm(sdpa, value) return sdpa
@triton.jit def _scatter_mm2_kernel( M: tl.constexpr, K: tl.constexpr, N: tl.constexpr, blocks_ptr, blocks_stride_P, blocks_stride_M, blocks_stride_K, others_ptr, others_stride_Q, others_stride_K, others_stride_N, accumulators_ptr, accumulators_stride_R, accumulators_stride_M, accumulators_stride_N, pq_offsets_ptr, pq_offsets_stride, pq_ptr, pq_stride_T, pq_stride_1, dot_out_dtype: tl.constexpr, TILE_M: tl.constexpr, TILE_N: tl.constexpr, allow_tf32: tl.constexpr, ): Ms = M // TILE_M
pid_t = tl.program_id(axis=0)
pid = tl.program_id(axis=1) pid_m = pid // Ms pid_n = pid % Ms
rm = pid_m * TILE_M + tl.arange(0, TILE_M) rn = pid_n * TILE_N + tl.arange(0, TILE_N) rk = tl.arange(0, K)
A_ptr = blocks_ptr + ( rm[:, None] * blocks_stride_M + rk[None, :] * blocks_stride_K ) B_ptr = others_ptr + ( rk[:, None] * others_stride_K + rn[None, :] * others_stride_N )
g0 = tl.load(pq_offsets_ptr + pid_t * pq_offsets_stride) g1 = tl.load(pq_offsets_ptr + (pid_t + 1) * pq_offsets_stride)
if g0 == g1: return
acc_block = tl.zeros((TILE_M, TILE_N), dtype=dot_out_dtype)
for i in range(g0, g1): p = tl.load(pq_ptr + i * pq_stride_T) q = tl.load(pq_ptr + i * pq_stride_T + pq_stride_1) A = tl.load(A_ptr + p * blocks_stride_P) B = tl.load(B_ptr + q * others_stride_Q) acc_block += tl.dot(A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32)
C_ptr = ( accumulators_ptr + pid_t * accumulators_stride_R + ( rm[:, None] * accumulators_stride_M + rn[None, :] * accumulators_stride_N ) ) tl.store(C_ptr, acc_block.to(accumulators_ptr.dtype.element_ty))
def _scatter_mm2( blocks: torch.Tensor, others: torch.Tensor, pq_offsets: torch.Tensor, pq_indices: torch.Tensor, accumulators: torch.Tensor, ): _P, M, K = blocks.shape _Q, _, N = others.shape
meta = dict( TILE_M=max(16, M // 4), TILE_N=max(16, N // 4), num_stages=1, num_warps=2 )
def grid(META): return ( pq_offsets.shape[0] - 1, triton.cdiv(M, META["TILE_M"]) * triton.cdiv(N, META["TILE_N"]), 1, )
dot_out_dtype = { torch.float16: tl.float32, torch.bfloat16: tl.float32, torch.float32: tl.float64, torch.float64: tl.float64, }[accumulators.dtype] if "allow_tf32" not in meta: meta.update(allow_tf32=dot_out_dtype == tl.float32) _scatter_mm2_kernel[grid]( M, K, N, blocks, blocks.stride(0), blocks.stride(1), blocks.stride(2), others, others.stride(0), others.stride(1), others.stride(2), accumulators, accumulators.stride(0), accumulators.stride(1), accumulators.stride(2), pq_offsets, pq_offsets.stride(0), pq_indices, pq_indices.stride(0), pq_indices.stride(1), dot_out_dtype=dot_out_dtype, **meta, )
@triton.jit def _scatter_mm6_kernel( nbatches, Ms, Ks: tl.constexpr, N, blocks_ptr, blocks_stride_P, blocks_stride_M, blocks_stride_K, others_ptr, others_stride_B, others_stride_K, others_stride_N, accumulators_ptr, accumulators_stride_B, accumulators_stride_M, accumulators_stride_N, c_indices_ptr, r_offsets_ptr, p_offsets_ptr, q_offsets_ptr, is_compressed: tl.constexpr, dot_out_dtype: tl.constexpr, SPLIT_N: tl.constexpr, TILE_M: tl.constexpr, TILE_N: tl.constexpr, GROUP_SIZE: tl.constexpr, allow_tf32: tl.constexpr, ): Ns = N // SPLIT_N BLOCKS_M = Ms // TILE_M BLOCKS_N = Ns // TILE_N
pid_t_ = tl.program_id(axis=0) pid = tl.program_id(axis=1) pid_b = pid_t_ % nbatches pid_t = pid_t_ // nbatches
num_pid_in_group = GROUP_SIZE * BLOCKS_N group_id = pid // num_pid_in_group first_pid_m = group_id * GROUP_SIZE group_size_m = min(BLOCKS_M - first_pid_m, GROUP_SIZE) pid_m = first_pid_m + (pid % group_size_m) pid_n = (pid % num_pid_in_group) // group_size_m
rm = pid_m * TILE_M + tl.arange(0, TILE_M) rn = pid_n * TILE_N + tl.arange(0, TILE_N) rk = tl.arange(0, Ks) A_ptr = blocks_ptr + ( rm[:, None] * blocks_stride_M + rk[None, :] * blocks_stride_K ) B_ptr = ( others_ptr + pid_b * others_stride_B + (rk[:, None] * others_stride_K + rn[None, :] * others_stride_N) )
# When is_compressed is True, r is the only variable that # depends on pid_t. This property allows sorting r values # before calling the kernel. The sorting of r is equivalent to # defining swizzle operator outside of the kernel. r = tl.load(r_offsets_ptr + pid_t)
if is_compressed: m = (r // N) // Ms n = (r % N) // Ns r0 = tl.load(c_indices_ptr + m) r1 = tl.load(c_indices_ptr + m + 1) g0 = n * r1 + (SPLIT_N - n) * r0 nnz = r1 - r0 else: g0 = tl.load(c_indices_ptr + pid_t) g1 = tl.load(c_indices_ptr + pid_t + 1) nnz = g1 - g0
q_ptr = q_offsets_ptr + g0 acc_block = tl.zeros((TILE_M, TILE_N), dtype=dot_out_dtype)
if is_compressed: A_ptr += r0 * blocks_stride_P # type: ignore[possibly-undefined] for _ in range(nnz): q = tl.load(q_ptr) B = tl.load(B_ptr + q) A = tl.load(A_ptr) acc_block += tl.dot( A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32 ) A_ptr += blocks_stride_P q_ptr += 1 else: p_ptr = p_offsets_ptr + g0 for _ in range(nnz): q = tl.load(q_ptr) B = tl.load(B_ptr + q) p = tl.load(p_ptr) A = tl.load(A_ptr + p * blocks_stride_P) p_ptr += 1 q_ptr += 1 acc_block += tl.dot( A, B, out_dtype=dot_out_dtype, allow_tf32=allow_tf32 )
C_ptr = ( accumulators_ptr + r + pid_b * accumulators_stride_B + ( rm[:, None] * accumulators_stride_M + rn[None, :] * accumulators_stride_N ) ) tl.store(C_ptr, acc_block.to(accumulators_ptr.dtype.element_ty))
def _scatter_mm6( blocks: torch.Tensor, others: torch.Tensor, c_indices: torch.Tensor, r_offsets: torch.Tensor, p_offsets: torch.Tensor, q_offsets: torch.Tensor, meta: dict, accumulators: torch.Tensor, force_contiguous: bool = True, ): SPLIT_N = meta["SPLIT_N"] _P, Ms, Ks = blocks.shape B, _K, N = others.shape B_, _M, N_ = accumulators.shape assert N_ == N Ns = N // SPLIT_N assert B_ == B
def grid(META): return ( r_offsets.shape[0] * B, triton.cdiv(Ms, META["TILE_M"]) * triton.cdiv(Ns, META["TILE_N"]), )
dot_out_dtype = { torch.float16: tl.float32, torch.bfloat16: tl.float32, torch.float32: tl.float64, torch.float64: tl.float64, }[accumulators.dtype] if "allow_tf32" not in meta: meta.update(allow_tf32=dot_out_dtype == tl.float32)
assert c_indices.stride(0) == 1 assert r_offsets.stride(0) == 1 assert p_offsets.stride(0) == 1 assert q_offsets.stride(0) == 1
# Re non-contiguous tensor arguments. Sometimes triton kernel # launches may fail with # # RuntimeError: Triton Error [CUDA]: an illegal memory access was encountered # # that appears to be case when the size of a non-contiguous # tensor argument is larger than a certain threshold. Could # this be related to shared memory or L1 cache size of a GPU # card? In anycase, ensuring that tensor arguments are # contiguous seems to avoid the above exception. So, in the # following we'll always convert tensor arguments to # C-contiguous tensors.
if force_contiguous: blocks = blocks.contiguous() others = others.contiguous() if not accumulators.is_contiguous(): accumulators_ = accumulators.contiguous() else: accumulators_ = accumulators else: accumulators_ = accumulators
_scatter_mm6_kernel[grid]( B, Ms, Ks, N, blocks, blocks.stride(0), blocks.stride(1), blocks.stride(2), others, others.stride(0), others.stride(1), others.stride(2), accumulators_, accumulators_.stride(0), accumulators_.stride(1), accumulators_.stride(2), c_indices, r_offsets, p_offsets, q_offsets, dot_out_dtype=dot_out_dtype, **meta, )
if force_contiguous and not accumulators.is_contiguous(): accumulators.copy_(accumulators_)
@triton.jit def _bsr_strided_addmm_kernel( # values prologue values_ptr, values_batch_stride, values_nnz_stride, values_row_block_stride, values_col_block_stride, # values epilogue # crow_indices prologue crow_indices_ptr, crow_indices_batch_stride, crow_indices_stride, # crow_indices epilogue # col_indices prologue col_indices_ptr, col_indices_batch_stride, col_indices_stride, # col_indices epilogue # input prologue input_ptr, input_batch_stride, input_tiled_row_stride, input_tiled_col_stride, input_row_block_stride, input_col_block_stride, # input epilogue # dense prologue dense_ptr, dense_batch_stride, dense_tiled_row_stride, dense_tiled_col_stride, dense_row_block_stride, dense_col_block_stride, # dense epilogue # left_alpha prologue left_alpha_ptr, left_alpha_batch_stride, left_alpha_tiled_row_stride, left_alpha_tiled_col_stride: tl.constexpr, left_alpha_row_block_stride, left_alpha_col_block_stride: tl.constexpr, # left_alpha epilogue # right_alpha prologue right_alpha_ptr, right_alpha_batch_stride, right_alpha_tiled_row_stride: tl.constexpr, right_alpha_tiled_col_stride, right_alpha_row_block_stride: tl.constexpr, right_alpha_col_block_stride, # right_alpha epilogue # output prologue output_ptr, output_batch_stride, output_tiled_row_stride, output_tiled_col_stride, output_row_block_stride, output_col_block_stride, # output epilogue beta, alpha, beta_is_one: tl.constexpr, beta_is_nonzero: tl.constexpr, alpha_is_one: tl.constexpr, left_alpha_is_one: tl.constexpr, right_alpha_is_one: tl.constexpr, BLOCKSIZE_ROW: tl.constexpr, BLOCKSIZE_COL: tl.constexpr, BLOCKSIZE_INNER: tl.constexpr, acc_dtype: tl.constexpr, allow_tf32: tl.constexpr, GROUP_SIZE_ROW: tl.constexpr, SPLIT_N: tl.constexpr, ): # left/right_alpha tensors are originally (* + 1)-dimensional assert left_alpha_tiled_col_stride == 0 assert left_alpha_col_block_stride == 0 assert right_alpha_tiled_row_stride == 0 assert right_alpha_row_block_stride == 0
batch_pid = tl.program_id(axis=2) row_block_pid = tl.program_id(axis=0) col_block_pid = tl.program_id(axis=1) n_block_rows = tl.num_programs(axis=0) n_block_cols = tl.num_programs(axis=1)
row_block_pid, col_block_pid = tl.swizzle2d( row_block_pid, col_block_pid, n_block_rows, n_block_cols, GROUP_SIZE_ROW )
crow_indices_offset_ptr = ( crow_indices_ptr + crow_indices_batch_stride * batch_pid + crow_indices_stride * row_block_pid ) nnz_offset = tl.load(crow_indices_offset_ptr) nnz_offset_next = tl.load(crow_indices_offset_ptr + crow_indices_stride)
# Compute nnz for the row with number row_block_pid. row_nnz = nnz_offset_next - nnz_offset
row_block_arange = tl.arange(0, BLOCKSIZE_ROW) inner_block_arange = tl.arange(0, BLOCKSIZE_INNER) col_block_arange = tl.arange(0, BLOCKSIZE_COL)
# Pointers are set to the first block of the current row. values_block_ptrs = ( values_ptr + values_batch_stride * batch_pid + values_nnz_stride * nnz_offset + values_row_block_stride * row_block_arange[:, None] + values_col_block_stride * inner_block_arange[None, :] )
# NOTE: dense is advanced into all dimensions but the tiled row one. # That will be advanced in the loop according to values in col_indices. dense_block_ptrs = ( dense_ptr + dense_batch_stride * batch_pid + dense_tiled_col_stride * col_block_pid + dense_row_block_stride * inner_block_arange[:, None] + dense_col_block_stride * col_block_arange[None, :] )
# Pointers are set to exact write-to locations output_ptrs = ( output_ptr + output_batch_stride * batch_pid + output_tiled_row_stride * row_block_pid + output_tiled_col_stride * col_block_pid + output_row_block_stride * row_block_arange[:, None] + output_col_block_stride * col_block_arange[None, :] )
# Set pointer to the first nonzero element in the current row col_index_nnz_ptr = ( col_indices_ptr + col_indices_batch_stride * batch_pid + col_indices_stride * nnz_offset )
output_acc_block = tl.zeros((BLOCKSIZE_ROW, BLOCKSIZE_COL), dtype=acc_dtype)
for _ in range(row_nnz): values_block = tl.load(values_block_ptrs)
# find which row of dense needs to get loaded # for multiplication with values_block. dense_row_idx = tl.load(col_index_nnz_ptr) dense_block = tl.load( dense_block_ptrs + dense_tiled_row_stride * dense_row_idx )
# do block mm output_acc_block += tl.dot( values_block, dense_block, allow_tf32=allow_tf32, out_dtype=acc_dtype )
# move val/col_index ptrs to the next block in the row values_block_ptrs += values_nnz_stride col_index_nnz_ptr += col_indices_stride
if not alpha_is_one: output_acc_block *= alpha
if not left_alpha_is_one: left_alpha_ptrs = ( left_alpha_ptr + left_alpha_batch_stride * batch_pid + left_alpha_tiled_row_stride * row_block_pid + left_alpha_tiled_col_stride * col_block_pid + left_alpha_row_block_stride * row_block_arange[:, None] + left_alpha_col_block_stride * col_block_arange[None, :] ) output_acc_block *= tl.load(left_alpha_ptrs)
if not right_alpha_is_one: right_alpha_ptrs = ( right_alpha_ptr + right_alpha_batch_stride * batch_pid + right_alpha_tiled_row_stride * row_block_pid + right_alpha_tiled_col_stride * col_block_pid + right_alpha_row_block_stride * row_block_arange[:, None] + right_alpha_col_block_stride * col_block_arange[None, :] ) output_acc_block *= tl.load(right_alpha_ptrs)
if beta_is_nonzero: input_ptrs = ( input_ptr + input_batch_stride * batch_pid + input_tiled_row_stride * row_block_pid + input_tiled_col_stride * col_block_pid + input_row_block_stride * row_block_arange[:, None] + input_col_block_stride * col_block_arange[None, :] ) if beta_is_one: output_acc_block += tl.load(input_ptrs) else: output_acc_block += beta * tl.load(input_ptrs)
# write back the result tl.store(output_ptrs, output_acc_block.to(output_ptr.dtype.element_ty))
else: bsr_softmax = None # type: ignore[assignment] bsr_dense_mm = None # type: ignore[assignment] sampled_addmm = None # type: ignore[assignment] _scaled_dot_product_attention = None # type: ignore[assignment] _scatter_mm2 = None # type: ignore[assignment] _scatter_mm6 = None # type: ignore[assignment] _bsr_strided_addmm_kernel = None # type: ignore[assignment]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658# mypy: allow-untyped-defsimport warningsfrom collections import namedtuplefrom typing import Any, Callable, Optional
import torchfrom torch.sparse._semi_structured_conversions import ( sparse_semi_structured_from_dense_cutlass, sparse_semi_structured_to_dense_cutlass,)from torch.sparse._semi_structured_ops import ( fallback_dispatcher, semi_sparse_addmm, semi_sparse_detach, semi_sparse_indices, semi_sparse_linear, semi_sparse_mm, semi_sparse_scaled_mm, semi_sparse_t, semi_sparse_values, semi_sparse_view,)
__all__ = [ "SparseSemiStructuredTensor", "SparseSemiStructuredTensorCUTLASS", "SparseSemiStructuredTensorCUSPARSELT", "to_sparse_semi_structured",]
_SEMI_STRUCTURED_SPARSE_CONFIG = namedtuple( "_SEMI_STRUCTURED_SPARSE_CONFIG", "sparse_min_rows sparse_min_cols dense_min_rows dense_min_cols",)
class SparseSemiStructuredTensor(torch.Tensor): """ This class implements semi-structured sparsity as a Tensor subclass.
Semi-structured sparsity describes a sparsity pattern where n in every 2n elements are sparse, depending on the datatype. It is also referred to as 2:4 sparsity or fine-grained structured sparsity.
There are two backends available for semi_structred sparsity, either cuSPARSELt or CUTLASS. This class is meant to serve as a base class for both implementations. SparseSemiStructuredCUTLASS and SparseSemiStructuredCUSPARSELT both inherit from this class and define three backend-specific items. Note that as such, this class cannot be instantiated directly.
-`_DTYPE_SHAPE_CONSTRAINTS` - A dictionary holding backend specific dense/sparse min shape constraints - `def from_dense()` - backend specific compression routines - `def _mm()` - backend specific mm op (either torch._cslt_sparse_mm or torch._sparse_semi_structured_(mm|addmm)) """
_DEFAULT_ALG_ID: int = 0 _DTYPE_SHAPE_CONSTRAINTS: dict[torch.dtype, _SEMI_STRUCTURED_SPARSE_CONFIG] _FORCE_CUTLASS: bool = False _FUSE_TRANSPOSE: bool = False _PROTOTYPE_WARNING_SHOWN: bool = False
BACKEND: str SPARSE_DISPATCH: dict[Callable, Callable]
packed: Optional[torch.Tensor] meta: Optional[torch.Tensor] packed_t: Optional[torch.Tensor] meta_t: Optional[torch.Tensor] compressed_swizzled_bitmask: Optional[torch.Tensor] fuse_transpose_cusparselt: bool alg_id_cusparselt: int
__slots__ = ["packed", "meta", "packed_t", "meta_t", "compressed_swizzled_bitmask"]
@staticmethod def __new__( # noqa: PYI034 cls, shape: torch.Size, packed: Optional[torch.Tensor], meta: Optional[torch.Tensor], packed_t: Optional[torch.Tensor], meta_t: Optional[torch.Tensor], compressed_swizzled_bitmask: Optional[torch.Tensor], fuse_transpose_cusparselt: bool = False, alg_id_cusparselt: int = 0, requires_grad: bool = False, ): """ Create a new instance of the tensor subclass from the compressed sparse representation.
We have the option to create the subclass with the compressed representations of both X and X', for training. For inference, we only need a single representation (either X or X'), while the corresponding other set will be None.
Depending on the backend selected, certain fields will be set to None. (CUSPARSELT vs CUTLASS)
Args: shape: The shape of the original dense tensor packed: The compressed representation of the original dense tensor meta: The metadata of the original dense tensor, if it is stored separately packed_t: The compressed representation of the transposed original dense tensor meta_t: The metadata of the transposed original dense tensor, if it is stored separately compressed_swizzled_bitmask: The masks used by the CUTLASS backend to determine which threads should participate in the computation. Used for pointwise ops. fuse_transpose_cusparselt: When running with cuSPARSELt, we have the option to fuse a transposition with a matmul, which is useful in the case of 2:4 sparse training. alg_id_cusparselt: The algorithm id to use when using cuSPARSELT, will have effect on performance
Returns: torch.Tensor: A torch.Tensor wrapper subclass.
Raises: ValueError: If all of the tensor arguments are None. """ if not cls._PROTOTYPE_WARNING_SHOWN: warnings.warn( ( "The PyTorch API of SparseSemiStructuredTensor is in prototype stage " "and will change in the near future. Please open a Github issue " "for features requests and see our documentation on the torch.sparse " "module for further information about the project." ), UserWarning, ) cls._PROTOTYPE_WARNING_SHOWN = True
# Because this only runs once, we also load the dispatch table here as well. # We can't define the dispatch table explicitly because of torch.ops import errors, so we do this instead # But this is useful since it allows users to overload the dispatch table for debugging / testing. cls._load_dispatch_table()
# we can also register the classes with dynamo when the warning is shown. torch._dynamo.allow_in_graph(cls)
if packed is not None: previous_tensor = packed elif packed_t is not None: previous_tensor = packed_t else: raise ValueError("At least one of packed or packed_t must be provided")
tensor = torch.Tensor._make_wrapper_subclass( cls, shape, device=previous_tensor.device, dtype=previous_tensor.dtype, layout=previous_tensor.layout, requires_grad=requires_grad, )
tensor.packed = packed tensor.meta = meta tensor.packed_t = packed_t tensor.meta_t = meta_t tensor.compressed_swizzled_bitmask = compressed_swizzled_bitmask tensor.fuse_transpose_cusparselt = fuse_transpose_cusparselt tensor.alg_id_cusparselt = alg_id_cusparselt return tensor
def __repr__(self) -> str: # type: ignore[override] assert hasattr(self, "shape") return f"{self.__class__.__name__}(shape={self.shape})"
def __tensor_flatten__( self, ) -> tuple[list[str], tuple[torch.Size, bool, int, bool]]: inner_tensors = list( filter(lambda x: getattr(self, x) is not None, self.__slots__) ) tensor_meta = ( self.shape, self.fuse_transpose_cusparselt, self.alg_id_cusparselt, self.requires_grad, ) return inner_tensors, tensor_meta
@classmethod def __tensor_unflatten__( cls, inner_tensors, tensor_meta: tuple[torch.Size, bool, int, bool], outer_size, outer_stride, ) -> torch.Tensor: shape, fuse_transpose_cusparselt, alg_id_cusparselt, requires_grad = tensor_meta return cls( shape=shape, packed=inner_tensors.get("packed", None), meta=inner_tensors.get("meta", None), packed_t=inner_tensors.get("packed_t", None), meta_t=inner_tensors.get("meta_t", None), compressed_swizzled_bitmask=inner_tensors.get( "compressed_swizzled_bitmask", None ), fuse_transpose_cusparselt=fuse_transpose_cusparselt, alg_id_cusparselt=alg_id_cusparselt, requires_grad=requires_grad, )
__torch_function__ = torch._C._disabled_torch_function_impl # type: ignore[assignment]
@classmethod def __torch_dispatch__(cls, func, types, args, kwargs) -> Any: # type: ignore[override] if func._overloadpacket not in cls.SPARSE_DISPATCH: raise NotImplementedError( f"{cls.__name__} only supports a specific set of operations, " f"can't perform requested op ({func.__name__})" ) return cls.SPARSE_DISPATCH[func._overloadpacket](func, types, args, kwargs)
@classmethod def _load_dispatch_table(cls, custom_dispatch_table=None) -> None: """ Loads the op overload sparse dispatch table for the current class. """ if getattr(cls, "SPARSE_DISPATCH", None) is None: cls.SPARSE_DISPATCH = { torch.ops.aten.values: semi_sparse_values, torch.ops.aten.indices: semi_sparse_indices, torch.ops.aten.is_same_size: fallback_dispatcher, torch.ops.aten.detach_: fallback_dispatcher, torch.ops.aten.detach: semi_sparse_detach, torch.ops.aten.t: semi_sparse_t, torch.ops.aten.view: semi_sparse_view, torch.ops.aten.mm: semi_sparse_mm, torch.ops.aten.matmul: semi_sparse_mm, torch.ops.aten.addmm: semi_sparse_addmm, torch.ops.aten.linear: semi_sparse_linear, torch.ops.aten._to_copy: fallback_dispatcher, torch.ops.aten._scaled_mm: semi_sparse_scaled_mm, } if custom_dispatch_table is not None: cls.SPARSE_DISPATCH.update(custom_dispatch_table)
@classmethod def _validate_device_dim_dtype_shape(cls, original_tensor: torch.Tensor) -> None: """ Assert that the given tensor is valid for semi-structured sparse compression. """ # check device if not original_tensor.is_cuda: raise RuntimeError( f"Error original_tensor.device= {original_tensor.device} is not supported! " "Only CUDA tensors are currently supported." )
# check dim if original_tensor.dim() != 2: raise RuntimeError( f"Error original_tensor.dim = {original_tensor.dim()} is not supported! " "Only 2d tensors are currently supported." )
# check contiguous if not original_tensor.is_contiguous(): raise RuntimeError( "Error original_tensor is not contiguous!" "Only contiguous tensors are currently supported." )
# check dtype if original_tensor.dtype not in cls._DTYPE_SHAPE_CONSTRAINTS: raise RuntimeError( f"Error original_tensor.dtype {original_tensor.dtype} is not a supported dtype for {cls}!" )
# check shape m, n = original_tensor.shape min_rows = cls._DTYPE_SHAPE_CONSTRAINTS[original_tensor.dtype].sparse_min_rows min_cols = cls._DTYPE_SHAPE_CONSTRAINTS[original_tensor.dtype].sparse_min_cols if m < min_rows or m % min_rows or n < min_cols or n % min_cols: # TODO in the future we can add in padding to support sparse dimensions that aren't perfect multiples raise RuntimeError( f"Error original_tensor.shape {original_tensor.shape} is not supported! " f"Both dimensions must be larger or equal than and a multiple of ({min_rows}, {min_cols})" )
@classmethod def _pad_dense_input(cls, dense_input: torch.Tensor) -> torch.Tensor: """ Calculates padding for dense tensor and pads tensor if necessary. If padding is not required, this function returns the original tensor. """ # only 2d matmul assert dense_input.dim() == 2
# check shape m, n = dense_input.shape min_rows = cls._DTYPE_SHAPE_CONSTRAINTS[dense_input.dtype].dense_min_rows min_cols = cls._DTYPE_SHAPE_CONSTRAINTS[dense_input.dtype].dense_min_cols
# calculate padding to_pad_m = -m % min_rows if m < min_rows or m % min_rows else 0 to_pad_n = -n % min_cols if n < min_cols or n % min_rows else 0 if to_pad_m or to_pad_n: return torch.nn.functional.pad(dense_input, (0, to_pad_n, 0, to_pad_m)) else: return dense_input
def to_dense(self): # type:ignore[override] col = self.shape[-1] return torch.mm(self, torch.eye(col, dtype=self.dtype, device=self.device))
@classmethod def from_dense(cls, original_tensor: torch.Tensor) -> "SparseSemiStructuredTensor": raise NotImplementedError
def _mm( self, B: torch.Tensor, *, bias: Optional[torch.Tensor] = None, **kwargs, ) -> torch.Tensor: raise NotImplementedError
def to_sparse_semi_structured( original_tensor: torch.Tensor, transposed: bool = False,) -> SparseSemiStructuredTensor: """ This function converts a dense tensor into a sparse semi-structured tensor. It will return a SparseSemiStructuredTensor, a subclass of torch.Tensor.
This function will check to ensure the dense tensor has the right dtype, size, dims, and device. We currently only support semi-structured sparse tensors for 2d CUDA tensors. Additionally, your tensor must be a positive multiple of the minimum sparse block size, given in `_DTYPE_TO_SHAPE_CONSTRAINTS` for each dtype (float32, float16, bfloat16, int8).
Args: original_tensor (Tensor): the dense tensor to convert transposed (bool, optional): deprecated arg to be removed in another release. Do not use. Returns: SparseSemiStructuredTensor: A sparse semi-structured tensor created from the given original_tensor Raises: None Example: >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA) >>> A = torch.Tensor([0, 0, 1, 1]).tile((128, 32)).half().cuda() tensor([[0., 0., 1., ..., 0., 1., 1.], [0., 0., 1., ..., 0., 1., 1.], [0., 0., 1., ..., 0., 1., 1.], ..., [0., 0., 1., ..., 0., 1., 1.], [0., 0., 1., ..., 0., 1., 1.], [0., 0., 1., ..., 0., 1., 1.]], device='cuda:0', dtype=torch.float16) >>> A_sparse = to_sparse_semi_structured(A) SparseSemiStructuredTensor(shape=torch.Size([128, 128])) >>> A_sparse.values() tensor([[1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.], ..., [1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.], [1., 1., 1., ..., 1., 1., 1.]], device='cuda:0', dtype=torch.float16), >>> A_sparse.indices() tensor([[-4370, -4370, -4370, ..., -4370, -4370, -4370], [-4370, -4370, -4370, ..., -4370, -4370, -4370], [-4370, -4370, -4370, ..., -4370, -4370, -4370], ..., [-4370, -4370, -4370, ..., -4370, -4370, -4370], [-4370, -4370, -4370, ..., -4370, -4370, -4370], [-4370, -4370, -4370, ..., -4370, -4370, -4370]], device='cuda:0', dtype=torch.int16)) """ if transposed: warnings.warn( "Setting transpose from `to_sparse_semi_structured` is deprecated " "and will be removed in a future release. " "`SparseSemiStructuredTensor` only support contiguous input tensors.", FutureWarning, stacklevel=2, )
# set from _FORCE_CUTLASS flag SPARSE_SUBCLASS = ( torch.sparse.SparseSemiStructuredTensorCUTLASS if SparseSemiStructuredTensor._FORCE_CUTLASS else torch.sparse.SparseSemiStructuredTensorCUSPARSELT )
return SPARSE_SUBCLASS.from_dense(original_tensor)
class SparseSemiStructuredTensorCUTLASS(SparseSemiStructuredTensor): """ This class implements semi-structured sparsity for the CUTLASS backend.
In this implementation, the specified elements and metadata are stored separately, in packed and meta respectively.
When _FORCE_CUTLASS is set, or when cuSPARSELt is not available, this subclass calls into _sparse_semi_structured_(mm|addmm) and sparse_semi_structured_from_dense for conversion to the compressed format. """
BACKEND = "cutlass" _DTYPE_SHAPE_CONSTRAINTS = { torch.int8: _SEMI_STRUCTURED_SPARSE_CONFIG(16, 128, 16, 16), torch.float16: _SEMI_STRUCTURED_SPARSE_CONFIG(32, 64, 8, 8), torch.bfloat16: _SEMI_STRUCTURED_SPARSE_CONFIG(32, 64, 8, 8), torch.float32: _SEMI_STRUCTURED_SPARSE_CONFIG(32, 32, 4, 4), }
@classmethod def from_dense( cls, original_tensor: torch.Tensor ) -> "SparseSemiStructuredTensorCUTLASS": cls._validate_device_dim_dtype_shape(original_tensor) ( sparse_tensor_cutlass, meta_tensor_cutlass, ) = sparse_semi_structured_from_dense_cutlass(original_tensor) return cls( original_tensor.shape, packed=sparse_tensor_cutlass, meta=meta_tensor_cutlass, packed_t=None, meta_t=None, compressed_swizzled_bitmask=None, requires_grad=original_tensor.requires_grad, )
def to_dense(self): # type: ignore[override] assert self.meta is not None and self.packed is not None return ( sparse_semi_structured_to_dense_cutlass( self.packed, self.meta, ) if self.meta.ndim == 2 else super().to_dense() )
@classmethod def prune_dense_static_sort( cls, original_tensor: torch.Tensor, algorithm="" ) -> "SparseSemiStructuredTensor": """ This function takes in a unpruned dense tensor and runs a (branchless) static sort across a 4x4 tile.
It greedily picks the largest values in the tile, upholding the 2:4 sparsity constraint across both rows and columns. The algorithm used to prune the matrix is implemented in `_sparse_semi_structured_tile`.
Then it creates the packed and meta tensors for the compressed sparse representation of the pruned dense tensor. It also calculates the packed_t and meta_t tensors for the compressed sparse representation of the transposed pruned dense tensor. Since we cannot transpose the compressed representations, we store both for the fw/bw pass respectively.
Finally, this function also computes a compressed swizzled bitmask that encodes the sparsity pattern This can be used in the backward pass to mask the gradients.
[9 1 7 4] [9 0 7 0] [1 2 3 0] [0 2 0 0] [8 3 5 4] -> prune 4x4 tile -> [8 0 0 4] -> pack to CUTLASS semi-structured -> packed [1 2 6 2] [0 0 6 2] -> metadata
-> pack to transposed CUTLASS -> packed_t semi-structured representation -> metadata_t
-> compute swizzled bitmask -> compressed_swizzled_bitmask
The equivalent PyTorch code to create the same five outputs from the dense tensor can be found below: ``` from torch.sparse import SparseSemiStructuredTensorCUTLASS from torch.sparse._semi_structured_conversions import _sparse_semi_structured_tile, _compute_compressed_swizzled_bitmask
pruned = _sparse_semi_structured_tile(dense) packed_cutlass, meta_cutlass = sparse_semi_structured_from_dense_cutlass(pruned) packed_t_cutlass, meta_t_cutlass = sparse_semi_structured_from_dense_cutlass(pruned.t().contiguous()) bitmask = _compute_compressed_swizzled_bitmask(pruned)
SparseSemiStructuredTensorCUTLASS(dense.shape, packed_cutlass, meta_cutlass, packed_t_cutlass, meta_t_cutlass, bitmask) ``` """ # We can either pack to the CUTLASS or cuSPARSELt representation, depending on the use_cutlass flag. ( packed, meta, packed_t, meta_t, compressed_swizzled_bitmask, ) = torch._sparse_semi_structured_tile( original_tensor, algorithm=algorithm, use_cutlass=True )
return cls( original_tensor.shape, packed=packed, meta=meta, packed_t=packed_t, meta_t=meta_t, compressed_swizzled_bitmask=compressed_swizzled_bitmask, requires_grad=False, )
def _mm( self, B: torch.Tensor, *, bias: Optional[torch.Tensor] = None, **kwargs ) -> torch.Tensor: if isinstance(B, SparseSemiStructuredTensor): raise ValueError( "`SparseSemiStructuredTensor @ SparseSemiStructuredTensor` is not supported by the hardware" ) cls_name = self.__class__.__name__ if self.ndim != 2 or B.ndim != 2: raise NotImplementedError( f"`{cls_name}` matmul: Broadcasting is not implemented" ) if self.packed is None or self.meta is None: raise NotImplementedError( f"`{cls_name}` matmul: operation is not supported" ) else: if bias is None: res = torch._sparse_semi_structured_mm(self.packed, self.meta, B) else: res = torch._sparse_semi_structured_addmm( bias, self.packed, self.meta, B ) return res[: self.shape[0]]
class SparseSemiStructuredTensorCUSPARSELT(SparseSemiStructuredTensor): """ The cuSPARSELt backend expects the specified elements and the metadata to be stored in a single tensor: packed = [ specified elements of original tensor | metadata ] For an original tensor of size (m, k) we expect the first m * k // 2 elements to be the kept elements The rest of the tensor is metadata. Since there is only one tensor, we only use the packed and packed_t attributes respectively.
cuSPARSELt also supports transposition fusion, which is necessary for performant 2:4 sparse training, as well as specifying alg_id, a config that affects the performance of the matmul depending on matmul sizes. """
BACKEND = "cusparselt" _DTYPE_SHAPE_CONSTRAINTS = { torch.float8_e4m3fn: _SEMI_STRUCTURED_SPARSE_CONFIG(32, 32, 16, 16), torch.int8: _SEMI_STRUCTURED_SPARSE_CONFIG(32, 32, 16, 16), torch.float16: _SEMI_STRUCTURED_SPARSE_CONFIG(16, 16, 8, 8), torch.bfloat16: _SEMI_STRUCTURED_SPARSE_CONFIG(16, 16, 8, 8), }
@classmethod def from_dense( cls, original_tensor: torch.Tensor ) -> "SparseSemiStructuredTensorCUSPARSELT": cls._validate_device_dim_dtype_shape(original_tensor) return cls( shape=original_tensor.shape, packed=torch._cslt_compress(original_tensor), meta=None, packed_t=None, meta_t=None, compressed_swizzled_bitmask=None, fuse_transpose_cusparselt=SparseSemiStructuredTensor._FUSE_TRANSPOSE, alg_id_cusparselt=SparseSemiStructuredTensor._DEFAULT_ALG_ID, requires_grad=original_tensor.requires_grad, )
@classmethod def prune_dense_static_sort( cls, original_tensor: torch.Tensor, algorithm="" ) -> "SparseSemiStructuredTensor": """ This function does the same thing as described in SparseSemiStructuredCUTLASS, but uses the cuSPASRELt metadata layout and sparse matmul.
The only functional difference is that cuSPARSELt stores `metadata` and `packed` together into a single tensor.
[9 1 7 4] [9 0 7 0] [1 2 3 0] [0 2 0 0] [8 3 5 4] -> prune 4x4 tile -> [8 0 0 4] -> pack to cuSPARSELT semi-structured -> packed [1 2 6 2] [0 0 6 2]
-> pack to transposed cuSPARSELt -> packed_t semi-structured representation
-> compute swizzled bitmask -> compressed_swizzled_bitmask
The equivalent PyTorch code to create the same three outputs from the dense tensor can be found below: ``` from torch.sparse import SparseSemiStructuredTensorCUSPARSELT from torch.sparse._semi_structured_conversions import _sparse_semi_structured_tile, _compute_compressed_swizzled_bitmask
pruned = _sparse_semi_structured_tile(dense) packed_cusparselt = torch._cslt_compress(pruned) packed_t_cusparselt = torch._cslt_compress(pruned.t().contiguous()) bitmask = _compute_compressed_swizzled_bitmask(pruned)
SparseSemiStructuredTensorCUSPARSELT(dense.shape, packed_cutlass, None, packed_t_cutlass, None, bitmask) ``` """ ( packed, meta, packed_t, meta_t, compressed_swizzled_bitmask, ) = torch._sparse_semi_structured_tile( original_tensor, algorithm=algorithm, use_cutlass=False )
return cls( original_tensor.shape, packed=packed, meta=meta, packed_t=packed_t, meta_t=meta_t, compressed_swizzled_bitmask=compressed_swizzled_bitmask, requires_grad=False, )
def _mm( self, B: torch.Tensor, *, bias: Optional[torch.Tensor] = None, **kwargs ) -> torch.Tensor: if isinstance(B, SparseSemiStructuredTensor): raise ValueError( "`SparseSemiStructuredTensor @ SparseSemiStructuredTensor` is not supported by the hardware" ) if self.ndim != 2 or B.ndim != 2: raise NotImplementedError( f"`{self.__class__.__name__}` matmul: Broadcasting is not implemented" ) if B.dtype != self.dtype: raise NotImplementedError( f"`{self.__class__.__name__}` matmul: trying to do `A={tuple(self.shape)} @ B={tuple(B.shape)}`, " f"with A.dtype={self.dtype} and B.dtype={B.dtype}. " "This operation is only supported when A and B have the same data type." ) if bias is not None and bias.dtype != self.dtype: raise NotImplementedError( f"`{self.__class__.__name__}` matmul: trying to do `A={tuple(self.shape)} @ B={tuple(B.shape)} + C`, " f"with A.dtype=B.dtype={self.dtype} and C.dtype={B.dtype}. " "This operation is only supported when A, B and C have the same data type." ) # Force fp8 mm to error to be consistent with torch if self.dtype == torch.float8_e4m3fn: raise NotImplementedError( f"`{self.__class__.__name__}` matmul: trying to do `A={tuple(self.shape)} @ B={tuple(B.shape)}`, " f"with A.dtype=B.dtype={self.dtype}. " "mm is not supported for float8_e4m3fn, please use `torch._scaled_mm` instead." ) if self.packed is None: raise NotImplementedError( f"`{self.__class__.__name__}` matmul: operation is not supported" ) else: res = torch._cslt_sparse_mm( self.packed, B, bias=bias, transpose_result=self.fuse_transpose_cusparselt, alg_id=self.alg_id_cusparselt, ) return res.t() if self.fuse_transpose_cusparselt else res12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559import torchfrom torch._C import _add_docstr, _special # type: ignore[attr-defined]from torch._torch_docs import common_args, multi_dim_common
__all__ = [ "airy_ai", "bessel_j0", "bessel_j1", "bessel_y0", "bessel_y1", "chebyshev_polynomial_t", "chebyshev_polynomial_u", "chebyshev_polynomial_v", "chebyshev_polynomial_w", "digamma", "entr", "erf", "erfc", "erfcx", "erfinv", "exp2", "expit", "expm1", "gammainc", "gammaincc", "gammaln", "hermite_polynomial_h", "hermite_polynomial_he", "i0", "i0e", "i1", "i1e", "laguerre_polynomial_l", "legendre_polynomial_p", "log1p", "log_ndtr", "log_softmax", "logit", "logsumexp", "modified_bessel_i0", "modified_bessel_i1", "modified_bessel_k0", "modified_bessel_k1", "multigammaln", "ndtr", "ndtri", "polygamma", "psi", "round", "shifted_chebyshev_polynomial_t", "shifted_chebyshev_polynomial_u", "shifted_chebyshev_polynomial_v", "shifted_chebyshev_polynomial_w", "scaled_modified_bessel_k0", "scaled_modified_bessel_k1", "sinc", "softmax", "spherical_bessel_j0", "xlog1py", "xlogy", "zeta",]
Tensor = torch.Tensor
entr = _add_docstr( _special.special_entr, r"""entr(input, *, out=None) -> TensorComputes the entropy on :attr:`input` (as defined below), elementwise.
.. math:: \begin{align} \text{entr(x)} = \begin{cases} -x * \ln(x) & x > 0 \\ 0 & x = 0.0 \\ -\infty & x < 0 \end{cases} \end{align}""" + """
Args: input (Tensor): the input tensor.
Keyword args: out (Tensor, optional): the output tensor.
Example::
>>> a = torch.arange(-0.5, 1, 0.5) >>> a tensor([-0.5000, 0.0000, 0.5000]) >>> torch.special.entr(a) tensor([ -inf, 0.0000, 0.3466])""",)
psi = _add_docstr( _special.special_psi, r"""psi(input, *, out=None) -> Tensor
Alias for :func:`torch.special.digamma`.""",)
digamma = _add_docstr( _special.special_digamma, r"""digamma(input, *, out=None) -> Tensor
Computes the logarithmic derivative of the gamma function on `input`.
.. math:: \digamma(x) = \frac{d}{dx} \ln\left(\Gamma\left(x\right)\right) = \frac{\Gamma'(x)}{\Gamma(x)}""" + r"""Args: input (Tensor): the tensor to compute the digamma function on
Keyword args: {out}
.. note:: This function is similar to SciPy's `scipy.special.digamma`.
.. note:: From PyTorch 1.8 onwards, the digamma function returns `-Inf` for `0`. Previously it returned `NaN` for `0`.
Example::
>>> a = torch.tensor([1, 0.5]) >>> torch.special.digamma(a) tensor([-0.5772, -1.9635])
""".format( **common_args ),)
gammaln = _add_docstr( _special.special_gammaln, r"""gammaln(input, *, out=None) -> Tensor
Computes the natural logarithm of the absolute value of the gamma function on :attr:`input`.
.. math:: \text{out}_{i} = \ln \Gamma(|\text{input}_{i}|)""" + """Args: {input}
Keyword args: {out}
Example::
>>> a = torch.arange(0.5, 2, 0.5) >>> torch.special.gammaln(a) tensor([ 0.5724, 0.0000, -0.1208])
""".format( **common_args ),)
polygamma = _add_docstr( _special.special_polygamma, r"""polygamma(n, input, *, out=None) -> Tensor
Computes the :math:`n^{th}` derivative of the digamma function on :attr:`input`.:math:`n \geq 0` is called the order of the polygamma function.
.. math:: \psi^{(n)}(x) = \frac{d^{(n)}}{dx^{(n)}} \psi(x)
.. note:: This function is implemented only for nonnegative integers :math:`n \geq 0`.""" + """Args: n (int): the order of the polygamma function {input}
Keyword args: {out}
Example::
>>> a = torch.tensor([1, 0.5]) >>> torch.special.polygamma(1, a) tensor([1.64493, 4.9348]) >>> torch.special.polygamma(2, a) tensor([ -2.4041, -16.8288]) >>> torch.special.polygamma(3, a) tensor([ 6.4939, 97.4091]) >>> torch.special.polygamma(4, a) tensor([ -24.8863, -771.4742])""".format( **common_args ),)
erf = _add_docstr( _special.special_erf, r"""erf(input, *, out=None) -> Tensor
Computes the error function of :attr:`input`. The error function is defined as follows:
.. math:: \mathrm{erf}(x) = \frac{2}{\sqrt{\pi}} \int_{0}^{x} e^{-t^2} dt""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> torch.special.erf(torch.tensor([0, -1., 10.])) tensor([ 0.0000, -0.8427, 1.0000])""".format( **common_args ),)
erfc = _add_docstr( _special.special_erfc, r"""erfc(input, *, out=None) -> Tensor
Computes the complementary error function of :attr:`input`.The complementary error function is defined as follows:
.. math:: \mathrm{erfc}(x) = 1 - \frac{2}{\sqrt{\pi}} \int_{0}^{x} e^{-t^2} dt""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> torch.special.erfc(torch.tensor([0, -1., 10.])) tensor([ 1.0000, 1.8427, 0.0000])""".format( **common_args ),)
erfcx = _add_docstr( _special.special_erfcx, r"""erfcx(input, *, out=None) -> Tensor
Computes the scaled complementary error function for each element of :attr:`input`.The scaled complementary error function is defined as follows:
.. math:: \mathrm{erfcx}(x) = e^{x^2} \mathrm{erfc}(x)""" + r"""
""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> torch.special.erfcx(torch.tensor([0, -1., 10.])) tensor([ 1.0000, 5.0090, 0.0561])""".format( **common_args ),)
erfinv = _add_docstr( _special.special_erfinv, r"""erfinv(input, *, out=None) -> Tensor
Computes the inverse error function of :attr:`input`.The inverse error function is defined in the range :math:`(-1, 1)` as:
.. math:: \mathrm{erfinv}(\mathrm{erf}(x)) = x""" + r"""
Args: {input}
Keyword args: {out}
Example::
>>> torch.special.erfinv(torch.tensor([0, 0.5, -1.])) tensor([ 0.0000, 0.4769, -inf])""".format( **common_args ),)
logit = _add_docstr( _special.special_logit, r"""logit(input, eps=None, *, out=None) -> Tensor
Returns a new tensor with the logit of the elements of :attr:`input`.:attr:`input` is clamped to [eps, 1 - eps] when eps is not None.When eps is None and :attr:`input` < 0 or :attr:`input` > 1, the function will yields NaN.
.. math:: \begin{align} y_{i} &= \ln(\frac{z_{i}}{1 - z_{i}}) \\ z_{i} &= \begin{cases} x_{i} & \text{if eps is None} \\ \text{eps} & \text{if } x_{i} < \text{eps} \\ x_{i} & \text{if } \text{eps} \leq x_{i} \leq 1 - \text{eps} \\ 1 - \text{eps} & \text{if } x_{i} > 1 - \text{eps} \end{cases} \end{align}""" + r"""Args: {input} eps (float, optional): the epsilon for input clamp bound. Default: ``None``
Keyword args: {out}
Example::
>>> a = torch.rand(5) >>> a tensor([0.2796, 0.9331, 0.6486, 0.1523, 0.6516]) >>> torch.special.logit(a, eps=1e-6) tensor([-0.9466, 2.6352, 0.6131, -1.7169, 0.6261])""".format( **common_args ),)
logsumexp = _add_docstr( _special.special_logsumexp, r"""logsumexp(input, dim, keepdim=False, *, out=None)
Alias for :func:`torch.logsumexp`.""".format( **multi_dim_common ),)
expit = _add_docstr( _special.special_expit, r"""expit(input, *, out=None) -> Tensor
Computes the expit (also known as the logistic sigmoid function) of the elements of :attr:`input`.
.. math:: \text{out}_{i} = \frac{1}{1 + e^{-\text{input}_{i}}}""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> t = torch.randn(4) >>> t tensor([ 0.9213, 1.0887, -0.8858, -1.7683]) >>> torch.special.expit(t) tensor([ 0.7153, 0.7481, 0.2920, 0.1458])""".format( **common_args ),)
exp2 = _add_docstr( _special.special_exp2, r"""exp2(input, *, out=None) -> Tensor
Computes the base two exponential function of :attr:`input`.
.. math:: y_{i} = 2^{x_{i}}
""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> torch.special.exp2(torch.tensor([0, math.log2(2.), 3, 4])) tensor([ 1., 2., 8., 16.])""".format( **common_args ),)
expm1 = _add_docstr( _special.special_expm1, r"""expm1(input, *, out=None) -> Tensor
Computes the exponential of the elements minus 1of :attr:`input`.
.. math:: y_{i} = e^{x_{i}} - 1
.. note:: This function provides greater precision than exp(x) - 1 for small values of x.
""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> torch.special.expm1(torch.tensor([0, math.log(2.)])) tensor([ 0., 1.])""".format( **common_args ),)
xlog1py = _add_docstr( _special.special_xlog1py, r"""xlog1py(input, other, *, out=None) -> Tensor
Computes ``input * log1p(other)`` with the following cases.
.. math:: \text{out}_{i} = \begin{cases} \text{NaN} & \text{if } \text{other}_{i} = \text{NaN} \\ 0 & \text{if } \text{input}_{i} = 0.0 \text{ and } \text{other}_{i} != \text{NaN} \\ \text{input}_{i} * \text{log1p}(\text{other}_{i})& \text{otherwise} \end{cases}
Similar to SciPy's `scipy.special.xlog1py`.
""" + r"""
Args: input (Number or Tensor) : Multiplier other (Number or Tensor) : Argument
.. note:: At least one of :attr:`input` or :attr:`other` must be a tensor.
Keyword args: {out}
Example::
>>> x = torch.zeros(5,) >>> y = torch.tensor([-1, 0, 1, float('inf'), float('nan')]) >>> torch.special.xlog1py(x, y) tensor([0., 0., 0., 0., nan]) >>> x = torch.tensor([1, 2, 3]) >>> y = torch.tensor([3, 2, 1]) >>> torch.special.xlog1py(x, y) tensor([1.3863, 2.1972, 2.0794]) >>> torch.special.xlog1py(x, 4) tensor([1.6094, 3.2189, 4.8283]) >>> torch.special.xlog1py(2, y) tensor([2.7726, 2.1972, 1.3863])""".format( **common_args ),)
xlogy = _add_docstr( _special.special_xlogy, r"""xlogy(input, other, *, out=None) -> Tensor
Computes ``input * log(other)`` with the following cases.
.. math:: \text{out}_{i} = \begin{cases} \text{NaN} & \text{if } \text{other}_{i} = \text{NaN} \\ 0 & \text{if } \text{input}_{i} = 0.0 \\ \text{input}_{i} * \log{(\text{other}_{i})} & \text{otherwise} \end{cases}
Similar to SciPy's `scipy.special.xlogy`.
""" + r"""
Args: input (Number or Tensor) : Multiplier other (Number or Tensor) : Argument
.. note:: At least one of :attr:`input` or :attr:`other` must be a tensor.
Keyword args: {out}
Example::
>>> x = torch.zeros(5,) >>> y = torch.tensor([-1, 0, 1, float('inf'), float('nan')]) >>> torch.special.xlogy(x, y) tensor([0., 0., 0., 0., nan]) >>> x = torch.tensor([1, 2, 3]) >>> y = torch.tensor([3, 2, 1]) >>> torch.special.xlogy(x, y) tensor([1.0986, 1.3863, 0.0000]) >>> torch.special.xlogy(x, 4) tensor([1.3863, 2.7726, 4.1589]) >>> torch.special.xlogy(2, y) tensor([2.1972, 1.3863, 0.0000])""".format( **common_args ),)
i0 = _add_docstr( _special.special_i0, r"""i0(input, *, out=None) -> Tensor
Computes the zeroth order modified Bessel function of the first kind for each element of :attr:`input`.
.. math:: \text{out}_{i} = I_0(\text{input}_{i}) = \sum_{k=0}^{\infty} \frac{(\text{input}_{i}^2/4)^k}{(k!)^2}
""" + r"""Args: input (Tensor): the input tensor
Keyword args: {out}
Example::
>>> torch.i0(torch.arange(5, dtype=torch.float32)) tensor([ 1.0000, 1.2661, 2.2796, 4.8808, 11.3019])
""".format( **common_args ),)
i0e = _add_docstr( _special.special_i0e, r"""i0e(input, *, out=None) -> TensorComputes the exponentially scaled zeroth order modified Bessel function of the first kind (as defined below)for each element of :attr:`input`.
.. math:: \text{out}_{i} = \exp(-|x|) * i0(x) = \exp(-|x|) * \sum_{k=0}^{\infty} \frac{(\text{input}_{i}^2/4)^k}{(k!)^2}
""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> torch.special.i0e(torch.arange(5, dtype=torch.float32)) tensor([1.0000, 0.4658, 0.3085, 0.2430, 0.2070])""".format( **common_args ),)
i1 = _add_docstr( _special.special_i1, r"""i1(input, *, out=None) -> TensorComputes the first order modified Bessel function of the first kind (as defined below)for each element of :attr:`input`.
.. math:: \text{out}_{i} = \frac{(\text{input}_{i})}{2} * \sum_{k=0}^{\infty} \frac{(\text{input}_{i}^2/4)^k}{(k!) * (k+1)!}
""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> torch.special.i1(torch.arange(5, dtype=torch.float32)) tensor([0.0000, 0.5652, 1.5906, 3.9534, 9.7595])""".format( **common_args ),)
i1e = _add_docstr( _special.special_i1e, r"""i1e(input, *, out=None) -> TensorComputes the exponentially scaled first order modified Bessel function of the first kind (as defined below)for each element of :attr:`input`.
.. math:: \text{out}_{i} = \exp(-|x|) * i1(x) = \exp(-|x|) * \frac{(\text{input}_{i})}{2} * \sum_{k=0}^{\infty} \frac{(\text{input}_{i}^2/4)^k}{(k!) * (k+1)!}
""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> torch.special.i1e(torch.arange(5, dtype=torch.float32)) tensor([0.0000, 0.2079, 0.2153, 0.1968, 0.1788])""".format( **common_args ),)
ndtr = _add_docstr( _special.special_ndtr, r"""ndtr(input, *, out=None) -> TensorComputes the area under the standard Gaussian probability density function,integrated from minus infinity to :attr:`input`, elementwise.
.. math:: \text{ndtr}(x) = \frac{1}{\sqrt{2 \pi}}\int_{-\infty}^{x} e^{-\frac{1}{2}t^2} dt
""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> torch.special.ndtr(torch.tensor([-3., -2, -1, 0, 1, 2, 3])) tensor([0.0013, 0.0228, 0.1587, 0.5000, 0.8413, 0.9772, 0.9987])""".format( **common_args ),)
ndtri = _add_docstr( _special.special_ndtri, r"""ndtri(input, *, out=None) -> TensorComputes the argument, x, for which the area under the Gaussian probability density function(integrated from minus infinity to x) is equal to :attr:`input`, elementwise.
.. math:: \text{ndtri}(p) = \sqrt{2}\text{erf}^{-1}(2p - 1)
.. note:: Also known as quantile function for Normal Distribution.
""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> torch.special.ndtri(torch.tensor([0, 0.25, 0.5, 0.75, 1])) tensor([ -inf, -0.6745, 0.0000, 0.6745, inf])""".format( **common_args ),)
log_ndtr = _add_docstr( _special.special_log_ndtr, r"""log_ndtr(input, *, out=None) -> TensorComputes the log of the area under the standard Gaussian probability density function,integrated from minus infinity to :attr:`input`, elementwise.
.. math:: \text{log\_ndtr}(x) = \log\left(\frac{1}{\sqrt{2 \pi}}\int_{-\infty}^{x} e^{-\frac{1}{2}t^2} dt \right)
""" + r"""Args: {input}
Keyword args: {out}
Example::
>>> torch.special.log_ndtr(torch.tensor([-3., -2, -1, 0, 1, 2, 3])) tensor([-6.6077 -3.7832 -1.841 -0.6931 -0.1728 -0.023 -0.0014])""".format( **common_args ),)
log1p = _add_docstr( _special.special_log1p, r"""log1p(input, *, out=None) -> Tensor
Alias for :func:`torch.log1p`.""",)
sinc = _add_docstr( _special.special_sinc, r"""sinc(input, *, out=None) -> Tensor
Computes the normalized sinc of :attr:`input.`
.. math:: \text{out}_{i} = \begin{cases} 1, & \text{if}\ \text{input}_{i}=0 \\ \sin(\pi \text{input}_{i}) / (\pi \text{input}_{i}), & \text{otherwise} \end{cases}""" + r"""
Args: {input}
Keyword args: {out}
Example::
>>> t = torch.randn(4) >>> t tensor([ 0.2252, -0.2948, 1.0267, -1.1566]) >>> torch.special.sinc(t) tensor([ 0.9186, 0.8631, -0.0259, -0.1300])""".format( **common_args ),)
round = _add_docstr( _special.special_round, r"""round(input, *, out=None) -> Tensor
Alias for :func:`torch.round`.""",)
softmax = _add_docstr( _special.special_softmax, r"""softmax(input, dim, *, dtype=None) -> Tensor
Computes the softmax function.
Softmax is defined as:
:math:`\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}`
It is applied to all slices along dim, and will re-scale them so that the elementslie in the range `[0, 1]` and sum to 1.
Args: input (Tensor): input dim (int): A dimension along which softmax will be computed. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. If specified, the input tensor is cast to :attr:`dtype` before the operation is performed. This is useful for preventing data type overflows. Default: None.
Examples:: >>> t = torch.ones(2, 2) >>> torch.special.softmax(t, 0) tensor([[0.5000, 0.5000], [0.5000, 0.5000]])
""",)
log_softmax = _add_docstr( _special.special_log_softmax, r"""log_softmax(input, dim, *, dtype=None) -> Tensor
Computes softmax followed by a logarithm.
While mathematically equivalent to log(softmax(x)), doing these twooperations separately is slower and numerically unstable. This functionis computed as:
.. math:: \text{log\_softmax}(x_{i}) = \log\left(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} \right)""" + r"""
Args: input (Tensor): input dim (int): A dimension along which log_softmax will be computed. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. If specified, the input tensor is cast to :attr:`dtype` before the operation is performed. This is useful for preventing data type overflows. Default: None.
Example::
>>> t = torch.ones(2, 2) >>> torch.special.log_softmax(t, 0) tensor([[-0.6931, -0.6931], [-0.6931, -0.6931]])""",)
zeta = _add_docstr( _special.special_zeta, r"""zeta(input, other, *, out=None) -> Tensor
Computes the Hurwitz zeta function, elementwise.
.. math:: \zeta(x, q) = \sum_{k=0}^{\infty} \frac{1}{(k + q)^x}
""" + r"""Args: input (Tensor): the input tensor corresponding to `x`. other (Tensor): the input tensor corresponding to `q`.
.. note:: The Riemann zeta function corresponds to the case when `q = 1`
Keyword args: {out}
Example::
>>> x = torch.tensor([2., 4.]) >>> torch.special.zeta(x, 1) tensor([1.6449, 1.0823]) >>> torch.special.zeta(x, torch.tensor([1., 2.])) tensor([1.6449, 0.0823]) >>> torch.special.zeta(2, torch.tensor([1., 2.])) tensor([1.6449, 0.6449])""".format( **common_args ),)
multigammaln = _add_docstr( _special.special_multigammaln, r"""multigammaln(input, p, *, out=None) -> Tensor
Computes the `multivariate log-gamma function<https://en.wikipedia.org/wiki/Multivariate_gamma_function>`_ with dimension:math:`p` element-wise, given by
.. math:: \log(\Gamma_{p}(a)) = C + \displaystyle \sum_{i=1}^{p} \log\left(\Gamma\left(a - \frac{i - 1}{2}\right)\right)
where :math:`C = \log(\pi) \cdot \frac{p (p - 1)}{4}` and :math:`\Gamma(-)` is the Gamma function.
All elements must be greater than :math:`\frac{p - 1}{2}`, otherwise the behavior is undefined.""" + """
Args: input (Tensor): the tensor to compute the multivariate log-gamma function p (int): the number of dimensions
Keyword args: {out}
Example::
>>> a = torch.empty(2, 3).uniform_(1, 2) >>> a tensor([[1.6835, 1.8474, 1.1929], [1.0475, 1.7162, 1.4180]]) >>> torch.special.multigammaln(a, 2) tensor([[0.3928, 0.4007, 0.7586], [1.0311, 0.3901, 0.5049]])""".format( **common_args ),)
gammainc = _add_docstr( _special.special_gammainc, r"""gammainc(input, other, *, out=None) -> Tensor
Computes the regularized lower incomplete gamma function:
.. math:: \text{out}_{i} = \frac{1}{\Gamma(\text{input}_i)} \int_0^{\text{other}_i} t^{\text{input}_i-1} e^{-t} dt
where both :math:`\text{input}_i` and :math:`\text{other}_i` are weakly positiveand at least one is strictly positive.If both are zero or either is negative then :math:`\text{out}_i=\text{nan}`.:math:`\Gamma(\cdot)` in the equation above is the gamma function,
.. math:: \Gamma(\text{input}_i) = \int_0^\infty t^{(\text{input}_i-1)} e^{-t} dt.
See :func:`torch.special.gammaincc` and :func:`torch.special.gammaln` for related functions.
Supports :ref:`broadcasting to a common shape <broadcasting-semantics>`and float inputs.
.. note:: The backward pass with respect to :attr:`input` is not yet supported. Please open an issue on PyTorch's Github to request it.
""" + r"""Args: input (Tensor): the first non-negative input tensor other (Tensor): the second non-negative input tensor
Keyword args: {out}
Example::
>>> a1 = torch.tensor([4.0]) >>> a2 = torch.tensor([3.0, 4.0, 5.0]) >>> a = torch.special.gammaincc(a1, a2) tensor([0.3528, 0.5665, 0.7350]) tensor([0.3528, 0.5665, 0.7350]) >>> b = torch.special.gammainc(a1, a2) + torch.special.gammaincc(a1, a2) tensor([1., 1., 1.])
""".format( **common_args ),)
gammaincc = _add_docstr( _special.special_gammaincc, r"""gammaincc(input, other, *, out=None) -> Tensor
Computes the regularized upper incomplete gamma function:
.. math:: \text{out}_{i} = \frac{1}{\Gamma(\text{input}_i)} \int_{\text{other}_i}^{\infty} t^{\text{input}_i-1} e^{-t} dt
where both :math:`\text{input}_i` and :math:`\text{other}_i` are weakly positiveand at least one is strictly positive.If both are zero or either is negative then :math:`\text{out}_i=\text{nan}`.:math:`\Gamma(\cdot)` in the equation above is the gamma function,
.. math:: \Gamma(\text{input}_i) = \int_0^\infty t^{(\text{input}_i-1)} e^{-t} dt.
See :func:`torch.special.gammainc` and :func:`torch.special.gammaln` for related functions.
Supports :ref:`broadcasting to a common shape <broadcasting-semantics>`and float inputs.
.. note:: The backward pass with respect to :attr:`input` is not yet supported. Please open an issue on PyTorch's Github to request it.
""" + r"""Args: input (Tensor): the first non-negative input tensor other (Tensor): the second non-negative input tensor
Keyword args: {out}
Example::
>>> a1 = torch.tensor([4.0]) >>> a2 = torch.tensor([3.0, 4.0, 5.0]) >>> a = torch.special.gammaincc(a1, a2) tensor([0.6472, 0.4335, 0.2650]) >>> b = torch.special.gammainc(a1, a2) + torch.special.gammaincc(a1, a2) tensor([1., 1., 1.])
""".format( **common_args ),)
airy_ai = _add_docstr( _special.special_airy_ai, r"""airy_ai(input, *, out=None) -> Tensor
Airy function :math:`\text{Ai}\left(\text{input}\right)`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)
bessel_j0 = _add_docstr( _special.special_bessel_j0, r"""bessel_j0(input, *, out=None) -> Tensor
Bessel function of the first kind of order :math:`0`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)
bessel_j1 = _add_docstr( _special.special_bessel_j1, r"""bessel_j1(input, *, out=None) -> Tensor
Bessel function of the first kind of order :math:`1`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)
bessel_y0 = _add_docstr( _special.special_bessel_y0, r"""bessel_y0(input, *, out=None) -> Tensor
Bessel function of the second kind of order :math:`0`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)
bessel_y1 = _add_docstr( _special.special_bessel_y1, r"""bessel_y1(input, *, out=None) -> Tensor
Bessel function of the second kind of order :math:`1`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)
chebyshev_polynomial_t = _add_docstr( _special.special_chebyshev_polynomial_t, r"""chebyshev_polynomial_t(input, n, *, out=None) -> Tensor
Chebyshev polynomial of the first kind :math:`T_{n}(\text{input})`.
If :math:`n = 0`, :math:`1` is returned. If :math:`n = 1`, :math:`\text{input}`is returned. If :math:`n < 6` or :math:`|\text{input}| > 1` the recursion:
.. math:: T_{n + 1}(\text{input}) = 2 \times \text{input} \times T_{n}(\text{input}) - T_{n - 1}(\text{input})
is evaluated. Otherwise, the explicit trigonometric formula:
.. math:: T_{n}(\text{input}) = \text{cos}(n \times \text{arccos}(x))
is evaluated.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
chebyshev_polynomial_u = _add_docstr( _special.special_chebyshev_polynomial_u, r"""chebyshev_polynomial_u(input, n, *, out=None) -> Tensor
Chebyshev polynomial of the second kind :math:`U_{n}(\text{input})`.
If :math:`n = 0`, :math:`1` is returned. If :math:`n = 1`,:math:`2 \times \text{input}` is returned. If :math:`n < 6` or:math:`|\text{input}| > 1`, the recursion:
.. math:: U_{n + 1}(\text{input}) = 2 \times \text{input} \times U_{n}(\text{input}) - U_{n - 1}(\text{input})
is evaluated. Otherwise, the explicit trigonometric formula:
.. math:: \frac{\text{sin}((n + 1) \times \text{arccos}(\text{input}))}{\text{sin}(\text{arccos}(\text{input}))}
is evaluated.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
chebyshev_polynomial_v = _add_docstr( _special.special_chebyshev_polynomial_v, r"""chebyshev_polynomial_v(input, n, *, out=None) -> Tensor
Chebyshev polynomial of the third kind :math:`V_{n}^{\ast}(\text{input})`.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
chebyshev_polynomial_w = _add_docstr( _special.special_chebyshev_polynomial_w, r"""chebyshev_polynomial_w(input, n, *, out=None) -> Tensor
Chebyshev polynomial of the fourth kind :math:`W_{n}^{\ast}(\text{input})`.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
hermite_polynomial_h = _add_docstr( _special.special_hermite_polynomial_h, r"""hermite_polynomial_h(input, n, *, out=None) -> Tensor
Physicist's Hermite polynomial :math:`H_{n}(\text{input})`.
If :math:`n = 0`, :math:`1` is returned. If :math:`n = 1`, :math:`\text{input}`is returned. Otherwise, the recursion:
.. math:: H_{n + 1}(\text{input}) = 2 \times \text{input} \times H_{n}(\text{input}) - H_{n - 1}(\text{input})
is evaluated.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
hermite_polynomial_he = _add_docstr( _special.special_hermite_polynomial_he, r"""hermite_polynomial_he(input, n, *, out=None) -> Tensor
Probabilist's Hermite polynomial :math:`He_{n}(\text{input})`.
If :math:`n = 0`, :math:`1` is returned. If :math:`n = 1`, :math:`\text{input}`is returned. Otherwise, the recursion:
.. math:: He_{n + 1}(\text{input}) = 2 \times \text{input} \times He_{n}(\text{input}) - He_{n - 1}(\text{input})
is evaluated.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
laguerre_polynomial_l = _add_docstr( _special.special_laguerre_polynomial_l, r"""laguerre_polynomial_l(input, n, *, out=None) -> Tensor
Laguerre polynomial :math:`L_{n}(\text{input})`.
If :math:`n = 0`, :math:`1` is returned. If :math:`n = 1`, :math:`\text{input}`is returned. Otherwise, the recursion:
.. math:: L_{n + 1}(\text{input}) = 2 \times \text{input} \times L_{n}(\text{input}) - L_{n - 1}(\text{input})
is evaluated.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
legendre_polynomial_p = _add_docstr( _special.special_legendre_polynomial_p, r"""legendre_polynomial_p(input, n, *, out=None) -> Tensor
Legendre polynomial :math:`P_{n}(\text{input})`.
If :math:`n = 0`, :math:`1` is returned. If :math:`n = 1`, :math:`\text{input}`is returned. Otherwise, the recursion:
.. math:: P_{n + 1}(\text{input}) = 2 \times \text{input} \times P_{n}(\text{input}) - P_{n - 1}(\text{input})
is evaluated.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
modified_bessel_i0 = _add_docstr( _special.special_modified_bessel_i0, r"""modified_bessel_i0(input, *, out=None) -> Tensor
Modified Bessel function of the first kind of order :math:`0`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)
modified_bessel_i1 = _add_docstr( _special.special_modified_bessel_i1, r"""modified_bessel_i1(input, *, out=None) -> Tensor
Modified Bessel function of the first kind of order :math:`1`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)
modified_bessel_k0 = _add_docstr( _special.special_modified_bessel_k0, r"""modified_bessel_k0(input, *, out=None) -> Tensor
Modified Bessel function of the second kind of order :math:`0`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)
modified_bessel_k1 = _add_docstr( _special.special_modified_bessel_k1, r"""modified_bessel_k1(input, *, out=None) -> Tensor
Modified Bessel function of the second kind of order :math:`1`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)
scaled_modified_bessel_k0 = _add_docstr( _special.special_scaled_modified_bessel_k0, r"""scaled_modified_bessel_k0(input, *, out=None) -> Tensor
Scaled modified Bessel function of the second kind of order :math:`0`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)
scaled_modified_bessel_k1 = _add_docstr( _special.special_scaled_modified_bessel_k1, r"""scaled_modified_bessel_k1(input, *, out=None) -> Tensor
Scaled modified Bessel function of the second kind of order :math:`1`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)
shifted_chebyshev_polynomial_t = _add_docstr( _special.special_shifted_chebyshev_polynomial_t, r"""shifted_chebyshev_polynomial_t(input, n, *, out=None) -> Tensor
Chebyshev polynomial of the first kind :math:`T_{n}^{\ast}(\text{input})`.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
shifted_chebyshev_polynomial_u = _add_docstr( _special.special_shifted_chebyshev_polynomial_u, r"""shifted_chebyshev_polynomial_u(input, n, *, out=None) -> Tensor
Chebyshev polynomial of the second kind :math:`U_{n}^{\ast}(\text{input})`.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
shifted_chebyshev_polynomial_v = _add_docstr( _special.special_shifted_chebyshev_polynomial_v, r"""shifted_chebyshev_polynomial_v(input, n, *, out=None) -> Tensor
Chebyshev polynomial of the third kind :math:`V_{n}^{\ast}(\text{input})`.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
shifted_chebyshev_polynomial_w = _add_docstr( _special.special_shifted_chebyshev_polynomial_w, r"""shifted_chebyshev_polynomial_w(input, n, *, out=None) -> Tensor
Chebyshev polynomial of the fourth kind :math:`W_{n}^{\ast}(\text{input})`.
""" + r"""Args: {input} n (Tensor): Degree of the polynomial.
Keyword args: {out}""".format( **common_args ),)
spherical_bessel_j0 = _add_docstr( _special.special_spherical_bessel_j0, r"""spherical_bessel_j0(input, *, out=None) -> Tensor
Spherical Bessel function of the first kind of order :math:`0`.
""" + r"""Args: {input}
Keyword args: {out}""".format( **common_args ),)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551# mypy: allow-untyped-defs
from __future__ import annotations
import collectionsimport copyimport functoolsimport ioimport threadingimport warningsfrom typing import Any, cast, Optional as _Optional, TYPE_CHECKING, TypeVar, Unionfrom typing_extensions import Self
import torchfrom torch._utils import _to, _typefrom torch.types import _bool, _int, Storage
if TYPE_CHECKING: from torch._prims_common import DeviceLikeType
__all__ = ["TypedStorage", "UntypedStorage"]
try: import numpy as np
HAS_NUMPY = Trueexcept ModuleNotFoundError: HAS_NUMPY = False np = None # type: ignore[assignment]
_share_memory_lock = threading.Lock()_share_memory_map: dict[int, threading.RLock] = {}
T = TypeVar("T", bound="Union[_StorageBase, TypedStorage]")
class _StorageBase: _cdata: Any is_sparse: _bool = False is_sparse_csr: _bool = False device: torch.device # Used when # (1) stashing FakeTensor device onto storage in torch.serialization.skip_data # (2) stashing device onto storage to propagate to FakeTensor when torch.load under FakeTensorMode _fake_device: _Optional[torch.device] = None # Used when loading with FakeTensorMode to give information about offset of storage in torch.saved-file _checkpoint_offset: _Optional[int] = None
def __init__(self, *args, **kwargs): pass
def __len__(self) -> _int: raise NotImplementedError
def __getitem__(self, idx): raise NotImplementedError
def __setitem__(self, *args, **kwargs): raise NotImplementedError
def copy_(self, source: T, non_blocking: _Optional[_bool] = None) -> T: raise NotImplementedError
def new(self) -> Union[_StorageBase, TypedStorage]: raise NotImplementedError
def nbytes(self) -> _int: raise NotImplementedError
def size(self) -> _int: return self.nbytes()
def type( self, dtype: _Optional[str] = None, non_blocking: _bool = False ) -> Union[_StorageBase, TypedStorage]: return _type(self, dtype, non_blocking)
def cuda( self, device=None, non_blocking=False ) -> Union[_StorageBase, TypedStorage]: """Returns a copy of this object in CUDA memory.
If this object is already in CUDA memory and on the correct device, then no copy is performed and the original object is returned.
Args: device (int): The destination GPU id. Defaults to the current device. non_blocking (bool): If ``True`` and the source is in pinned memory, the copy will be asynchronous with respect to the host. Otherwise, the argument has no effect. """ device2 = torch.device("cuda", device) if device else torch.device("cuda") return self.to(device=device2, non_blocking=non_blocking)
def hpu(self, device=None, non_blocking=False) -> Union[_StorageBase, TypedStorage]: """Returns a copy of this object in HPU memory.
If this object is already in HPU memory and on the correct device, then no copy is performed and the original object is returned.
Args: device (int): The destination HPU id. Defaults to the current device. non_blocking (bool): If ``True`` and the source is in pinned memory, the copy will be asynchronous with respect to the host. Otherwise, the argument has no effect. """ device2 = torch.device("hpu", device) if device else torch.device("hpu") return self.to(device=device2, non_blocking=non_blocking)
def element_size(self) -> _int: raise NotImplementedError
def get_device(self) -> _int: return self.device.index
def data_ptr(self) -> _int: raise NotImplementedError
def resizable(self) -> _bool: raise NotImplementedError
# Defined in torch/csrc/generic/StorageSharing.cpp def _share_filename_cpu_(self, *args, **kwargs): raise NotImplementedError
def _share_fd_cpu_(self, *args, **kwargs): raise NotImplementedError
@classmethod def _new_using_filename_cpu(cls, size: _int) -> Self: raise NotImplementedError
@classmethod def _new_using_fd_cpu(cls, size: _int) -> Self: raise NotImplementedError
@classmethod def from_buffer(cls, *args, **kwargs) -> Self: raise NotImplementedError
@classmethod def _new_shared_filename_cpu( cls, manager, obj, size, *, device=None, dtype=None, ) -> Self: raise NotImplementedError
@classmethod def _release_ipc_counter(cls, *args, device=None, **kwargs): return cls._release_ipc_counter_cuda(*args, **kwargs)
@classmethod def _release_ipc_counter_cuda(cls, *args, **kwargs) -> Self: raise NotImplementedError
@classmethod def _new_with_weak_ptr(cls, *args, **kwargs) -> Self: raise NotImplementedError
def _shared_decref(self) -> Union[_StorageBase, TypedStorage]: raise NotImplementedError
def _write_file(self, *args, **kwargs): raise NotImplementedError
def resize_(self, size: _int): raise NotImplementedError
def _weak_ref(self, *args, **kwargs) -> Union[_StorageBase, TypedStorage]: raise NotImplementedError
def _set_from_file(self, *args, **kwargs): raise NotImplementedError
def _set_cdata(self, *args, **kwargs): raise NotImplementedError
def _share_cuda_(self, *args, **kwargs): raise NotImplementedError
def is_shared(self) -> _bool: raise NotImplementedError
@classmethod def _new_shared_cuda(cls, *args, **kwargs) -> Self: raise NotImplementedError
def _shared_incref(self, *args, **kwargs): raise NotImplementedError
@classmethod def _free_weak_ref(cls, *args, **kwargs): raise NotImplementedError
@property def is_cuda(self): raise NotImplementedError
@property def is_hpu(self): raise NotImplementedError
@classmethod def from_file(cls, filename, shared, nbytes) -> Union[_StorageBase, TypedStorage]: raise NotImplementedError
@classmethod def _expired(cls, *args, **kwargs) -> Union[_StorageBase, TypedStorage]: raise NotImplementedError
def _byteswap(self, *args, **kwargs): raise NotImplementedError
def _get_filename(self, *args, **kwargs) -> _Optional[str]: raise NotImplementedError
def __repr__(self): info_str = f"[{torch.typename(self)}(device={self.device}) of size {len(self)}]" if self.device.type == "meta": return "...\n" + info_str data_str = " " + "\n ".join(str(self[i]) for i in range(self.size())) return data_str + "\n" + info_str
def __iter__(self): return iter(self[i] for i in range(self.size()))
def __copy__(self): return self.clone()
def __deepcopy__(self, memo): memo = memo.setdefault("torch", {}) if self._cdata in memo: return memo[self._cdata] new_storage = self.clone() memo[self._cdata] = new_storage return new_storage
def __reduce__(self): b = io.BytesIO() torch.save(self, b, _use_new_zipfile_serialization=False) return (_load_from_bytes, (b.getvalue(),))
def __sizeof__(self): return super().__sizeof__() + self.size()
def clone(self): """Return a copy of this storage.""" return type(self)(self.nbytes(), device=self.device).copy_(self)
def tolist(self): """Return a list containing the elements of this storage.""" return list(self)
def cpu(self): """Return a CPU copy of this storage if it's not already on the CPU.""" if self.device.type != "cpu": return torch.UntypedStorage(self.size()).copy_(self, False) return self
def mps(self): """Return a MPS copy of this storage if it's not already on the MPS.""" if self.device.type != "mps": return torch.UntypedStorage(self.size(), device="mps").copy_(self, False) return self
def _to(self, dtype): if not isinstance(dtype, torch.dtype): raise TypeError(f"Argument 'dtype' must be torch.dtype, not {type(dtype)}") storage = ( torch.tensor([], dtype=torch.uint8, device=self.device) .set_(cast(Storage, self)) .to(dtype) ._typed_storage() ) if storage.data_ptr() == self.data_ptr(): storage = storage.clone() return storage
def to(self, *, device: DeviceLikeType, non_blocking: _bool = False): if not isinstance(device, torch.device): device = torch.device(device) return _to(self, device, non_blocking)
def double(self): """Casts this storage to double type.""" return self._to(torch.double)
def float(self): """Casts this storage to float type.""" return self._to(torch.float)
def half(self): """Casts this storage to half type.""" return self._to(torch.half)
def long(self): """Casts this storage to long type.""" return self._to(torch.long)
def int(self): """Casts this storage to int type.""" return self._to(torch.int)
def short(self): """Casts this storage to short type.""" return self._to(torch.short)
def char(self): """Casts this storage to char type.""" return self._to(torch.int8)
def byte(self): """Casts this storage to byte type.""" return self._to(torch.uint8)
def bool(self): """Casts this storage to bool type.""" return self._to(torch.bool)
def bfloat16(self): """Casts this storage to bfloat16 type.""" return self._to(torch.bfloat16)
def complex_double(self): """Casts this storage to complex double type.""" return self._to(torch.cdouble)
def complex_float(self): """Casts this storage to complex float type.""" return self._to(torch.cfloat)
def float8_e5m2(self): """Casts this storage to float8_e5m2 type""" return self._to(torch.float8_e5m2)
def float8_e4m3fn(self): """Casts this storage to float8_e4m3fn type""" return self._to(torch.float8_e4m3fn)
def float8_e5m2fnuz(self): """Casts this storage to float8_e5m2fnuz type""" return self._to(torch.float8_e5m2fnuz)
def float8_e4m3fnuz(self): """Casts this storage to float8_e4m3fnuz type""" return self._to(torch.float8_e4m3fnuz)
def is_pinned(self, device: Union[str, torch.device] = "cuda"): r"""Determine whether the CPU storage is already pinned on device.
Args: device (str or torch.device): The device to pin memory on (default: ``'cuda'``). This argument is discouraged and subject to deprecated.
Returns: A boolean variable. """ return ( torch.tensor([], dtype=torch.uint8, device=self.device) .set_(cast(Storage, self)) .is_pinned(device) )
def pin_memory(self, device: Union[str, torch.device] = "cuda"): r"""Copy the CPU storage to pinned memory, if it's not already pinned.
Args: device (str or torch.device): The device to pin memory on (default: ``'cuda'``). This argument is discouraged and subject to deprecated.
Returns: A pinned CPU storage. """ if self.device.type != "cpu": raise TypeError(f"cannot pin '{self.type()}' only CPU memory can be pinned")
pinned_tensor = ( torch.tensor([], dtype=torch.uint8, device=self.device) .set_(cast(Storage, self)) .pin_memory(device) ) return pinned_tensor.untyped_storage()
def share_memory_(self): """See :meth:`torch.UntypedStorage.share_memory_`""" from torch.multiprocessing import get_sharing_strategy
if self.device.type in ["cuda", torch._C._get_privateuse1_backend_name()]: pass # CUDA or PrivateUse1 doesn't use POSIX shared memory elif get_sharing_strategy() == "file_system": self._share_filename_cpu_() else: self._share_fd_cpu_() return self
@classmethod def _new_shared(cls, size, *, device="cpu"): """Create a new storage in shared memory with the same data type.""" from torch.multiprocessing import get_sharing_strategy
device = torch.device(device) if device.type in ["cuda", torch._C._get_privateuse1_backend_name(), "hpu"]: return cls(size, device=device) elif get_sharing_strategy() == "file_system": return cls._new_using_filename_cpu(size) else: return cls._new_using_fd_cpu(size)
def untyped(self): return self
def byteswap(self, dtype): """Swap bytes in underlying data.""" elem_size = torch._utils._element_size(dtype) # for complex types, don't swap first and second numbers if dtype.is_complex: elem_size = max(int(elem_size / 2), 1) self._byteswap(elem_size)
def _share_memory_lock_protected(fn): @functools.wraps(fn) def wrapper(self, *args, **kwargs): to_free = None to_wait = None with _share_memory_lock: key = self._cdata if key in _share_memory_map: to_wait = _share_memory_map[key] else: _share_memory_map[key] = threading.RLock() _share_memory_map[key].acquire() to_free = key
# If we're already in the process of sharing the storage, wait # for it to be done. if to_wait is not None: with to_wait: pass
try: return fn(self, *args, **kwargs) finally: # If we acquired the storage lock here and we're done working on it # we can now release it and free the entry. if to_free is not None: # Ensure that the cdata from the storage didn't change and only # the data_ptr did. assert self._cdata == to_free with _share_memory_lock: _share_memory_map[to_free].release() del _share_memory_map[to_free]
return wrapper
class UntypedStorage(torch._C.StorageBase, _StorageBase): def __getitem__(self, *args, **kwargs): if self.device.type == "meta": raise NotImplementedError("Not available for 'meta' device type") return super().__getitem__(*args, **kwargs)
@property def is_cuda(self): return self.device.type == "cuda"
@property def is_hpu(self): return self.device.type == "hpu"
@property def filename(self) -> _Optional[str]: """Returns the file name associated with this storage.
The file name will be a string if the storage is on CPU and was created via :meth:`~torch.from_file()` with ``shared`` as ``True``. This attribute is ``None`` otherwise. """ return self._get_filename()
@_share_memory_lock_protected def share_memory_(self, *args, **kwargs): """ Moves the storage to shared memory.
This is a no-op for storages already in shared memory and for CUDA storages, which do not need to be moved for sharing across processes. Storages in shared memory cannot be resized.
Note that to mitigate issues like `this <https://github.com/pytorch/pytorch/issues/95606>`_ it is thread safe to call this function from multiple threads on the same object. It is NOT thread safe though to call any other function on self without proper synchronization. Please see :doc:`/notes/multiprocessing` for more details.
.. note:: When all references to a storage in shared memory are deleted, the associated shared memory object will also be deleted. PyTorch has a special cleanup process to ensure that this happens even if the current process exits unexpectedly.
It is worth noting the difference between :meth:`share_memory_` and :meth:`from_file` with ``shared = True``
#. ``share_memory_`` uses `shm_open(3) <https://man7.org/linux/man-pages/man3/shm_open.3.html>`_ to create a POSIX shared memory object while :meth:`from_file` uses `open(2) <https://man7.org/linux/man-pages/man2/open.2.html>`_ to open the filename passed by the user. #. Both use an `mmap(2) call <https://man7.org/linux/man-pages/man2/mmap.2.html>`_ with ``MAP_SHARED`` to map the file/object into the current virtual address space #. ``share_memory_`` will call ``shm_unlink(3)`` on the object after mapping it to make sure the shared memory object is freed when no process has the object open. ``torch.from_file(shared=True)`` does not unlink the file. This file is persistent and will remain until it is deleted by the user.
Returns: ``self`` """ return super().share_memory_(*args, **kwargs)
@_share_memory_lock_protected def _share_fd_cpu_(self, *args, **kwargs): return super()._share_fd_cpu_(*args, **kwargs)
@_share_memory_lock_protected def _share_filename_cpu_(self, *args, **kwargs): return super()._share_filename_cpu_(*args, **kwargs)
def _load_from_bytes(b): return torch.load(io.BytesIO(b), weights_only=False)
@functools.cachedef _new_dtypes(): # These are dtypes serialized as UntypedStorage unlike those in # _dtype_to_storage_type_map return { torch.float8_e5m2, torch.float8_e4m3fn, torch.float8_e5m2fnuz, torch.float8_e4m3fnuz, torch.float8_e8m0fnu, torch.float4_e2m1fn_x2, torch.bits8, torch.bits16, torch.bits1x8, torch.bits2x4, torch.bits4x2, torch.complex32, torch.uint16, torch.uint32, torch.uint64, }
@functools.cachedef _dtype_to_storage_type_map(): # NOTE: We should no longer add dtypes to this map. This map # is only used for BC/FC with older PyTorch versions. Going forward, # new dtypes of TypedStorage should not translate to a legacy # <type>Storage class. Instead, new dtypes of TypedStorage should # be serialized as an UntypedStorage paired with a torch.dtype return { torch.double: "DoubleStorage", torch.float: "FloatStorage", torch.half: "HalfStorage", torch.long: "LongStorage", torch.int: "IntStorage", torch.int16: "ShortStorage", torch.int8: "CharStorage", torch.uint8: "ByteStorage", torch.bool: "BoolStorage", torch.bfloat16: "BFloat16Storage", torch.cdouble: "ComplexDoubleStorage", torch.cfloat: "ComplexFloatStorage", torch.qint8: "QInt8Storage", torch.qint32: "QInt32Storage", torch.quint8: "QUInt8Storage", torch.quint4x2: "QUInt4x2Storage", torch.quint2x4: "QUInt2x4Storage", }
@functools.cachedef _storage_type_to_dtype_map(): dtype_map = {val: key for key, val in _dtype_to_storage_type_map().items()} return dtype_map
def _get_storage_from_sequence(sequence, dtype, device): if dtype in [ torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8, ]: interpret_dtypes = { torch.quint8: torch.uint8, torch.quint4x2: torch.uint8, torch.quint2x4: torch.uint8, torch.qint32: torch.int32, torch.qint8: torch.int8, } tmp_tensor = torch.tensor( sequence, dtype=interpret_dtypes[dtype], device=device )
else: tmp_tensor = torch.tensor(sequence, dtype=dtype, device=device)
return tmp_tensor._typed_storage()._untyped_storage
def _isint(x): if HAS_NUMPY: return isinstance(x, (int, np.integer)) else: return isinstance(x, int)
_always_warn_typed_storage_removal = False
def _get_always_warn_typed_storage_removal(): return _always_warn_typed_storage_removal
def _set_always_warn_typed_storage_removal(always_warn): global _always_warn_typed_storage_removal assert isinstance(always_warn, bool) _always_warn_typed_storage_removal = always_warn
def _warn_typed_storage_removal(stacklevel=2): global _always_warn_typed_storage_removal
def is_first_time(): if not hasattr(_warn_typed_storage_removal, "has_warned"): return True else: return not _warn_typed_storage_removal.__dict__["has_warned"]
if _get_always_warn_typed_storage_removal() or is_first_time(): message = ( "TypedStorage is deprecated. It will be removed in the future and " "UntypedStorage will be the only storage class. This should only matter " "to you if you are using storages directly. To access UntypedStorage " "directly, use tensor.untyped_storage() instead of tensor.storage()" ) warnings.warn(message, UserWarning, stacklevel=stacklevel + 1) _warn_typed_storage_removal.__dict__["has_warned"] = True
def _reset_warn_typed_storage_removal(): _warn_typed_storage_removal.__dict__["has_warned"] = False
def _get_device_from_module(module: str): last_part = module.rsplit(".", 1)[-1] if last_part in ["cuda", torch._C._get_privateuse1_backend_name(), "hpu"]: return last_part else: return "cpu"
class TypedStorage: is_sparse: _bool = False # Used when stashing FakeTensor device onto storage in torch.save(metadata_only=True) _fake_device: _Optional[torch.device] = None
dtype: torch.dtype
@property def _dtype(self): return self.dtype
@property def filename(self) -> _Optional[str]: """Returns the file name associated with this storage if the storage was memory mapped from a file. or ``None`` if the storage was not created by memory mapping a file.""" return self._untyped_storage.filename
def fill_(self, value): _warn_typed_storage_removal() self._setitem(slice(0, self._size()), value) return self
def __new__( cls, *args, wrap_storage=None, dtype=None, device=None, _internal=False, ): if not _internal: _warn_typed_storage_removal()
if cls == torch.storage._LegacyStorage: raise RuntimeError( "Only child classes of _LegacyStorage can be instantiated" )
if cls == TypedStorage: return super().__new__(cls)
else: arg_error_msg = ( f"{cls}.__new__ received an invalid combination " f"of arguments. Expected one of:\n" " * no arguments\n" " * (int size)\n" " * (Sequence data)\n" " * (*, UntypedStorage wrap_storage)" )
if device is not None: raise RuntimeError( arg_error_msg + "\nKeyword argument 'device' cannot be specified" )
if dtype is not None: raise RuntimeError( arg_error_msg + "\nKeyword argument 'dtype' cannot be specified" )
if wrap_storage is None: if len(args) > 1: raise RuntimeError( arg_error_msg + "\nToo many positional arguments" )
if ( len(args) == 1 and not _isint(args[0]) and not isinstance(args[0], collections.abc.Sequence) ): raise TypeError( arg_error_msg + f"\nArgument type not recognized: {type(args[0])}" )
return TypedStorage( *args, dtype=cls._dtype, device=_get_device_from_module(cls.__module__), _internal=True, )
else: if len(args) != 0: raise RuntimeError( arg_error_msg + "\nNo positional arguments should be given when using " "'wrap_storage'" )
if not isinstance(wrap_storage, torch.UntypedStorage): raise TypeError( arg_error_msg + f"\nArgument 'wrap_storage' must be UntypedStorage, but got {type(wrap_storage)}" )
cls_device = _get_device_from_module(cls.__module__)
if wrap_storage.device.type != cls_device: raise RuntimeError( arg_error_msg + f"\nDevice of 'wrap_storage' must be {cls_device}" f", but got {wrap_storage.device.type}" )
return TypedStorage( *args, wrap_storage=wrap_storage, dtype=cls.dtype, _internal=True, )
def __init__( self, *args, device=None, dtype=None, wrap_storage=None, _internal=False, ): if not _internal: _warn_typed_storage_removal() arg_error_msg = ( "TypedStorage.__init__ received an invalid combination " "of arguments. Expected one of:\n" " * (*, torch.device device, torch.dtype dtype)\n" " * (int size, *, torch.device device, torch.dtype dtype)\n" " * (Sequence data, *, torch.device device, torch.dtype dtype)\n" " * (*, UntypedStorage wrap_storage, torch.dtype dtype)" )
if wrap_storage is not None: if len(args) != 0: raise RuntimeError( arg_error_msg + "\nNo positional arguments should be given when using " "'wrap_storage'" )
if dtype is None: raise RuntimeError( arg_error_msg + "\nArgument 'dtype' must be specified" )
if not isinstance(dtype, torch.dtype): raise TypeError( arg_error_msg + f"\nArgument 'dtype' must be torch.dtype, not {type(dtype)}" )
if device is not None: raise RuntimeError( arg_error_msg + "\nArgument 'device' should not be specified when 'wrap_storage' is given" )
self.dtype = dtype
if not isinstance(wrap_storage, torch.UntypedStorage): raise TypeError( arg_error_msg + f"\nArgument 'wrap_storage' must be UntypedStorage, but got {type(wrap_storage)}" )
self._untyped_storage = wrap_storage
else: self.dtype = torch.get_default_dtype() if dtype is None else dtype device = torch.device("cpu" if device is None else device)
if self.dtype in [ torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8, ]: if device.type == "cuda": raise RuntimeError( "Cannot create CUDA storage with quantized dtype" )
if len(args) == 0: self._untyped_storage = torch.UntypedStorage(device=device)
elif len(args) == 1: if _isint(args[0]): self._untyped_storage = torch.UntypedStorage( int(args[0]) * self._element_size(), device=device ) elif isinstance(args[0], collections.abc.Sequence): self._untyped_storage = _get_storage_from_sequence( args[0], self.dtype, device ) else: raise TypeError( arg_error_msg + f"\nArgument type not recognized: {type(args[0])}" )
else: raise RuntimeError(arg_error_msg + "\nToo many positional arguments")
@property def is_cuda(self): _warn_typed_storage_removal() return self._untyped_storage.device.type == "cuda"
@property def is_hpu(self): _warn_typed_storage_removal() return self._untyped_storage.device.type == "hpu"
def untyped(self): """Return the internal :class:`torch.UntypedStorage`.""" _warn_typed_storage_removal() return self._untyped_storage
def _new_wrapped_storage(self, untyped_storage) -> Self: assert type(untyped_storage) == torch.UntypedStorage
if type(self) == TypedStorage: return cast( Self, TypedStorage( wrap_storage=untyped_storage, dtype=self.dtype, _internal=True ), ) else: return type(self)(wrap_storage=untyped_storage)
def __len__(self): _warn_typed_storage_removal() return self._size()
def _maybe_wrap_index(self, idx, is_stop=False): if idx is None: if is_stop: return self._size() else: return 0
else: if type(idx) != int: raise TypeError(f"can't index a {type(self)} with {type(idx)}") if is_stop: if (idx > self._size()) or (idx < -self._size()): raise IndexError( f"index {idx} out of range for storage of size {self.size()}" ) if idx > 0: return idx else: return idx % self._size() else: if (idx >= self._size()) or (idx < -self._size()): raise IndexError( f"index {idx} out of range for storage of size {self.size()}" ) return idx % self._size()
def __setitem__(self, idx, value): _warn_typed_storage_removal() return self._setitem(idx, value)
def _setitem(self, idx, value): if not isinstance(idx, (int, slice)): raise RuntimeError(f"can't index a {type(self)} with {type(idx)}") if torch.is_storage(value): raise RuntimeError(f"cannot set item with value type {type(value)}") if self.dtype in [ torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8, ]: interpret_dtypes = { torch.quint8: torch.uint8, torch.quint4x2: torch.uint8, torch.quint2x4: torch.uint8, torch.qint32: torch.int32, torch.qint8: torch.int8, } tmp_dtype = interpret_dtypes[self.dtype] tmp_tensor = torch.tensor( [], dtype=tmp_dtype, device=self._untyped_storage.device ) tmp_tensor.set_( TypedStorage( wrap_storage=self._untyped_storage, dtype=tmp_dtype, _internal=True ) ) else: tmp_tensor = torch.tensor( [], dtype=self.dtype, device=self._untyped_storage.device ).set_(self)
tmp_tensor[idx] = value
def __getitem__(self, idx): _warn_typed_storage_removal() return self._getitem(idx)
def _getitem(self, idx): if self._untyped_storage.device.type == "meta": raise NotImplementedError("Not available for 'meta' device type")
# NOTE: Before TypedStorage existed, indexing with a slice used to be # possible for <type>Storage objects. However, it would return # a storage view, which would be a hassle to implement in TypedStorage, # so it was disabled if isinstance(idx, slice): raise RuntimeError( "slices are only supported in UntypedStorage.__getitem__" ) elif not isinstance(idx, int): raise RuntimeError(f"can't index a {type(self)} with {type(idx)}")
if self.dtype in [ torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8, ]: interpret_dtypes = { torch.quint8: torch.uint8, torch.quint4x2: torch.uint8, torch.quint2x4: torch.uint8, torch.qint32: torch.int32, torch.qint8: torch.int8, } return TypedStorage( wrap_storage=self._untyped_storage, dtype=interpret_dtypes[self.dtype], _internal=True, )._getitem(idx)
idx_wrapped = self._maybe_wrap_index(idx) from torch._subclasses.fake_tensor import unset_fake_temporarily
with unset_fake_temporarily(): tmp_tensor = torch.tensor( [], dtype=self.dtype, device=self._untyped_storage.device ).set_(self) return tmp_tensor[idx_wrapped].item()
def copy_(self, source: T, non_blocking: _Optional[bool] = None): _warn_typed_storage_removal() if isinstance(source, TypedStorage): self._untyped_storage.copy_(source._untyped_storage, non_blocking) else: self._untyped_storage.copy_(source, non_blocking) return self
def nbytes(self): _warn_typed_storage_removal() return self._nbytes()
# For internal use only, to avoid deprecation warning def _nbytes(self): return self._untyped_storage.nbytes()
def type( self, dtype: _Optional[str] = None, non_blocking: bool = False, ) -> Union[_StorageBase, TypedStorage, str]: _warn_typed_storage_removal() if dtype is None: legacy_class = self._get_legacy_storage_class()
if legacy_class is not None: return legacy_class.__module__ + "." + legacy_class.__name__
return ".".join([self.__module__, type(self).__name__])
else: return self._untyped_storage.type(dtype, non_blocking)
def cuda(self, device=None, non_blocking=False) -> Self: _warn_typed_storage_removal() if self.dtype in [ torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8, ]: raise RuntimeError("Cannot create CUDA storage with quantized dtype") cuda_storage = self._untyped_storage.cuda(device, non_blocking) return self._new_wrapped_storage(cuda_storage)
def hpu(self, device=None, non_blocking=False) -> Self: _warn_typed_storage_removal() if self.dtype in [ torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8, ]: raise RuntimeError("Cannot create HPU storage with quantized dtype") hpu_storage = self._untyped_storage.hpu(device, non_blocking) return self._new_wrapped_storage(hpu_storage)
def to(self, *, device: DeviceLikeType, non_blocking: bool = False) -> Self: _warn_typed_storage_removal() if not isinstance(device, torch.device): device = torch.device(device) if self.dtype in [ torch.quint8, torch.quint4x2, torch.quint2x4, torch.qint32, torch.qint8, ]: raise RuntimeError( f"Cannot create {device.type.upper()} storage with quantized dtype" ) to_storage = self._untyped_storage.to(device=device, non_blocking=non_blocking) return self._new_wrapped_storage(to_storage)
def element_size(self): _warn_typed_storage_removal() return self._element_size()
# For internal use only, to avoid deprecation warning def _element_size(self): return torch._utils._element_size(self.dtype)
def get_device(self) -> _int: _warn_typed_storage_removal() return self._untyped_storage.get_device()
def __str__(self): _warn_typed_storage_removal() info_str = ( f"[{torch.typename(self)}(dtype={self.dtype}, " f"device={self.device}) of size {len(self)}]" ) if self.device.type == "meta": return "...\n" + info_str else: data_str = " " + "\n ".join(str(self[i]) for i in range(self.size())) return data_str + "\n" + info_str
def __repr__(self): _warn_typed_storage_removal() return str(self)
def __iter__(self): _warn_typed_storage_removal() return iter(self[i] for i in range(self.size()))
def __copy__(self): _warn_typed_storage_removal() return self._new_wrapped_storage(copy.copy(self._untyped_storage))
def __deepcopy__(self, memo): _warn_typed_storage_removal() return self._deepcopy(memo)
# For internal use only, to avoid deprecation warning def _deepcopy(self, memo): return self._new_wrapped_storage(copy.deepcopy(self._untyped_storage, memo))
def __sizeof__(self): _warn_typed_storage_removal() return super().__sizeof__() + self.nbytes()
def clone(self): """Return a copy of this storage.""" _warn_typed_storage_removal() return self._new_wrapped_storage(self._untyped_storage.clone())
def tolist(self): """Return a list containing the elements of this storage.""" _warn_typed_storage_removal() return list(self)
def cpu(self): """Return a CPU copy of this storage if it's not already on the CPU.""" _warn_typed_storage_removal() return self._new_wrapped_storage(self._untyped_storage.cpu())
def is_pinned(self, device: Union[str, torch.device] = "cuda"): r"""Determine whether the CPU TypedStorage is already pinned on device.
Args: device (str or torch.device): The device to pin memory on (default: ``'cuda'``). This argument is discouraged and subject to deprecated.
Returns: A boolean variable. """ _warn_typed_storage_removal() return self._untyped_storage.is_pinned(device)
def pin_memory(self, device: Union[str, torch.device] = "cuda"): r"""Copy the CPU TypedStorage to pinned memory, if it's not already pinned.
Args: device (str or torch.device): The device to pin memory on (default: ``'cuda'``). This argument is discouraged and subject to deprecated.
Returns: A pinned CPU storage. """ _warn_typed_storage_removal() return self._new_wrapped_storage( self._untyped_storage.pin_memory(device=device) )
def share_memory_(self): """See :meth:`torch.UntypedStorage.share_memory_`""" _warn_typed_storage_removal() return self._share_memory_()
# For internal use only, to avoid deprecation warning def _share_memory_(self): self._untyped_storage.share_memory_() return self
def _new_shared(self, size, *, device=None): """Create a new storage in shared memory with the same data type.""" if device is None: device = "cpu" device = torch.device(device) untyped_storage = torch.UntypedStorage._new_shared( size * self._element_size(), device=device ) return TypedStorage( wrap_storage=untyped_storage, dtype=self.dtype, _internal=True )
@property def _cdata(self): return self._untyped_storage._cdata
@property def device(self): _warn_typed_storage_removal() return self._untyped_storage.device
def size(self): _warn_typed_storage_removal() return self._size()
# For internal use only, to avoid deprecation warning def _size(self): # NB: don't indirect through __len__, as that requires # an int to be returned return self._untyped_storage.nbytes() // self._element_size()
def pickle_storage_type(self): _warn_typed_storage_removal() return self._pickle_storage_type()
# For internal use only, to avoid deprecation warning def _pickle_storage_type(self): try: return _dtype_to_storage_type_map()[self.dtype] except KeyError as e: raise KeyError(f"dtype {self.dtype} is not recognized") from e
def __reduce__(self): b = io.BytesIO() torch.save(self, b, _use_new_zipfile_serialization=False) return (_load_from_bytes, (b.getvalue(),))
def data_ptr(self): _warn_typed_storage_removal() return self._data_ptr()
# For internal use only, to avoid deprecation warning def _data_ptr(self): return self._untyped_storage.data_ptr()
def resizable(self): _warn_typed_storage_removal() return self._untyped_storage.resizable()
def resize_(self, size): _warn_typed_storage_removal() self._resize_(size)
# For internal use only, to avoid deprecation warning def _resize_(self, size): self._untyped_storage.resize_(size * self._element_size())
@classmethod def _free_weak_ref(cls, *args, **kwargs): return UntypedStorage._free_weak_ref(*args, **kwargs)
def _weak_ref(self, *args, **kwargs): return self._untyped_storage._weak_ref(*args, **kwargs)
@classmethod def from_buffer(cls, *args, **kwargs): _warn_typed_storage_removal() return cls._from_buffer(*args, **kwargs)
@classmethod def _from_buffer(cls, *args, dtype=None, device=None, **kwargs): if cls == TypedStorage: dtype = torch.get_default_dtype() if dtype is None else dtype device = torch.device("cpu" if device is None else device) if device.type != "cpu": raise RuntimeError( f"TypedStorage.from_buffer: Not available for device {device.type}" ) untyped_storage: torch.UntypedStorage = torch.UntypedStorage.from_buffer( *args, dtype=dtype, **kwargs )
else: if dtype is not None or len(args) == 5: raise RuntimeError( "from_buffer: 'dtype' can only be specified in " "UntypedStorage.from_buffer and TypedStorage.from_buffer" ) if device is not None: raise RuntimeError( "from_buffer: 'device' can only be specified in " "UntypedStorage.from_buffer and TypedStorage.from_buffer" )
dtype = cls._dtype untyped_storage = torch.UntypedStorage.from_buffer( *args, dtype=dtype, **kwargs )
return TypedStorage(wrap_storage=untyped_storage, dtype=dtype, _internal=True)
def _to(self, dtype): if not isinstance(dtype, torch.dtype): raise TypeError(f"Argument 'dtype' must be torch.dtype, not {type(dtype)}") storage = ( torch.tensor([], dtype=self.dtype, device=self.device) .set_(self) .to(dtype) ._typed_storage() ) if storage.data_ptr() == self.data_ptr(): storage = storage.clone() return storage
def double(self): """Casts this storage to double type.""" _warn_typed_storage_removal() return self._to(torch.double)
def float(self): """Casts this storage to float type.""" _warn_typed_storage_removal() return self._to(torch.float)
def half(self): """Casts this storage to half type.""" _warn_typed_storage_removal() return self._to(torch.half)
def long(self): """Casts this storage to long type.""" _warn_typed_storage_removal() return self._to(torch.long)
def int(self): """Casts this storage to int type.""" _warn_typed_storage_removal() return self._to(torch.int)
def short(self): """Casts this storage to short type.""" _warn_typed_storage_removal() return self._to(torch.short)
def char(self): """Casts this storage to char type.""" _warn_typed_storage_removal() return self._to(torch.int8)
def byte(self): """Casts this storage to byte type.""" _warn_typed_storage_removal() return self._to(torch.uint8)
def bool(self): """Casts this storage to bool type.""" _warn_typed_storage_removal() return self._to(torch.bool)
def bfloat16(self): """Casts this storage to bfloat16 type.""" _warn_typed_storage_removal() return self._to(torch.bfloat16)
def complex_double(self): """Casts this storage to complex double type.""" _warn_typed_storage_removal() return self._to(torch.cdouble)
def complex_float(self): """Casts this storage to complex float type.""" _warn_typed_storage_removal() return self._to(torch.cfloat)
def float8_e5m2(self): """Casts this storage to float8_e5m2 type""" _warn_typed_storage_removal() return self._to(torch.float8_e5m2)
def float8_e4m3fn(self): """Casts this storage to float8_e4m3fn type""" _warn_typed_storage_removal() return self._to(torch.float8_e4m3fn)
def float8_e5m2fnuz(self): """Casts this storage to float8_e5m2fnuz type""" _warn_typed_storage_removal() return self._to(torch.float8_e5m2fnuz)
def float8_e4m3fnuz(self): """Casts this storage to float8_e4m3fnuz type""" _warn_typed_storage_removal() return self._to(torch.float8_e4m3fnuz)
@classmethod def from_file(cls, filename, shared, size): """from_file(filename, shared=False, size=0) -> Storage
Creates a CPU storage backed by a memory-mapped file.
If ``shared`` is ``True``, then memory is shared between all processes. All changes are written to the file. If ``shared`` is ``False``, then the changes on the storage do not affect the file.
``size`` is the number of elements in the storage. If ``shared`` is ``False``, then the file must contain at least ``size * sizeof(Type)`` bytes (``Type`` is the type of storage). If ``shared`` is ``True`` the file will be created if needed.
Args: filename (str): file name to map shared (bool): whether to share memory (whether ``MAP_SHARED`` or ``MAP_PRIVATE`` is passed to the underlying `mmap(2) call <https://man7.org/linux/man-pages/man2/mmap.2.html>`_) size (int): number of elements in the storage """ _warn_typed_storage_removal() if cls == TypedStorage: raise RuntimeError("from_file can only be called on derived classes") untyped_storage = UntypedStorage.from_file( filename, shared, size * torch._utils._element_size(cls.dtype) ) storage = cls(wrap_storage=untyped_storage) return storage
@classmethod def _expired(cls, *args, **kwargs): return UntypedStorage._expired(*args, **kwargs)
def _write_file(self, *args, **kwargs): return self._untyped_storage._write_file(*args, **kwargs)
def _set_from_file(self, *args, **kwargs): return self._untyped_storage._set_from_file(*args, **kwargs)
def _set_cdata(self, *args, **kwargs): return self._untyped_storage._set_cdata(*args, **kwargs)
def _share_cuda_(self, *args, **kwargs): return self._untyped_storage._share_cuda_(*args, **kwargs)
def is_shared(self): _warn_typed_storage_removal() return self._is_shared()
# For internal use only, to avoid deprecation warning def _is_shared(self): return self._untyped_storage.is_shared()
@classmethod def _new_shared_cuda(cls, *args, **kwargs): return torch.UntypedStorage._new_shared_cuda(*args, **kwargs)
def _share_filename_cpu_(self, *args, **kwargs): ( manager_handle, storage_handle, size, ) = self._untyped_storage._share_filename_cpu_(*args, **kwargs) return manager_handle, storage_handle, size // self._element_size()
def _shared_decref(self): self._untyped_storage._shared_decref() return self
@classmethod def _release_ipc_counter(cls, *args, device=None, **kwargs): return torch.UntypedStorage._release_ipc_counter_cuda(*args, **kwargs)
def _shared_incref(self, *args, **kwargs): return self._untyped_storage._shared_incref(*args, **kwargs)
def _share_fd_cpu_(self, *args, **kwargs): fd, size = self._untyped_storage._share_fd_cpu_(*args, **kwargs) return fd, size // self._element_size()
def _get_legacy_storage_class(self): if self.dtype not in _dtype_to_storage_type_map(): return None
storage_name = _dtype_to_storage_type_map()[self.dtype]
if self.device.type not in [ "cpu", "cuda", "hpu", torch._C._get_privateuse1_backend_name(), ]: return None
module = ( torch if self.device.type == "cpu" else getattr(torch, self.device.type) )
try: return getattr(module, storage_name) except AttributeError: return None
TypedStorage.type.__doc__ = _type.__doc__TypedStorage.cuda.__doc__ = _StorageBase.cuda.__doc__TypedStorage.hpu.__doc__ = _StorageBase.hpu.__doc__TypedStorage.to.__doc__ = _to.__doc__
class _LegacyStorageMeta(type): dtype: torch.dtype
def __instancecheck__(cls, instance): if type(instance) == TypedStorage: cls_device = _get_device_from_module(cls.__module__) return (cls_device == instance.device.type) and ( cls.dtype == instance.dtype ) return False
class _LegacyStorage(TypedStorage, metaclass=_LegacyStorageMeta): @classmethod def _new_shared(cls, size): # type: ignore[override] """Create a new storage in shared memory with the same data type.""" untyped_storage = torch.UntypedStorage._new_shared(size * cls()._element_size()) return cls(wrap_storage=untyped_storage)
@classmethod def _release_ipc_counter(cls, *args, **kwargs): return torch.UntypedStorage._release_ipc_counter_cuda(*args, **kwargs)
@classmethod def _new_shared_filename(cls, manager, obj, size): bytes_size = size * torch._utils._element_size(cls.dtype) return cls( wrap_storage=torch.UntypedStorage._new_shared_filename_cpu( manager, obj, bytes_size ) )
def _get_dtype_from_pickle_storage_type(pickle_storage_type: str): try: return _storage_type_to_dtype_map()[pickle_storage_type] except KeyError as e: raise KeyError( f'pickle storage type "{pickle_storage_type}" is not recognized' ) from e123version https://git-lfs.github.com/spec/v1oid sha256:3ffc3c1afbd254de4ea6c160bc918b31acd4c54ad30a545b5bcb05640da35b9fsize 621448.gitattributes+1
.venv/lib/python3.12/site-packages/torch/signal/__init__.pyAdded+4
.venv/lib/python3.12/site-packages/torch/signal/__pycache__/__init__.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/torch/signal/windows/__init__.pyAdded+28
.venv/lib/python3.12/site-packages/torch/signal/windows/__pycache__/__init__.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/torch/signal/windows/__pycache__/windows.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/torch/signal/windows/windows.pyAdded+890
.venv/lib/python3.12/site-packages/torch/sparse/__init__.pyAdded+703
.venv/lib/python3.12/site-packages/torch/sparse/__pycache__/__init__.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/torch/sparse/__pycache__/_semi_structured_conversions.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/torch/sparse/__pycache__/_semi_structured_ops.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/torch/sparse/__pycache__/semi_structured.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/torch/sparse/_semi_structured_conversions.pyAdded+356
.venv/lib/python3.12/site-packages/torch/sparse/_semi_structured_ops.pyAdded+197
.venv/lib/python3.12/site-packages/torch/sparse/_triton_ops.pyAdded+2529
.venv/lib/python3.12/site-packages/torch/sparse/_triton_ops_meta.pyAdded
.venv/lib/python3.12/site-packages/torch/sparse/semi_structured.pyAdded+658
.venv/lib/python3.12/site-packages/torch/special/__init__.pyAdded+1559
.venv/lib/python3.12/site-packages/torch/special/__pycache__/__init__.cpython-312.pycAdded
.venv/lib/python3.12/site-packages/torch/storage.pyAdded+1551
.venv/lib/python3.12/site-packages/torch/test/CppSignature_testAdded+3