__init__.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. # mypy: allow-untyped-defs
  2. from typing import Optional, Union
  3. import torch
  4. import torch.nn.functional as F
  5. from torch import SymInt, Tensor
  6. from torch._C import _add_docstr, _nested # type: ignore[attr-defined]
  7. from torch.types import _device as Device, _dtype as DType
  8. __all__ = [
  9. "to_padded_tensor",
  10. "as_nested_tensor",
  11. "nested_tensor",
  12. "nested_tensor_from_jagged",
  13. "narrow",
  14. "masked_select",
  15. ]
  16. # Allowlist these for weights_only load of NJT
  17. from ._internal.nested_tensor import _rebuild_njt, NestedTensor as _NestedTensor
  18. torch.serialization.add_safe_globals([_NestedTensor, _rebuild_njt])
  19. def as_nested_tensor(
  20. ts: Union[Tensor, list[Tensor], tuple[Tensor, ...]],
  21. dtype: Optional[DType] = None,
  22. device: Optional[Device] = None,
  23. layout=None,
  24. ) -> Tensor:
  25. r"""
  26. Constructs a nested tensor preserving autograd history from a tensor or a list / tuple of
  27. tensors.
  28. If a nested tensor is passed, it will be returned directly unless the device / dtype / layout
  29. differ. Note that converting device / dtype will result in a copy, while converting layout
  30. is not currently supported by this function.
  31. If a non-nested tensor is passed, it is treated as a batch of constituents of consistent size.
  32. A copy will be incurred if the passed device / dtype differ from those of the input OR if
  33. the input is non-contiguous. Otherwise, the input's storage will be used directly.
  34. If a tensor list is provided, tensors in the list are always copied during construction of
  35. the nested tensor.
  36. Args:
  37. ts (Tensor or List[Tensor] or Tuple[Tensor]): a tensor to treat as a nested tensor OR a
  38. list / tuple of tensors with the same ndim
  39. Keyword arguments:
  40. dtype (:class:`torch.dtype`, optional): the desired type of returned nested tensor.
  41. Default: if None, same :class:`torch.dtype` as leftmost tensor in the list.
  42. device (:class:`torch.device`, optional): the desired device of returned nested tensor.
  43. Default: if None, same :class:`torch.device` as leftmost tensor in the list
  44. layout (:class:`torch.layout`, optional): the desired layout of returned nested tensor.
  45. Only strided and jagged layouts are supported. Default: if None, the strided layout.
  46. Example::
  47. >>> a = torch.arange(3, dtype=torch.float, requires_grad=True)
  48. >>> b = torch.arange(5, dtype=torch.float, requires_grad=True)
  49. >>> nt = torch.nested.as_nested_tensor([a, b])
  50. >>> nt.is_leaf
  51. False
  52. >>> fake_grad = torch.nested.nested_tensor([torch.ones_like(a), torch.zeros_like(b)])
  53. >>> nt.backward(fake_grad)
  54. >>> a.grad
  55. tensor([1., 1., 1.])
  56. >>> b.grad
  57. tensor([0., 0., 0., 0., 0.])
  58. >>> c = torch.randn(3, 5, requires_grad=True)
  59. >>> nt2 = torch.nested.as_nested_tensor(c)
  60. """
  61. is_tensor_list = isinstance(ts, (list, tuple)) and all(
  62. isinstance(t, Tensor) for t in ts
  63. )
  64. if not isinstance(ts, Tensor) and not is_tensor_list:
  65. raise TypeError(
  66. "as_nested_tensor(): Expected first argument to be a tensor or a list / tuple of tensors "
  67. )
  68. # convert tuple -> list if needed
  69. if is_tensor_list and not isinstance(ts, list):
  70. ts = list(ts)
  71. if isinstance(ts, Tensor) and ts.dim() < 2:
  72. raise RuntimeError(
  73. "as_nested_tensor(): Expected tensor argument to have dim() > 1"
  74. )
  75. if isinstance(ts, Tensor) and ts.is_nested:
  76. if layout == ts.layout:
  77. # return input directly or input copied to device / dtype
  78. return ts.to(device=device, dtype=dtype)
  79. else:
  80. # TODO: Just use nt.to(layout=layout) when it exists.
  81. raise RuntimeError(
  82. "as_nested_tensor(): Converting between nested tensor layouts is not supported"
  83. )
  84. if layout is None:
  85. layout = torch.strided
  86. if layout == torch.strided:
  87. if isinstance(ts, Tensor):
  88. # contiguous() might be necessary to get flattened view.
  89. # we could probably be more precise about when to do this as an optimization
  90. buffer = ts.contiguous().view(-1).to(device=device, dtype=dtype)
  91. nested_sizes = torch.tensor([t.shape for t in ts])
  92. return torch._nested_view_from_buffer(
  93. buffer,
  94. nested_sizes,
  95. *torch._nested_compute_contiguous_strides_offsets(nested_sizes),
  96. )
  97. else:
  98. assert isinstance(ts, list)
  99. return torch._nested_tensor_from_tensor_list(ts, dtype, None, device, None)
  100. elif layout == torch.jagged:
  101. if isinstance(ts, Tensor):
  102. if device is None:
  103. device = ts.device
  104. # contiguous() might be necessary to get flattened view.
  105. # we could probably be more precise about when to do this as an optimization
  106. values = ts.contiguous().flatten(0, 1).to(device=device, dtype=dtype)
  107. batch_size = ts.shape[0]
  108. seq_len = ts.shape[1]
  109. offsets = torch.arange(
  110. 0, batch_size * seq_len + 1, seq_len, device=device, dtype=torch.int64
  111. )
  112. from torch.nested._internal.nested_tensor import (
  113. nested_view_from_values_offsets,
  114. )
  115. return nested_view_from_values_offsets(
  116. values, offsets, min_seqlen=seq_len, max_seqlen=seq_len
  117. )
  118. else:
  119. from torch.nested._internal.nested_tensor import jagged_from_list
  120. assert isinstance(ts, list)
  121. nt, _ = jagged_from_list(ts, offsets=None, device=device, dtype=dtype)
  122. return nt
  123. else:
  124. raise RuntimeError(
  125. f"Specified layout is unsupported for nested tensors: {layout}"
  126. )
  127. # Note: This not only adds doc strings for the nested ops, but
  128. # also connects the torch.nested Python namespace to the torch._C._nested builtins.
  129. to_padded_tensor = _add_docstr(
  130. _nested.nested_to_padded_tensor,
  131. r"""
  132. to_padded_tensor(input, padding, output_size=None, out=None) -> Tensor
  133. Returns a new (non-nested) Tensor by padding the :attr:`input` nested tensor.
  134. The leading entries will be filled with the nested data,
  135. while the trailing entries will be padded.
  136. .. warning::
  137. :func:`to_padded_tensor` always copies the underlying data,
  138. since the nested and the non-nested tensors differ in memory layout.
  139. Args:
  140. padding (float): The padding value for the trailing entries.
  141. Keyword args:
  142. output_size (Tuple[int]): The size of the output tensor.
  143. If given, it must be large enough to contain all nested data;
  144. else, will infer by taking the max size of each nested sub-tensor along each dimension.
  145. out (Tensor, optional): the output tensor.
  146. Example::
  147. >>> nt = torch.nested.nested_tensor([torch.randn((2, 5)), torch.randn((3, 4))])
  148. nested_tensor([
  149. tensor([[ 1.6862, -1.1282, 1.1031, 0.0464, -1.3276],
  150. [-1.9967, -1.0054, 1.8972, 0.9174, -1.4995]]),
  151. tensor([[-1.8546, -0.7194, -0.2918, -0.1846],
  152. [ 0.2773, 0.8793, -0.5183, -0.6447],
  153. [ 1.8009, 1.8468, -0.9832, -1.5272]])
  154. ])
  155. >>> pt_infer = torch.nested.to_padded_tensor(nt, 0.0)
  156. tensor([[[ 1.6862, -1.1282, 1.1031, 0.0464, -1.3276],
  157. [-1.9967, -1.0054, 1.8972, 0.9174, -1.4995],
  158. [ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
  159. [[-1.8546, -0.7194, -0.2918, -0.1846, 0.0000],
  160. [ 0.2773, 0.8793, -0.5183, -0.6447, 0.0000],
  161. [ 1.8009, 1.8468, -0.9832, -1.5272, 0.0000]]])
  162. >>> pt_large = torch.nested.to_padded_tensor(nt, 1.0, (2, 4, 6))
  163. tensor([[[ 1.6862, -1.1282, 1.1031, 0.0464, -1.3276, 1.0000],
  164. [-1.9967, -1.0054, 1.8972, 0.9174, -1.4995, 1.0000],
  165. [ 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000],
  166. [ 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000]],
  167. [[-1.8546, -0.7194, -0.2918, -0.1846, 1.0000, 1.0000],
  168. [ 0.2773, 0.8793, -0.5183, -0.6447, 1.0000, 1.0000],
  169. [ 1.8009, 1.8468, -0.9832, -1.5272, 1.0000, 1.0000],
  170. [ 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000]]])
  171. >>> pt_small = torch.nested.to_padded_tensor(nt, 2.0, (2, 2, 2))
  172. RuntimeError: Value in output_size is less than NestedTensor padded size. Truncation is not supported.
  173. """,
  174. )
  175. def nested_tensor(
  176. tensor_list,
  177. *,
  178. dtype=None,
  179. layout=None,
  180. device=None,
  181. requires_grad=False,
  182. pin_memory=False,
  183. ) -> Tensor:
  184. r"""
  185. Constructs a nested tensor with no autograd history (also known as a "leaf tensor", see
  186. :ref:`Autograd mechanics <autograd-mechanics>`) from :attr:`tensor_list` a list of tensors.
  187. Args:
  188. tensor_list (List[array_like]): a list of tensors, or anything that can be passed to torch.tensor,
  189. where each element of the list has the same dimensionality.
  190. Keyword arguments:
  191. dtype (:class:`torch.dtype`, optional): the desired type of returned nested tensor.
  192. Default: if None, same :class:`torch.dtype` as leftmost tensor in the list.
  193. layout (:class:`torch.layout`, optional): the desired layout of returned nested tensor.
  194. Only strided and jagged layouts are supported. Default: if None, the strided layout.
  195. device (:class:`torch.device`, optional): the desired device of returned nested tensor.
  196. Default: if None, same :class:`torch.device` as leftmost tensor in the list
  197. requires_grad (bool, optional): If autograd should record operations on the
  198. returned nested tensor. Default: ``False``.
  199. pin_memory (bool, optional): If set, returned nested tensor would be allocated in
  200. the pinned memory. Works only for CPU tensors. Default: ``False``.
  201. Example::
  202. >>> a = torch.arange(3, dtype=torch.float, requires_grad=True)
  203. >>> b = torch.arange(5, dtype=torch.float, requires_grad=True)
  204. >>> nt = torch.nested.nested_tensor([a, b], requires_grad=True)
  205. >>> nt.is_leaf
  206. True
  207. """
  208. if layout is None:
  209. layout = torch.strided
  210. if layout == torch.strided:
  211. return _nested.nested_tensor(
  212. tensor_list,
  213. dtype=dtype,
  214. device=device,
  215. requires_grad=requires_grad,
  216. pin_memory=pin_memory,
  217. )
  218. elif layout == torch.jagged:
  219. # Need to wrap lists of scalars as tensors
  220. list_of_tensors = [
  221. t if isinstance(t, Tensor) else torch.as_tensor(t) for t in tensor_list
  222. ]
  223. from torch.nested._internal.nested_tensor import jagged_from_list
  224. with torch.no_grad():
  225. nt, _ = jagged_from_list(
  226. list_of_tensors, offsets=None, device=device, dtype=dtype
  227. )
  228. nt.requires_grad_(requires_grad)
  229. if pin_memory:
  230. nt = nt.pin_memory() # type: ignore[assignment]
  231. return nt
  232. else:
  233. raise RuntimeError(
  234. f"Specified layout is unsupported for nested tensors: {layout}"
  235. )
  236. def narrow(
  237. tensor: Tensor,
  238. dim: int,
  239. start: Union[int, Tensor],
  240. length: Union[int, Tensor],
  241. layout=torch.strided,
  242. ) -> Tensor:
  243. r"""
  244. Constructs a nested tensor (which might be a view) from :attr:`tensor`, a strided tensor. This follows
  245. similar semantics to torch.Tensor.narrow, where in the :attr:`dim`-th dimension the new nested tensor
  246. shows only the elements in the interval `[start, start+length)`. As nested representations
  247. allow for a different `start` and `length` at each 'row' of that dimension, :attr:`start` and :attr:`length`
  248. can also be tensors of shape `tensor.shape[0]`.
  249. There's some differences depending on the layout you use for the nested tensor. If using strided layout,
  250. torch.narrow will do a copy of the narrowed data into a contiguous NT with strided layout, while
  251. jagged layout narrow() will create a non-contiguous view of your original strided tensor. This particular
  252. representation is really useful for representing kv-caches in Transformer models, as specialized
  253. SDPA kernels can deal with format easily, resulting in performance improvements.
  254. Args:
  255. tensor (:class:`torch.Tensor`): a strided tensor, which will be used as the underlying data
  256. for the nested tensor if using the jagged layout or will be copied for the strided layout.
  257. dim (int): the dimension where narrow will be applied. Only `dim=1` is supported for the
  258. jagged layout, while strided supports all dim
  259. start (Union[int, :class:`torch.Tensor`]): starting element for the narrow operation
  260. length (Union[int, :class:`torch.Tensor`]): number of elements taken during the narrow op
  261. Keyword arguments:
  262. layout (:class:`torch.layout`, optional): the desired layout of returned nested tensor.
  263. Only strided and jagged layouts are supported. Default: if None, the strided layout.
  264. Example::
  265. >>> starts = torch.tensor([0, 1, 2, 3, 4], dtype=torch.int64)
  266. >>> lengths = torch.tensor([3, 2, 2, 1, 5], dtype=torch.int64)
  267. >>> narrow_base = torch.randn(5, 10, 20)
  268. >>> nt_narrowed = torch.nested.narrow(narrow_base, 1, starts, lengths, layout=torch.jagged)
  269. >>> nt_narrowed.is_contiguous()
  270. False
  271. """
  272. if not isinstance(start, (int, SymInt, Tensor)):
  273. raise RuntimeError("start must be an integer or a tensor")
  274. if not isinstance(length, (int, SymInt, Tensor)):
  275. raise RuntimeError("length must be an integer or a tensor")
  276. if layout == torch.strided:
  277. if isinstance(start, Tensor) or isinstance(length, Tensor):
  278. raise RuntimeError(
  279. "start and length must be integers for the strided layout NT impl"
  280. )
  281. # TODO: switch to as_nested_tensor(tensor) when it is available
  282. nt = as_nested_tensor(torch.unbind(tensor), layout=torch.strided).narrow(
  283. dim, start, length
  284. )
  285. elif layout == torch.jagged:
  286. if dim != 1:
  287. raise RuntimeError("jagged layout only supports dim=1")
  288. from torch.nested._internal.nested_tensor import jagged_from_tensor_and_lengths
  289. if isinstance(start, (int, SymInt)):
  290. start = torch.tensor([start], device=tensor.device, dtype=torch.int64)
  291. if isinstance(length, (int, SymInt)):
  292. length = torch.tensor([length], device=tensor.device, dtype=torch.int64)
  293. nt, _, _ = jagged_from_tensor_and_lengths(tensor, start, length)
  294. else:
  295. raise RuntimeError(
  296. f"Specified layout is unsupported for nested narrow: {layout}"
  297. )
  298. return nt
  299. def nested_tensor_from_jagged(
  300. values: Tensor,
  301. offsets: Optional[Tensor] = None,
  302. lengths: Optional[Tensor] = None,
  303. jagged_dim: Optional[int] = None,
  304. min_seqlen: Optional[int] = None,
  305. max_seqlen: Optional[int] = None,
  306. ) -> Tensor:
  307. r"""
  308. Constructs a jagged layout nested tensor from the given jagged components. The jagged layout
  309. consists of a required values buffer with the jagged dimension packed into a single dimension.
  310. The offsets / lengths metadata determines how this dimension is split into batch elements
  311. and are expected to be allocated on the same device as the values buffer.
  312. Expected metadata formats:
  313. * offsets: Indices within the packed dimension splitting it into heterogeneously-sized
  314. batch elements. Example: [0, 2, 3, 6] indicates that a packed jagged dim of size 6
  315. should be conceptually split into batch elements of length [2, 1, 3]. Note that both the
  316. beginning and ending offsets are required for kernel convenience (i.e. shape batch_size + 1).
  317. * lengths: Lengths of the individual batch elements; shape == batch_size. Example: [2, 1, 3]
  318. indicates that a packed jagged dim of size 6 should be conceptually split into batch
  319. elements of length [2, 1, 3].
  320. Note that it can be useful to provide both offsets and lengths. This describes a nested tensor
  321. with "holes", where the offsets indicate the start position of each batch item and the length
  322. specifies the total number of elements (see example below).
  323. The returned jagged layout nested tensor will be a view of the input values tensor.
  324. Args:
  325. values (:class:`torch.Tensor`): The underlying buffer in the shape of
  326. (sum_B(*), D_1, ..., D_N). The jagged dimension is packed into a single dimension,
  327. with the offsets / lengths metadata used to distinguish batch elements.
  328. offsets (optional :class:`torch.Tensor`): Offsets into the jagged dimension of shape B + 1.
  329. lengths (optional :class:`torch.Tensor`): Lengths of the batch elements of shape B.
  330. jagged_dim (optional int): Indicates which dimension in values is the packed jagged
  331. dimension. Must be >= 1 as the batch dimension (dim=0) cannot be ragged.
  332. If None, this is set to dim=1 (i.e. the dimension immediately following the batch dimension). Default: None
  333. min_seqlen (optional int): If set, uses the specified value as the cached minimum sequence
  334. length for the returned nested tensor. This can be a useful alternative to computing
  335. this value on-demand, possibly avoiding a GPU -> CPU sync. Default: None
  336. max_seqlen (optional int): If set, uses the specified value as the cached maximum sequence
  337. length for the returned nested tensor. This can be a useful alternative to computing
  338. this value on-demand, possibly avoiding a GPU -> CPU sync. Default: None
  339. Example::
  340. >>> values = torch.randn(12, 5)
  341. >>> offsets = torch.tensor([0, 3, 5, 6, 10, 12])
  342. >>> nt = nested_tensor_from_jagged(values, offsets)
  343. >>> # 3D shape with the middle dimension jagged
  344. >>> nt.shape
  345. torch.Size([5, j2, 5])
  346. >>> # Length of each item in the batch:
  347. >>> offsets.diff()
  348. tensor([3, 2, 1, 4, 2])
  349. >>> values = torch.randn(6, 5)
  350. >>> offsets = torch.tensor([0, 2, 3, 6])
  351. >>> lengths = torch.tensor([1, 1, 2])
  352. >>> # NT with holes
  353. >>> nt = nested_tensor_from_jagged(values, offsets, lengths)
  354. >>> a, b, c = nt.unbind()
  355. >>> # Batch item 1 consists of indices [0, 1)
  356. >>> torch.equal(a, values[0:1, :])
  357. True
  358. >>> # Batch item 2 consists of indices [2, 3)
  359. >>> torch.equal(b, values[2:3, :])
  360. True
  361. >>> # Batch item 3 consists of indices [3, 5)
  362. >>> torch.equal(c, values[3:5, :])
  363. True
  364. """
  365. from torch.fx._symbolic_trace import is_fx_tracing
  366. if is_fx_tracing():
  367. raise RuntimeError(
  368. "torch.nested.nested_tensor_from_jagged does not support tracing with fx.symbolic_trace. "
  369. "Use fx.wrap to wrap the function that calls nested_tensor_from_jagged."
  370. )
  371. if offsets is None:
  372. if lengths is None:
  373. raise RuntimeError(
  374. "nested_tensor_from_jagged(): At least one of offsets or lengths is required."
  375. )
  376. else:
  377. # TODO: Truly support offsets=None at some point?
  378. # For now, just convert lengths -> offsets for kernel convenience
  379. offsets = F.pad(lengths.cumsum(0), (1, 0))
  380. lengths = None
  381. if jagged_dim is None:
  382. jagged_dim = 1
  383. elif jagged_dim < 1:
  384. raise ValueError(f"Expected jagged_dim >=1, but got {jagged_dim}.")
  385. from torch.nested._internal.nested_tensor import (
  386. nested_view_from_values_offsets_lengths,
  387. )
  388. return nested_view_from_values_offsets_lengths(
  389. values,
  390. offsets,
  391. lengths,
  392. ragged_idx=jagged_dim,
  393. min_seqlen=min_seqlen,
  394. max_seqlen=max_seqlen,
  395. )
  396. def masked_select(tensor: Tensor, mask: Tensor) -> Tensor:
  397. r"""
  398. Constructs a nested tensor given a strided tensor input and a strided mask, the resulting jagged layout nested tensor
  399. will have values retain values where the mask is equal to True. The dimensionality of the mask is preserved and is
  400. represented with the offsets, this is unlike :func:`masked_select` where the output is collapsed to a 1D tensor.
  401. Args:
  402. tensor (:class:`torch.Tensor`): a strided tensor from which the jagged layout nested tensor is constructed from.
  403. mask (:class:`torch.Tensor`): a strided mask tensor which is applied to the tensor input
  404. Example::
  405. >>> tensor = torch.randn(3, 3)
  406. >>> mask = torch.tensor([[False, False, True], [True, False, True], [False, False, True]])
  407. >>> nt = torch.nested.masked_select(tensor, mask)
  408. >>> nt.shape
  409. torch.Size([3, j4])
  410. >>> # Length of each item in the batch:
  411. >>> nt.offsets().diff()
  412. tensor([1, 2, 1])
  413. >>> tensor = torch.randn(6, 5)
  414. >>> mask = torch.tensor([False])
  415. >>> nt = torch.nested.masked_select(tensor, mask)
  416. >>> nt.shape
  417. torch.Size([6, j5])
  418. >>> # Length of each item in the batch:
  419. >>> nt.offsets().diff()
  420. tensor([0, 0, 0, 0, 0, 0])
  421. """
  422. if tensor.layout != torch.strided:
  423. raise RuntimeError(
  424. f"torch.nested.masked_select requires a strided tensor, given {tensor.layout}"
  425. )
  426. if mask.layout != torch.strided:
  427. raise RuntimeError(
  428. f"torch.nested.masked_select requires a strided mask, given: {mask.layout}"
  429. )
  430. res_values = tensor.masked_select(mask)
  431. expanded_mask = mask.expand(tensor.shape)
  432. res_lengths = expanded_mask.sum(dim=tensor.ndim - 1).view(-1)
  433. from torch.nested._internal.nested_tensor import nested_view_from_values_offsets
  434. return nested_view_from_values_offsets(
  435. values=res_values,
  436. offsets=F.pad(res_lengths.cumsum(dim=0), (1, 0)),
  437. )