Prompt48 commited on
Commit
8206cef
·
verified ·
1 Parent(s): 50a705f

Upload edit\Qwen3-TTS-test\.venv\Lib\site-packages\torch\nested\__init__.py with huggingface_hub

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