torch-einops-kit 0.1.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- torch_einops_kit/__init__.py +172 -0
- torch_einops_kit/_cat_and_stack.py +197 -0
- torch_einops_kit/_dimensions.py +523 -0
- torch_einops_kit/_helpers.py +441 -0
- torch_einops_kit/_masking.py +318 -0
- torch_einops_kit/_padding.py +654 -0
- torch_einops_kit/_slicing.py +300 -0
- torch_einops_kit/_theTypes.py +434 -0
- torch_einops_kit/device.py +326 -0
- torch_einops_kit/einops.py +234 -0
- torch_einops_kit/nn.py +189 -0
- torch_einops_kit/py.typed +0 -0
- torch_einops_kit/save_load.py +554 -0
- torch_einops_kit/scaleValues.py +391 -0
- torch_einops_kit/utils.py +170 -0
- torch_einops_kit-0.1.8.dist-info/METADATA +482 -0
- torch_einops_kit-0.1.8.dist-info/RECORD +20 -0
- torch_einops_kit-0.1.8.dist-info/WHEEL +4 -0
- torch_einops_kit-0.1.8.dist-info/licenses/LICENSE +407 -0
- torch_einops_kit-0.1.8.dist-info/licenses/LICENSE-WANG +23 -0
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from hunterMakesPy import decreasing, zeroIndexed
|
|
4
|
+
from torch import cat, stack, Tensor, tensor
|
|
5
|
+
from torch_einops_kit import DimAndValue, first
|
|
6
|
+
from typing import Literal, overload, TYPE_CHECKING
|
|
7
|
+
from typing_extensions import Unpack
|
|
8
|
+
import torch
|
|
9
|
+
import torch.nn.functional as F
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from collections.abc import Callable, Sequence
|
|
13
|
+
|
|
14
|
+
def pad_at_dim(t: Tensor, pad: tuple[int, int], *, dim: int = -1, value: float = 0.0) -> Tensor:
|
|
15
|
+
"""Pad `t` along `dim`, inserting `value` at each end by the amounts in `pad`.
|
|
16
|
+
|
|
17
|
+
You can use `pad_at_dim` to add fill elements to either side of any dimension of `t`. Negative
|
|
18
|
+
values in `pad` trim elements from the corresponding end rather than adding them. `pad_at_dim`
|
|
19
|
+
delegates to `torch.nn.functional.pad` [1] after constructing the flat padding tuple.
|
|
20
|
+
|
|
21
|
+
Parameters
|
|
22
|
+
----------
|
|
23
|
+
t : Tensor
|
|
24
|
+
The input `Tensor` to pad.
|
|
25
|
+
pad : tuple[int, int]
|
|
26
|
+
A pair `(left, right)` specifying how many elements to insert before and after the existing
|
|
27
|
+
content along `dim`. Negative values trim elements from the corresponding end.
|
|
28
|
+
dim : int = -1
|
|
29
|
+
The dimension along which to apply the padding.
|
|
30
|
+
value : float = 0.0
|
|
31
|
+
The scalar fill value used for inserted elements.
|
|
32
|
+
|
|
33
|
+
Returns
|
|
34
|
+
-------
|
|
35
|
+
padded : Tensor
|
|
36
|
+
The padded `Tensor`. The shape along `dim` is `t.shape[dim] + pad[0] + pad[1]`.
|
|
37
|
+
|
|
38
|
+
See Also
|
|
39
|
+
--------
|
|
40
|
+
pad_left_at_dim : Pad only the left side of a dimension.
|
|
41
|
+
pad_right_at_dim : Pad only the right side of a dimension.
|
|
42
|
+
|
|
43
|
+
Examples
|
|
44
|
+
--------
|
|
45
|
+
From the test suite [2]:
|
|
46
|
+
|
|
47
|
+
>>> import torch
|
|
48
|
+
>>> from torch_einops_kit import pad_at_dim
|
|
49
|
+
>>> t = torch.randn(3, 6, 1)
|
|
50
|
+
>>> pad_at_dim(t, (0, 1), dim=1).shape
|
|
51
|
+
torch.Size([3, 7, 1])
|
|
52
|
+
|
|
53
|
+
From dreamer4 [3], inserting a leading zero token to shift action tokens forward by one position
|
|
54
|
+
in the time dimension:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
action_tokens = pad_at_dim(action_tokens[:, :-1], (1, 0), value=0.0, dim=1)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
From locoformer [4], creating a one-step-delayed copy of an action sequence:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
past_action = pad_at_dim(action, (1, -1), dim=-2)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
References
|
|
67
|
+
----------
|
|
68
|
+
[1] torch.nn.functional.pad - PyTorch documentation
|
|
69
|
+
https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html
|
|
70
|
+
|
|
71
|
+
[2] tests.test_padding.py
|
|
72
|
+
|
|
73
|
+
[3] lucidrains/dreamer4
|
|
74
|
+
https://github.com/lucidrains/dreamer4
|
|
75
|
+
|
|
76
|
+
[4] lucidrains/locoformer
|
|
77
|
+
https://github.com/lucidrains/locoformer
|
|
78
|
+
"""
|
|
79
|
+
dims_from_right: int = ((decreasing * dim) - zeroIndexed + t.ndim) % t.ndim
|
|
80
|
+
zeros: tuple[Literal[0], ...] = (0, 0) * dims_from_right
|
|
81
|
+
return F.pad(t, (*zeros, *pad), value=value)
|
|
82
|
+
|
|
83
|
+
def pad_left_at_dim(t: Tensor, pad: int, **kwargs: Unpack[DimAndValue]) -> Tensor:
|
|
84
|
+
"""Pad `t` on the left side of a dimension by a fixed number of fill elements.
|
|
85
|
+
|
|
86
|
+
You can use `pad_left_at_dim` to prepend fill elements along any dimension of `t`.
|
|
87
|
+
`pad_left_at_dim` calls `pad_at_dim` [1] with `pad=(pad, 0)`. The keyword arguments `dim` and
|
|
88
|
+
`value` are forwarded via `DimAndValue` [2].
|
|
89
|
+
|
|
90
|
+
Parameters
|
|
91
|
+
----------
|
|
92
|
+
t : Tensor
|
|
93
|
+
The input `Tensor` to pad.
|
|
94
|
+
pad : int
|
|
95
|
+
The number of fill elements to insert before the existing content.
|
|
96
|
+
**kwargs : Unpack[DimAndValue]
|
|
97
|
+
Keyword arguments forwarded to `pad_at_dim`. Accepted keys are `dim` (`int`, default `-1`)
|
|
98
|
+
and `value` (`float`, default `0.0`).
|
|
99
|
+
|
|
100
|
+
Returns
|
|
101
|
+
-------
|
|
102
|
+
padded : Tensor
|
|
103
|
+
The padded `Tensor`. The shape along the target dimension is `t.shape[dim] + pad`.
|
|
104
|
+
|
|
105
|
+
See Also
|
|
106
|
+
--------
|
|
107
|
+
pad_at_dim : Pad with independent left and right amounts.
|
|
108
|
+
pad_left_at_dim_to : Pad the left side to reach a target length.
|
|
109
|
+
|
|
110
|
+
Examples
|
|
111
|
+
--------
|
|
112
|
+
From pi-zero-pytorch [3], prepending a start token marker to a sequence of discrete
|
|
113
|
+
action identifiers:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
discrete_action_ids_with_start = pad_left_at_dim(discrete_action_ids + 1, 1)
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
References
|
|
120
|
+
----------
|
|
121
|
+
[1] torch_einops_kit.pad_at_dim
|
|
122
|
+
|
|
123
|
+
[2] torch_einops_kit.DimAndValue
|
|
124
|
+
|
|
125
|
+
[3] lucidrains/pi-zero-pytorch
|
|
126
|
+
https://github.com/lucidrains/pi-zero-pytorch
|
|
127
|
+
"""
|
|
128
|
+
return pad_at_dim(t, (pad, 0), **kwargs)
|
|
129
|
+
|
|
130
|
+
def pad_right_at_dim(t: Tensor, pad: int, **kwargs: Unpack[DimAndValue]) -> Tensor:
|
|
131
|
+
"""Pad `t` on the right side of a dimension by a fixed number of fill elements.
|
|
132
|
+
|
|
133
|
+
You can use `pad_right_at_dim` to append fill elements along any dimension of `t`.
|
|
134
|
+
`pad_right_at_dim` calls `pad_at_dim` [1] with `pad=(0, pad)`. The keyword arguments `dim` and
|
|
135
|
+
`value` are forwarded via `DimAndValue` [2].
|
|
136
|
+
|
|
137
|
+
Parameters
|
|
138
|
+
----------
|
|
139
|
+
t : Tensor
|
|
140
|
+
The input `Tensor` to pad.
|
|
141
|
+
pad : int
|
|
142
|
+
The number of fill elements to append after the existing content.
|
|
143
|
+
**kwargs : Unpack[DimAndValue]
|
|
144
|
+
Keyword arguments forwarded to `pad_at_dim`. Accepted keys are `dim` (`int`, default `-1`)
|
|
145
|
+
and `value` (`float`, default `0.0`).
|
|
146
|
+
|
|
147
|
+
Returns
|
|
148
|
+
-------
|
|
149
|
+
padded : Tensor
|
|
150
|
+
The padded `Tensor`. The shape along the target dimension is `t.shape[dim] + pad`.
|
|
151
|
+
|
|
152
|
+
See Also
|
|
153
|
+
--------
|
|
154
|
+
pad_at_dim : Pad with independent left and right amounts.
|
|
155
|
+
pad_right_at_dim_to : Pad the right side to reach a target length.
|
|
156
|
+
|
|
157
|
+
Examples
|
|
158
|
+
--------
|
|
159
|
+
From the test suite [3], verifying that `pad_right_at_dim` appends one element along a dimension:
|
|
160
|
+
|
|
161
|
+
```python
|
|
162
|
+
import torch
|
|
163
|
+
from torch_einops_kit import pad_right_at_dim
|
|
164
|
+
|
|
165
|
+
t = torch.randn(3, 6, 1)
|
|
166
|
+
assert pad_right_at_dim(t, 1, dim=1).shape == torch.Size([3, 7, 1])
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
References
|
|
170
|
+
----------
|
|
171
|
+
[1] torch_einops_kit.pad_at_dim
|
|
172
|
+
|
|
173
|
+
[2] torch_einops_kit.DimAndValue
|
|
174
|
+
|
|
175
|
+
[3] tests/test_padding.py
|
|
176
|
+
"""
|
|
177
|
+
return pad_at_dim(t, (0, pad), **kwargs)
|
|
178
|
+
|
|
179
|
+
def pad_left_at_dim_to(t: Tensor, length: int, dim: int = -1, **kwargs: float) -> Tensor:
|
|
180
|
+
"""Pad `t` on the left side of `dim` until `dim` reaches `length`.
|
|
181
|
+
|
|
182
|
+
You can use `pad_left_at_dim_to` to ensure the size of `t` along `dim` is at least `length` by
|
|
183
|
+
left-padding with fill values. If `t.shape[dim]` is already greater than or equal to `length`,
|
|
184
|
+
`pad_left_at_dim_to` returns `t` unchanged. Otherwise, `pad_left_at_dim_to` calls
|
|
185
|
+
`pad_left_at_dim` [1] with `pad = length - t.shape[dim]`.
|
|
186
|
+
|
|
187
|
+
Parameters
|
|
188
|
+
----------
|
|
189
|
+
t : Tensor
|
|
190
|
+
The input `Tensor` to conditionally pad.
|
|
191
|
+
length : int
|
|
192
|
+
The minimum target size along `dim`.
|
|
193
|
+
dim : int = -1
|
|
194
|
+
The dimension to pad.
|
|
195
|
+
**kwargs : float
|
|
196
|
+
Keyword arguments forwarded to `pad_left_at_dim`. The accepted key is `value` (`float`,
|
|
197
|
+
default `0.0`), the fill value for inserted elements.
|
|
198
|
+
|
|
199
|
+
Returns
|
|
200
|
+
-------
|
|
201
|
+
padded : Tensor
|
|
202
|
+
The padded `Tensor` with `padded.shape[dim] == max(t.shape[dim], length)`. Returns `t`
|
|
203
|
+
unchanged when `t.shape[dim] >= length`.
|
|
204
|
+
|
|
205
|
+
See Also
|
|
206
|
+
--------
|
|
207
|
+
pad_left_at_dim : Pad the left side by an explicit count.
|
|
208
|
+
pad_right_at_dim_to : Pad the right side to a target length.
|
|
209
|
+
|
|
210
|
+
Examples
|
|
211
|
+
--------
|
|
212
|
+
From the test suite [2]:
|
|
213
|
+
|
|
214
|
+
>>> import torch
|
|
215
|
+
>>> from torch_einops_kit import pad_left_at_dim_to
|
|
216
|
+
>>> t = torch.randn(3, 6, 1)
|
|
217
|
+
>>> pad_left_at_dim_to(t, 7, dim=1).shape
|
|
218
|
+
torch.Size([3, 7, 1])
|
|
219
|
+
>>> pad_left_at_dim_to(t, 6, dim=1) is t # already at length, returned unchanged
|
|
220
|
+
True
|
|
221
|
+
|
|
222
|
+
References
|
|
223
|
+
----------
|
|
224
|
+
[1] torch_einops_kit.pad_left_at_dim
|
|
225
|
+
|
|
226
|
+
[2] tests/test_utils.py
|
|
227
|
+
"""
|
|
228
|
+
curr_len: int = t.shape[dim]
|
|
229
|
+
if curr_len >= length:
|
|
230
|
+
return t
|
|
231
|
+
|
|
232
|
+
return pad_left_at_dim(t, length - curr_len, dim=dim, **kwargs)
|
|
233
|
+
|
|
234
|
+
def pad_right_at_dim_to(t: Tensor, length: int, dim: int = -1, **kwargs: float) -> Tensor:
|
|
235
|
+
"""Pad `t` on the right side of `dim` until `dim` reaches `length`.
|
|
236
|
+
|
|
237
|
+
You can use `pad_right_at_dim_to` to ensure the size of `t` along `dim` is at least `length` by
|
|
238
|
+
right-padding with fill values. If `t.shape[dim]` is already greater than or equal to `length`,
|
|
239
|
+
`pad_right_at_dim_to` returns `t` unchanged. Otherwise, `pad_right_at_dim_to` calls
|
|
240
|
+
`pad_right_at_dim` [1] with `pad = length - t.shape[dim]`.
|
|
241
|
+
|
|
242
|
+
Parameters
|
|
243
|
+
----------
|
|
244
|
+
t : Tensor
|
|
245
|
+
The input `Tensor` to conditionally pad.
|
|
246
|
+
length : int
|
|
247
|
+
The minimum target size along `dim`.
|
|
248
|
+
dim : int = -1
|
|
249
|
+
The dimension to pad.
|
|
250
|
+
**kwargs : float
|
|
251
|
+
Keyword arguments forwarded to `pad_right_at_dim`. The accepted key is `value` (`float`,
|
|
252
|
+
default `0.0`), the fill value for inserted elements.
|
|
253
|
+
|
|
254
|
+
Returns
|
|
255
|
+
-------
|
|
256
|
+
padded : Tensor
|
|
257
|
+
The padded `Tensor` with `padded.shape[dim] == max(t.shape[dim], length)`. Returns `t`
|
|
258
|
+
unchanged when `t.shape[dim] >= length`.
|
|
259
|
+
|
|
260
|
+
See Also
|
|
261
|
+
--------
|
|
262
|
+
pad_right_at_dim : Pad the right side by an explicit count.
|
|
263
|
+
pad_left_at_dim_to : Pad the left side to a target length.
|
|
264
|
+
|
|
265
|
+
Examples
|
|
266
|
+
--------
|
|
267
|
+
From dreamer4 [2], bringing variable-length action sequences to a uniform time length before
|
|
268
|
+
batching:
|
|
269
|
+
|
|
270
|
+
```python
|
|
271
|
+
tensors = [pad_right_at_dim_to(t, max_time, dim=dim) for t in tensors]
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
References
|
|
275
|
+
----------
|
|
276
|
+
[1] torch_einops_kit.pad_right_at_dim
|
|
277
|
+
|
|
278
|
+
[2] lucidrains/dreamer4
|
|
279
|
+
https://github.com/lucidrains/dreamer4
|
|
280
|
+
"""
|
|
281
|
+
curr_len: int = t.shape[dim]
|
|
282
|
+
if curr_len >= length:
|
|
283
|
+
return t
|
|
284
|
+
|
|
285
|
+
return pad_right_at_dim(t, length - curr_len, dim=dim, **kwargs)
|
|
286
|
+
|
|
287
|
+
@overload
|
|
288
|
+
def pad_sequence(
|
|
289
|
+
tensors: Sequence[Tensor], *, dim: int = -1, value: float = 0., left: bool = False, dim_stack: int = 0,
|
|
290
|
+
return_stacked: Literal[True] = True,
|
|
291
|
+
return_lens: Literal[False] = False,
|
|
292
|
+
pad_lens: bool = False
|
|
293
|
+
) -> Tensor: ...
|
|
294
|
+
@overload
|
|
295
|
+
def pad_sequence(
|
|
296
|
+
tensors: Sequence[Tensor], *, dim: int = -1, value: float = 0., left: bool = False, dim_stack: int = 0,
|
|
297
|
+
return_stacked: Literal[False],
|
|
298
|
+
return_lens: Literal[False] = False,
|
|
299
|
+
pad_lens: bool = False
|
|
300
|
+
) -> list[Tensor]: ...
|
|
301
|
+
@overload
|
|
302
|
+
def pad_sequence(
|
|
303
|
+
tensors: Sequence[Tensor], *, dim: int = -1, value: float = 0., left: bool = False, dim_stack: int = 0,
|
|
304
|
+
return_stacked: Literal[True] = True,
|
|
305
|
+
return_lens: Literal[True],
|
|
306
|
+
pad_lens: bool = False
|
|
307
|
+
) -> tuple[Tensor, Tensor]: ...
|
|
308
|
+
@overload
|
|
309
|
+
def pad_sequence(
|
|
310
|
+
tensors: Sequence[Tensor], *, dim: int = -1, value: float = 0., left: bool = False, dim_stack: int = 0,
|
|
311
|
+
return_stacked: Literal[False],
|
|
312
|
+
return_lens: Literal[True],
|
|
313
|
+
pad_lens: bool = False
|
|
314
|
+
) -> tuple[list[Tensor], Tensor]: ...
|
|
315
|
+
@overload
|
|
316
|
+
def pad_sequence(
|
|
317
|
+
tensors: list[Tensor] = [], # noqa: B006
|
|
318
|
+
*, dim: int = -1, value: float = 0.0, left: bool = False, dim_stack: int = 0,
|
|
319
|
+
return_stacked: bool = True, return_lens: bool = False, pad_lens: bool = False
|
|
320
|
+
) -> None: ...
|
|
321
|
+
@overload
|
|
322
|
+
def pad_sequence(
|
|
323
|
+
tensors: tuple[()] = (),
|
|
324
|
+
*, dim: int = -1, value: float = 0.0, left: bool = False, dim_stack: int = 0,
|
|
325
|
+
return_stacked: bool = True, return_lens: bool = False, pad_lens: bool = False
|
|
326
|
+
) -> None: ...
|
|
327
|
+
def pad_sequence(
|
|
328
|
+
tensors: Sequence[Tensor] = (),
|
|
329
|
+
*,
|
|
330
|
+
dim: int = -1,
|
|
331
|
+
value: float = 0.0,
|
|
332
|
+
left: bool = False,
|
|
333
|
+
dim_stack: int = 0,
|
|
334
|
+
return_stacked: bool = True,
|
|
335
|
+
return_lens: bool = False,
|
|
336
|
+
pad_lens: bool = False
|
|
337
|
+
) -> Tensor | list[Tensor] | tuple[Tensor | list[Tensor], Tensor] | None:
|
|
338
|
+
"""Pad a sequence of `Tensor` values to a shared length along `dim` and optionally stack them.
|
|
339
|
+
|
|
340
|
+
You can use `pad_sequence` to align a heterogeneous-length sequence of `Tensor` values so that
|
|
341
|
+
all `Tensor` values in `tensors` share the same size along `dim`. Each `Tensor` is padded to the
|
|
342
|
+
maximum size of `dim` across `tensors` using `pad_left_at_dim` [1] (when `left=True`) or
|
|
343
|
+
`pad_right_at_dim` [2] (when `left=False`). If `tensors` is empty, `pad_sequence` returns `None`.
|
|
344
|
+
|
|
345
|
+
The return type depends on the combination of `return_stacked` and `return_lens`. When
|
|
346
|
+
`return_stacked=True`, the padded list is combined into a single `Tensor` along `dim_stack` using
|
|
347
|
+
`torch.stack` [3]. When `return_lens=True`, a second `Tensor` of original (or padding) lengths is
|
|
348
|
+
appended to the return value as a tuple.
|
|
349
|
+
|
|
350
|
+
Parameters
|
|
351
|
+
----------
|
|
352
|
+
tensors : Sequence[Tensor]
|
|
353
|
+
A sequence of `Tensor` values to pad. Each `Tensor` must have the same shape in every
|
|
354
|
+
dimension except `dim`.
|
|
355
|
+
dim : int = -1
|
|
356
|
+
The dimension along which lengths vary and padding is applied.
|
|
357
|
+
value : float = 0.0
|
|
358
|
+
The scalar fill value for inserted padding elements.
|
|
359
|
+
left : bool = False
|
|
360
|
+
When `True`, pad at the beginning of `dim` (left-pad). When `False`, pad at the end
|
|
361
|
+
(right-pad).
|
|
362
|
+
dim_stack : int = 0
|
|
363
|
+
The dimension along which to stack the padded `Tensor` values. Used only when
|
|
364
|
+
`return_stacked=True`.
|
|
365
|
+
return_stacked : bool = True
|
|
366
|
+
When `True`, return a single stacked `Tensor`. When `False`, return a `list` of individually
|
|
367
|
+
padded `Tensor` values.
|
|
368
|
+
return_lens : bool = False
|
|
369
|
+
When `True`, include a 1-D `Tensor` of per-element lengths (or padding widths, if
|
|
370
|
+
`pad_lens=True`) as the second element of a returned tuple.
|
|
371
|
+
pad_lens : bool = False
|
|
372
|
+
When `True` and `return_lens=True`, the returned lengths `Tensor` contains padding widths
|
|
373
|
+
(`max_len - original_len`) rather than original dimension lengths.
|
|
374
|
+
|
|
375
|
+
Returns
|
|
376
|
+
-------
|
|
377
|
+
output : Tensor | list[Tensor] | tuple[Tensor | list[Tensor], Tensor] | None
|
|
378
|
+
When `return_stacked=True` and `return_lens=False`, a stacked `Tensor` or `None`. When
|
|
379
|
+
`return_stacked=True` and `return_lens=True`, a tuple of a stacked `Tensor` and a 1-D lengths
|
|
380
|
+
`Tensor`, or `None`. When `return_stacked=False` and `return_lens=False`, a `list` of padded
|
|
381
|
+
`Tensor` values or `None`. When `return_stacked=False` and `return_lens=True`, a tuple of a
|
|
382
|
+
`list` of padded `Tensor` values and a 1-D lengths `Tensor`, or `None`. Returns `None` if
|
|
383
|
+
`tensors` is empty.
|
|
384
|
+
|
|
385
|
+
See Also
|
|
386
|
+
--------
|
|
387
|
+
pad_sequence_and_cat : Pad and concatenate along a separate dimension.
|
|
388
|
+
|
|
389
|
+
Examples
|
|
390
|
+
--------
|
|
391
|
+
From the test suite [4], padding three tensors of different sequence lengths and verifying the
|
|
392
|
+
packed shape and recovered lengths:
|
|
393
|
+
|
|
394
|
+
>>> import torch
|
|
395
|
+
>>> from torch_einops_kit import pad_sequence, lens_to_mask
|
|
396
|
+
>>> x, y, z = torch.randn(2, 4, 5), torch.randn(2, 3, 5), torch.randn(2, 1, 5)
|
|
397
|
+
>>> packed, lens = pad_sequence([x, y, z], dim=1, return_lens=True)
|
|
398
|
+
>>> packed.shape
|
|
399
|
+
torch.Size([3, 2, 4, 5])
|
|
400
|
+
>>> lens.tolist()
|
|
401
|
+
[4, 3, 1]
|
|
402
|
+
|
|
403
|
+
From sdft-pytorch [5], left-padding variable-length prompt token sequences and retrieving
|
|
404
|
+
per-sample padding widths for start-position tracking:
|
|
405
|
+
|
|
406
|
+
```python
|
|
407
|
+
student_prompt_ids, student_seq_start_pos = pad_sequence(student_prompt_ids, return_lens=True, left=True, pad_lens=True)
|
|
408
|
+
```
|
|
409
|
+
|
|
410
|
+
From pi-zero-pytorch [6], right-padding a list of discrete action id tensors with a sentinel fill
|
|
411
|
+
value of `-1`:
|
|
412
|
+
|
|
413
|
+
```python
|
|
414
|
+
discrete_action_ids = pad_sequence([tensor(ids) for ids in discrete_action_ids], value=-1)
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
References
|
|
418
|
+
----------
|
|
419
|
+
[1] torch_einops_kit.pad_left_at_dim
|
|
420
|
+
|
|
421
|
+
[2] torch_einops_kit.pad_right_at_dim
|
|
422
|
+
|
|
423
|
+
[3] torch.stack - PyTorch documentation
|
|
424
|
+
https://pytorch.org/docs/stable/generated/torch.stack.html
|
|
425
|
+
[4] tests/test_utils.py
|
|
426
|
+
|
|
427
|
+
[5] lucidrains/sdft-pytorch
|
|
428
|
+
https://github.com/lucidrains/sdft-pytorch
|
|
429
|
+
[6] lucidrains/pi-zero-pytorch
|
|
430
|
+
https://github.com/lucidrains/pi-zero-pytorch
|
|
431
|
+
"""
|
|
432
|
+
output: Tensor | list[Tensor] | tuple[Tensor | list[Tensor], Tensor] | None = None
|
|
433
|
+
|
|
434
|
+
if 0 < len(tensors):
|
|
435
|
+
lens: list[int] | Tensor = [t.shape[dim] for t in tensors]
|
|
436
|
+
max_len: int = max(lens)
|
|
437
|
+
|
|
438
|
+
pad_fn: Callable[..., Tensor] = pad_left_at_dim if left else pad_right_at_dim
|
|
439
|
+
padded_tensors: list[Tensor] = [pad_fn(t, max_len - t_len, dim=dim, value=value) for t, t_len in zip(tensors, lens, strict=True)]
|
|
440
|
+
|
|
441
|
+
if return_stacked:
|
|
442
|
+
output = stack(padded_tensors, dim=dim_stack)
|
|
443
|
+
else:
|
|
444
|
+
output = padded_tensors
|
|
445
|
+
|
|
446
|
+
if return_lens:
|
|
447
|
+
device: torch.device = first(tensors).device
|
|
448
|
+
lens = tensor(lens, device=device)
|
|
449
|
+
|
|
450
|
+
if pad_lens:
|
|
451
|
+
lens = max_len - lens
|
|
452
|
+
|
|
453
|
+
output = (output, lens)
|
|
454
|
+
|
|
455
|
+
return output
|
|
456
|
+
|
|
457
|
+
@overload
|
|
458
|
+
def pad_sequence_and_cat(tensors: Sequence[Tensor], *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> Tensor: ...
|
|
459
|
+
@overload
|
|
460
|
+
def pad_sequence_and_cat(tensors: list[Tensor] = [], *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> None: ... # noqa: B006
|
|
461
|
+
@overload
|
|
462
|
+
def pad_sequence_and_cat(tensors: tuple[()] = (), *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> None: ...
|
|
463
|
+
def pad_sequence_and_cat(tensors: Sequence[Tensor] = (), *, dim_cat: int = 0, dim: int = -1, value: float = 0., left: bool = False) -> Tensor | None:
|
|
464
|
+
"""Pad `tensors` to a shared length along `dim` and concatenate along `dim_cat`.
|
|
465
|
+
|
|
466
|
+
You can use `pad_sequence_and_cat` to align and merge a heterogeneous-length sequence of `Tensor`
|
|
467
|
+
values into a single `Tensor`. `pad_sequence_and_cat` first calls `pad_sequence` [1] with
|
|
468
|
+
`return_stacked=False` to obtain a list of padded `Tensor` values, then concatenates the list
|
|
469
|
+
along `dim_cat` using `torch.cat` [2]. If `tensors` is empty, `pad_sequence_and_cat` returns
|
|
470
|
+
`None`.
|
|
471
|
+
|
|
472
|
+
Parameters
|
|
473
|
+
----------
|
|
474
|
+
tensors : Sequence[Tensor]
|
|
475
|
+
A sequence of `Tensor` values to pad and concatenate. Each `Tensor` must have the same shape
|
|
476
|
+
in every dimension except `dim`.
|
|
477
|
+
dim : int = -1
|
|
478
|
+
The dimension along which lengths vary and padding is applied.
|
|
479
|
+
value : float = 0.0
|
|
480
|
+
The scalar fill value for inserted padding elements.
|
|
481
|
+
left : bool = False
|
|
482
|
+
When `True`, pad at the beginning of `dim`. When `False`, pad at the end.
|
|
483
|
+
dim_cat : int = 0
|
|
484
|
+
The dimension along which to concatenate the padded `Tensor` values.
|
|
485
|
+
|
|
486
|
+
Returns
|
|
487
|
+
-------
|
|
488
|
+
concatenated : Tensor | None
|
|
489
|
+
A single `Tensor` produced by concatenating all padded `Tensor` values along `dim_cat`.
|
|
490
|
+
Returns `None` if `tensors` is empty.
|
|
491
|
+
|
|
492
|
+
See Also
|
|
493
|
+
--------
|
|
494
|
+
pad_sequence : Pad and stack along a new or existing dimension.
|
|
495
|
+
|
|
496
|
+
Examples
|
|
497
|
+
--------
|
|
498
|
+
From the test suite [3], padding images to a common height and concatenating along the batch
|
|
499
|
+
dimension to produce a single batch `Tensor`:
|
|
500
|
+
|
|
501
|
+
>>> import torch
|
|
502
|
+
>>> from torch_einops_kit import pad_sequence, pad_sequence_and_cat
|
|
503
|
+
>>> images = [torch.randn(3, 16, 17), torch.randn(3, 15, 18), torch.randn(3, 17, 16)]
|
|
504
|
+
>>> padded_height = pad_sequence(images, dim=-2, return_stacked=False)
|
|
505
|
+
>>> stacked = pad_sequence_and_cat(padded_height, dim_cat=0)
|
|
506
|
+
>>> stacked.shape
|
|
507
|
+
torch.Size([9, 17, 18])
|
|
508
|
+
|
|
509
|
+
References
|
|
510
|
+
----------
|
|
511
|
+
[1] torch_einops_kit.pad_sequence
|
|
512
|
+
|
|
513
|
+
[2] torch.cat - PyTorch documentation
|
|
514
|
+
https://pytorch.org/docs/stable/generated/torch.cat.html
|
|
515
|
+
[3] tests/test_utils.py
|
|
516
|
+
"""
|
|
517
|
+
padded: Tensor | list[Tensor] | None = pad_sequence(tensors, dim=dim, value=value, left=left, return_stacked=False, return_lens=False)
|
|
518
|
+
if padded is not None: # pyright: ignore[reportUnnecessaryComparison]
|
|
519
|
+
return cat(padded, dim=dim_cat)
|
|
520
|
+
return padded
|
|
521
|
+
|
|
522
|
+
def shift(t: Tensor, amount: int = 1, dim: int = -1, pad_value: float = 0.) -> Tensor:
|
|
523
|
+
"""Shift values in `t` along `dim` while keeping the shape of `t` unchanged.
|
|
524
|
+
|
|
525
|
+
You can use `shift` to move values in `t` along `dim` and fill the vacated positions with
|
|
526
|
+
`pad_value`. `shift` preserves the shape of `t`. A positive `amount` moves values toward larger
|
|
527
|
+
indices along `dim`. A negative `amount` moves values toward smaller indices along `dim`. `shift`
|
|
528
|
+
delegates to `pad_at_dim` [1] with symmetric padding and trimming.
|
|
529
|
+
|
|
530
|
+
Parameters
|
|
531
|
+
----------
|
|
532
|
+
t : Tensor
|
|
533
|
+
The input `Tensor` to shift.
|
|
534
|
+
amount : int = 1
|
|
535
|
+
The number of positions to shift along `dim`. Positive values shift toward larger indices.
|
|
536
|
+
Negative values shift toward smaller indices. Zero returns a `Tensor` equal to `t`.
|
|
537
|
+
dim : int = -1
|
|
538
|
+
The dimension along which to shift `t`.
|
|
539
|
+
pad_value : float = 0.
|
|
540
|
+
The scalar value inserted into positions vacated by the shift.
|
|
541
|
+
|
|
542
|
+
Returns
|
|
543
|
+
-------
|
|
544
|
+
shifted : Tensor
|
|
545
|
+
A `Tensor` with the same shape as `t` after shifting values along `dim` and filling vacated
|
|
546
|
+
positions with `pad_value`.
|
|
547
|
+
|
|
548
|
+
See Also
|
|
549
|
+
--------
|
|
550
|
+
shift_left : Shift values toward smaller indices along one dimension.
|
|
551
|
+
shift_right : Shift values toward larger indices along one dimension.
|
|
552
|
+
pad_at_dim : Pad one dimension while trimming the opposite side.
|
|
553
|
+
|
|
554
|
+
References
|
|
555
|
+
----------
|
|
556
|
+
[1] torch_einops_kit.pad_at_dim
|
|
557
|
+
"""
|
|
558
|
+
return pad_at_dim(t, (amount, -amount), dim=dim, value=pad_value)
|
|
559
|
+
|
|
560
|
+
def shift_left(t: Tensor, amount: int = 1, dim: int = -1, pad_value: float = 0.) -> Tensor:
|
|
561
|
+
"""Shift values in `t` toward smaller indices along `dim`.
|
|
562
|
+
|
|
563
|
+
You can use `shift_left` to move values in `t` toward smaller indices along `dim` while keeping
|
|
564
|
+
the shape of `t` unchanged. `shift_left` fills positions opened at the end of `dim` with
|
|
565
|
+
`pad_value`. `shift_left` calls `shift` [1] with a negated `amount`.
|
|
566
|
+
|
|
567
|
+
Parameters
|
|
568
|
+
----------
|
|
569
|
+
t : Tensor
|
|
570
|
+
The input `Tensor` to shift.
|
|
571
|
+
amount : int = 1
|
|
572
|
+
The number of positions to shift toward smaller indices along `dim`.
|
|
573
|
+
dim : int = -1
|
|
574
|
+
The dimension along which to shift `t`.
|
|
575
|
+
pad_value : float = 0.
|
|
576
|
+
The scalar value inserted into positions vacated by the shift.
|
|
577
|
+
|
|
578
|
+
Returns
|
|
579
|
+
-------
|
|
580
|
+
shifted : Tensor
|
|
581
|
+
A `Tensor` with the same shape as `t` after shifting values toward smaller indices along `dim`
|
|
582
|
+
and filling vacated positions with `pad_value`.
|
|
583
|
+
|
|
584
|
+
See Also
|
|
585
|
+
--------
|
|
586
|
+
shift : Shift values in either direction along one dimension.
|
|
587
|
+
shift_right : Shift values toward larger indices along one dimension.
|
|
588
|
+
|
|
589
|
+
References
|
|
590
|
+
----------
|
|
591
|
+
[1] torch_einops_kit.shift
|
|
592
|
+
"""
|
|
593
|
+
return shift(t, -amount, dim=dim, pad_value=pad_value)
|
|
594
|
+
|
|
595
|
+
def shift_right(t: Tensor, amount: int = 1, dim: int = -1, pad_value: float = 0.) -> Tensor:
|
|
596
|
+
"""Shift values in `t` toward larger indices along `dim`.
|
|
597
|
+
|
|
598
|
+
You can use `shift_right` to move values in `t` toward larger indices along `dim` while keeping
|
|
599
|
+
the shape of `t` unchanged. `shift_right` fills positions opened at the beginning of `dim` with
|
|
600
|
+
`pad_value`. `shift_right` calls `shift` [1] with a positive `amount`.
|
|
601
|
+
|
|
602
|
+
Parameters
|
|
603
|
+
----------
|
|
604
|
+
t : Tensor
|
|
605
|
+
The input `Tensor` to shift.
|
|
606
|
+
amount : int = 1
|
|
607
|
+
The number of positions to shift toward larger indices along `dim`.
|
|
608
|
+
dim : int = -1
|
|
609
|
+
The dimension along which to shift `t`.
|
|
610
|
+
pad_value : float = 0.
|
|
611
|
+
The scalar value inserted into positions vacated by the shift.
|
|
612
|
+
|
|
613
|
+
Returns
|
|
614
|
+
-------
|
|
615
|
+
shifted : Tensor
|
|
616
|
+
A `Tensor` with the same shape as `t` after shifting values toward larger indices along `dim`
|
|
617
|
+
and filling vacated positions with `pad_value`.
|
|
618
|
+
|
|
619
|
+
See Also
|
|
620
|
+
--------
|
|
621
|
+
shift : Shift values in either direction along one dimension.
|
|
622
|
+
shift_left : Shift values toward smaller indices along one dimension.
|
|
623
|
+
|
|
624
|
+
References
|
|
625
|
+
----------
|
|
626
|
+
[1] torch_einops_kit.shift
|
|
627
|
+
"""
|
|
628
|
+
return shift(t, amount, dim=dim, pad_value=pad_value)
|
|
629
|
+
|
|
630
|
+
"""
|
|
631
|
+
Some of the logic in this module may be protected by the following.
|
|
632
|
+
|
|
633
|
+
MIT License
|
|
634
|
+
|
|
635
|
+
Copyright (c) 2026 Phil Wang
|
|
636
|
+
|
|
637
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
638
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
639
|
+
in the Software without restriction, including without limitation the rights
|
|
640
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
641
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
642
|
+
furnished to do so, subject to the following conditions:
|
|
643
|
+
|
|
644
|
+
The above copyright notice and this permission notice shall be included in all
|
|
645
|
+
copies or substantial portions of the Software.
|
|
646
|
+
|
|
647
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
648
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
649
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
650
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
651
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
652
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
653
|
+
SOFTWARE.
|
|
654
|
+
"""
|