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.
@@ -0,0 +1,523 @@
1
+ from __future__ import annotations
2
+
3
+ from torch_einops_kit import default, divisible_by, exists
4
+ from typing import TYPE_CHECKING
5
+
6
+ if TYPE_CHECKING:
7
+ from collections.abc import Sequence
8
+ from torch import Tensor
9
+
10
+ def pad_right_ndim(t: Tensor, ndims: int) -> Tensor:
11
+ """Reshape a tensor by inserting singleton dimensions at the trailing side.
12
+
13
+ You can use this function to append `ndims` singleton dimensions to a tensor, increasing its rank
14
+ without copying data.
15
+
16
+ Parameters
17
+ ----------
18
+ t : Tensor
19
+ The input tensor to reshape.
20
+ ndims : int
21
+ The number of singleton dimensions to append to the tensor's shape. Must be ≥ 0.
22
+
23
+ Returns
24
+ -------
25
+ padded : Tensor
26
+ A view of `t` with `ndims` trailing singleton dimensions added.
27
+
28
+ See Also
29
+ --------
30
+ pad_ndim : Insert singleton dimensions on both sides of the shape.
31
+ pad_left_ndim : Insert singleton dimensions at the leading side only.
32
+ pad_right_ndim_to : Pad the trailing side until the tensor reaches a target rank.
33
+ align_dims_left : Pad all tensors in a sequence to the same rank.
34
+
35
+ torch
36
+ -----
37
+ This function delegates to `pad_ndim` [1], which uses `torch.Tensor.reshape` [2] to produce a
38
+ view. In einops pattern notation [3], appending two singleton dimensions transforms a pattern `'b
39
+ n d'` to `'b n d 1 1'`, enabling scalar or lower-rank values to broadcast element-wise against a
40
+ higher-rank tensor.
41
+
42
+ References
43
+ ----------
44
+ [1] torch_einops_kit.pad_ndim
45
+
46
+ [2] torch.Tensor.reshape - PyTorch documentation
47
+ https://pytorch.org/docs/stable/generated/torch.Tensor.reshape.html
48
+ [3] einops - Context7
49
+ https://context7.com/arogozhnikov/einops
50
+ """
51
+ return pad_ndim(t, (0, ndims))
52
+
53
+ def align_dims_left(tensors: Sequence[Tensor], *, ndim: int | None = None) -> tuple[Tensor, ...]:
54
+ """Pad all tensors in a sequence with trailing singleton dimensions to a common rank.
55
+
56
+ You can use this function to align a heterogeneous sequence of tensors to the same number of
57
+ dimensions, enabling broadcasting in element-wise operations over tensors with different ranks.
58
+ When `ndim` is `None`, the target rank is the maximum rank across all input tensors.
59
+
60
+ Parameters
61
+ ----------
62
+ tensors : Sequence[Tensor]
63
+ The tensors to align. Each tensor may have a different rank.
64
+ ndim : int | None = None
65
+ The target number of dimensions. When `None`, the largest rank among the input tensors is
66
+ used as the target.
67
+
68
+ Returns
69
+ -------
70
+ aligned : tuple[Tensor, ...]
71
+ A tuple of tensor views, each having exactly `ndim` dimensions, with trailing singleton
72
+ dimensions appended as needed.
73
+
74
+ See Also
75
+ --------
76
+ pad_right_ndim : Append an exact count of trailing singleton dimensions.
77
+ pad_right_ndim_to : Pad the trailing side of a single tensor up to a target rank.
78
+
79
+ torch
80
+ -----
81
+ This function applies `pad_right_ndim` [1] to each tensor using `torch.Tensor.reshape` [2]. In
82
+ einops usage [3], aligning tensor ranks before an `einsum` [3] or element-wise multiply ensures a
83
+ scalar weight of shape `'b'` and a per-token loss of shape `'b n d'` broadcast correctly without
84
+ explicit `rearrange` calls.
85
+
86
+ Examples
87
+ --------
88
+ Align a PPO advantage tensor `(b, n)` with a log-probability ratio tensor `(b, n, d)` for
89
+ element-wise multiplication:
90
+
91
+ ```python
92
+ from torch_einops_kit import align_dims_left
93
+
94
+ # metacontroller: align ratio and advantages before the PPO surrogate loss
95
+ ratio, advantages = align_dims_left((ratio, advantages))
96
+ surr1 = ratio * advantages
97
+ ```
98
+
99
+ Align a noise schedule `(b,)` with a latent tensor `(b, n, d)` for linear interpolation:
100
+
101
+ ```python
102
+ from torch_einops_kit import align_dims_left
103
+
104
+ # dreamer4: align time with latents before noising
105
+ aligned_times, _ = align_dims_left((times, latents))
106
+ noised_latents = noise.lerp(latents, aligned_times)
107
+ ```
108
+
109
+ Align a 1-D time value with an action tensor before flow-matching noise interpolation:
110
+
111
+ ```python
112
+ from torch_einops_kit import align_dims_left
113
+
114
+ # mimic_video: align time with actions for noise interpolation
115
+ actions, left_aligned_time = align_dims_left((actions, time))
116
+ noised = noise.lerp(actions, left_aligned_time)
117
+ ```
118
+
119
+ References
120
+ ----------
121
+ [1] torch_einops_kit.pad_right_ndim
122
+
123
+ [2] torch.Tensor.reshape - PyTorch documentation
124
+ https://pytorch.org/docs/stable/generated/torch.Tensor.reshape.html
125
+ [3] einops - Context7
126
+ https://context7.com/arogozhnikov/einops
127
+ """
128
+ if not exists(ndim):
129
+ ndim = max(t.ndim for t in tensors)
130
+
131
+ return tuple(pad_right_ndim(t, ndim - t.ndim) for t in tensors)
132
+
133
+ def pad_ndim(t: Tensor, ndims: tuple[int, int]) -> Tensor:
134
+ """Reshape a tensor by inserting singleton dimensions on both sides.
135
+
136
+ You can use this function to insert leading and trailing singleton dimensions into a tensor,
137
+ increasing its rank for broadcasting with higher-rank tensors. Set `ndims` to `(left, right)` to
138
+ control how many singleton dimensions appear before and after the existing shape. The function
139
+ raises `ValueError` if either count is negative.
140
+
141
+ Parameters
142
+ ----------
143
+ t : Tensor
144
+ The input tensor to reshape.
145
+ ndims : tuple[int, int]
146
+ The count of singleton dimensions to add on each side. The first element specifies dimensions
147
+ prepended to the shape; the second element specifies dimensions appended. Both values must be
148
+ ≥ 0.
149
+
150
+ Returns
151
+ -------
152
+ padded : Tensor
153
+ A view of `t` with shape `(1,) * left + t.shape + (1,) * right`, where `left, right = ndims`.
154
+
155
+ Raises
156
+ ------
157
+ ValueError
158
+ When either element of `ndims` is negative.
159
+
160
+ See Also
161
+ --------
162
+ pad_left_ndim : Insert singleton dimensions only at the leading side.
163
+ pad_right_ndim : Insert singleton dimensions only at the trailing side.
164
+ pad_left_ndim_to : Pad the leading side until the tensor has a target rank.
165
+ pad_right_ndim_to : Pad the trailing side until the tensor has a target rank.
166
+
167
+ torch
168
+ -----
169
+ This function uses `torch.Tensor.reshape` [1] to produce a view with the requested singleton
170
+ axes. In einops pattern notation [2], adding `left=1` leading and `right=1` trailing dimensions
171
+ transforms a pattern `'b n d'` to `'1 b n d 1'`, without copying data.
172
+
173
+ References
174
+ ----------
175
+ [1] torch.Tensor.reshape - PyTorch documentation
176
+ https://pytorch.org/docs/stable/generated/torch.Tensor.reshape.html
177
+ [2] einops - Context7
178
+ https://context7.com/arogozhnikov/einops
179
+ """
180
+ shape: tuple[int, ...] = t.shape
181
+ left, right = ndims
182
+ if left < 0 or right < 0:
183
+ message: str = f'I received `{left = }` and `{right = }`, but I need both values to be greater than or equal to `0`.'
184
+ raise ValueError(message)
185
+
186
+ ones: tuple[int] = (1,)
187
+ ones_left: tuple[int, ...] = ones * left
188
+ ones_right: tuple[int, ...] = ones * right
189
+ return t.reshape(*ones_left, *shape, *ones_right)
190
+
191
+ def pad_left_ndim(t: Tensor, ndims: int) -> Tensor:
192
+ """Reshape a tensor by inserting singleton dimensions at the leading side.
193
+
194
+ You can use this function to prepend `ndims` singleton dimensions to a tensor, increasing its
195
+ rank without copying data.
196
+
197
+ Parameters
198
+ ----------
199
+ t : Tensor
200
+ The input tensor to reshape.
201
+ ndims : int
202
+ The number of singleton dimensions to prepend to the tensor's shape. Must be ≥ 0.
203
+
204
+ Returns
205
+ -------
206
+ padded : Tensor
207
+ A view of `t` with `ndims` leading singleton dimensions added.
208
+
209
+ See Also
210
+ --------
211
+ pad_ndim : Insert singleton dimensions on both sides of the shape.
212
+ pad_right_ndim : Insert singleton dimensions at the trailing side only.
213
+ pad_left_ndim_to : Pad the leading side until the tensor reaches a target rank.
214
+
215
+ torch
216
+ -----
217
+ This function delegates to `pad_ndim` [1], which uses `torch.Tensor.reshape` [2] to produce a
218
+ view. In einops pattern notation [3], prepending two singleton dimensions transforms a pattern
219
+ `'b n d'` to `'1 1 b n d'`, making the tensor suitable for broadcasting against higher-rank
220
+ tensors without copying data.
221
+
222
+ References
223
+ ----------
224
+ [1] torch_einops_kit.pad_ndim
225
+
226
+ [2] torch.Tensor.reshape - PyTorch documentation
227
+ https://pytorch.org/docs/stable/generated/torch.Tensor.reshape.html
228
+ [3] einops - Context7
229
+ https://context7.com/arogozhnikov/einops
230
+ """
231
+ return pad_ndim(t, (ndims, 0))
232
+
233
+ def pad_left_ndim_to(t: Tensor, ndims: int) -> Tensor:
234
+ """Reshape a tensor by padding leading singleton dimensions up to a target rank.
235
+
236
+ You can use this function to ensure a tensor has at least `ndims` dimensions by prepending
237
+ singleton dimensions at the leading side. The function returns `t` unchanged when `t.ndim` is
238
+ already ≥ `ndims`.
239
+
240
+ Parameters
241
+ ----------
242
+ t : Tensor
243
+ The input tensor to reshape.
244
+ ndims : int
245
+ The target total number of dimensions. Dimensions are added only when `t.ndim < ndims`.
246
+
247
+ Returns
248
+ -------
249
+ padded : Tensor
250
+ A view of `t` with at least `ndims` dimensions.
251
+
252
+ See Also
253
+ --------
254
+ pad_left_ndim : Prepend an exact count of leading singleton dimensions.
255
+ pad_right_ndim_to : Pad the trailing side up to a target rank.
256
+ align_dims_left : Pad all tensors in a sequence to the same rank.
257
+
258
+ torch
259
+ -----
260
+ This function uses `pad_left_ndim` [1], which calls `torch.Tensor.reshape` [2]. In einops pattern
261
+ notation [3], the operation prepends as many `1` axes as needed to align the tensor rank, placing
262
+ existing dimensions on the right so they correspond to the innermost axes of a higher-rank
263
+ reference tensor.
264
+
265
+ References
266
+ ----------
267
+ [1] torch_einops_kit.pad_left_ndim
268
+
269
+ [2] torch.Tensor.reshape - PyTorch documentation
270
+ https://pytorch.org/docs/stable/generated/torch.Tensor.reshape.html
271
+ [3] einops - Context7
272
+ https://context7.com/arogozhnikov/einops
273
+ """
274
+ if t.ndim >= ndims:
275
+ return t
276
+
277
+ return pad_left_ndim(t, ndims - t.ndim)
278
+
279
+ def pad_right_ndim_to(t: Tensor, ndims: int) -> Tensor:
280
+ """Reshape a tensor by padding trailing singleton dimensions up to a target rank.
281
+
282
+ You can use this function to ensure a tensor has at least `ndims` dimensions by appending
283
+ singleton dimensions at the trailing side. The function returns `t` unchanged when `t.ndim` is
284
+ already ≥ `ndims`.
285
+
286
+ Parameters
287
+ ----------
288
+ t : Tensor
289
+ The input tensor to reshape.
290
+ ndims : int
291
+ The target total number of dimensions. Dimensions are added only when `t.ndim < ndims`.
292
+
293
+ Returns
294
+ -------
295
+ padded : Tensor
296
+ A view of `t` with at least `ndims` dimensions.
297
+
298
+ See Also
299
+ --------
300
+ pad_right_ndim : Append an exact count of trailing singleton dimensions.
301
+ pad_left_ndim_to : Pad the leading side up to a target rank.
302
+ align_dims_left : Pad all tensors in a sequence to the same rank.
303
+
304
+ torch
305
+ -----
306
+ This function uses `pad_right_ndim` [1], which calls `torch.Tensor.reshape` [2]. In einops
307
+ pattern notation [3], the operation appends as many `1` axes as needed to align the tensor rank
308
+ before element-wise or `einsum` [3] operations with a higher-rank tensor.
309
+
310
+ Examples
311
+ --------
312
+ Broadcast a scalar time value against a video tensor of shape `(b, c, t, h, w)`
313
+ for flow interpolation:
314
+
315
+ ```python
316
+ from torch_einops_kit import pad_right_ndim_to
317
+
318
+ # dreamer4: align time '(b,)' with video '(b, c, t, h, w)'
319
+ padded_time = pad_right_ndim_to(time[None], video.ndim)
320
+ pred_flow = (pred_video - video) / (1.0 - padded_time)
321
+ ```
322
+
323
+ Scale a flow prediction using a denominator with lower rank than the prediction:
324
+
325
+ ```python
326
+ from torch_einops_kit import pad_right_ndim_to
327
+
328
+ # mimic_video: convert model output to flow space
329
+ pred_flow = (pred - actions) / pad_right_ndim_to(1.0 - action_time, pred.ndim).clamp_min(eps)
330
+ ```
331
+
332
+ References
333
+ ----------
334
+ [1] torch_einops_kit.pad_right_ndim
335
+
336
+ [2] torch.Tensor.reshape - PyTorch documentation
337
+ https://pytorch.org/docs/stable/generated/torch.Tensor.reshape.html
338
+ [3] einops - Context7
339
+ https://context7.com/arogozhnikov/einops
340
+ """
341
+ if t.ndim >= ndims:
342
+ return t
343
+
344
+ return pad_right_ndim(t, ndims - t.ndim)
345
+
346
+ def pad_right_ndim_to_and_expand_as(source: Tensor, target: Tensor) -> Tensor:
347
+ """Expand `source` across the trailing axes of `target`.
348
+
349
+ You can use this function to prepare `source` for `torch.Tensor.gather` [1] or other
350
+ rank-sensitive PyTorch operations against `target`. The function pads `source` with trailing
351
+ singleton dimensions until `source` has the same rank as `target`, then expands `source` across
352
+ the trailing shape contributed by `target`. The function returns a view when PyTorch can represent
353
+ the result without copying data.
354
+
355
+ Parameters
356
+ ----------
357
+ source : Tensor
358
+ The tensor to pad and expand.
359
+ target : Tensor
360
+ The reference tensor whose trailing axes determine the expanded shape.
361
+
362
+ Returns
363
+ -------
364
+ expanded : Tensor
365
+ A tensor view with shape `source.shape + target.shape[source.ndim:]` when `target.ndim >
366
+ source.ndim`. When `target.ndim <= source.ndim`, the returned tensor keeps `source.shape`.
367
+
368
+ See Also
369
+ --------
370
+ `pad_right_ndim_to`
371
+ Pad trailing singleton dimensions without expanding values.
372
+ `align_dims_left`
373
+ Align several tensors for broadcasting by padding trailing singleton dimensions.
374
+
375
+ PyTorch
376
+ -------
377
+ expansion : Tensor view
378
+ This function calls `pad_right_ndim_to` [2] and then `torch.Tensor.expand` [3]. The expansion
379
+ repeats metadata rather than materializing copies, so a gather index tensor can be broadcast
380
+ from shape `(b, k)` to `(b, k, d)` before `torch.Tensor.gather` [1].
381
+
382
+ Examples
383
+ --------
384
+ This example simplifies the flattened gather pattern from `rigidformer` [4].
385
+
386
+ ```python
387
+ from torch_einops_kit import pad_right_ndim_to_and_expand_as
388
+
389
+ safe_idx = pad_right_ndim_to_and_expand_as(safe_idx, all_pos) other_pos = all_pos.gather(1,
390
+ safe_idx)
391
+ ```
392
+
393
+ This example mirrors `gather_vectors()` in `worldparticle` [5].
394
+
395
+ ```python
396
+ from torch_einops_kit import pad_right_ndim_to_and_expand_as
397
+
398
+ expanded_indices = pad_right_ndim_to_and_expand_as(indices, src) gathered = src.gather(1,
399
+ expanded_indices)
400
+ ```
401
+
402
+ References
403
+ ----------
404
+ [1] torch.Tensor.gather - PyTorch documentation
405
+ https://pytorch.org/docs/stable/generated/torch.Tensor.gather.html
406
+ [2] `pad_right_ndim_to`
407
+
408
+ [3] torch.Tensor.expand - PyTorch documentation
409
+ https://pytorch.org/docs/stable/generated/torch.Tensor.expand.html
410
+ [4] lucidrains/rigidformer `rigidformer.py`
411
+ https://github.com/lucidrains/rigidformer/blob/main/rigidformer/rigidformer.py
412
+ [5] lucidrains/worldparticle `worldparticle.py`
413
+ https://github.com/lucidrains/worldparticle/blob/main/worldparticle/worldparticle.py
414
+ """
415
+ shape: list[int] = [*source.shape, *target.shape[source.ndim:None]]
416
+ source = pad_right_ndim_to(source, target.ndim)
417
+ return source.expand(shape)
418
+
419
+ def repeat_interleave_to_match(t: Tensor, target: Tensor | int, dim: int = 0, target_dim: int | None = None) -> Tensor:
420
+ """Repeat slices of `t` along `dim` until `t` matches the target length.
421
+
422
+ You can use this function to align the length of `t` along `dim` with an integer target length or
423
+ with the size of `Tensor` `target` along `target_dim`. The function returns `t` unchanged when the
424
+ lengths already match. Otherwise the function repeats each slice of `t` the same number of times
425
+ with `torch.Tensor.repeat_interleave` [1].
426
+
427
+ Parameters
428
+ ----------
429
+ t : Tensor
430
+ The tensor whose size along `dim` will be matched to the resolved target length.
431
+ target : Tensor | int
432
+ Either the target length directly, or a tensor whose size provides the target length.
433
+ dim : int = 0
434
+ The axis of `t` whose length will be repeated.
435
+ target_dim : int | None = None
436
+ The axis of `target` whose length will be used when `target` is a tensor. When `target_dim` is
437
+ `None`, the function uses `dim`.
438
+
439
+ Returns
440
+ -------
441
+ matched : Tensor
442
+ `t` itself when the resolved target length already equals `t.shape[dim]`. Otherwise a tensor
443
+ whose size along `dim` equals the resolved target length.
444
+
445
+ Raises
446
+ ------
447
+ ValueError
448
+ When the resolved target length is not divisible by `t.shape[dim]`.
449
+
450
+ See Also
451
+ --------
452
+ `align_dims_left`
453
+ Align tensor ranks for broadcasting without material repetition.
454
+ `pad_right_ndim_to_and_expand_as`
455
+ Expand a tensor across trailing axes of a reference tensor instead of repeating values along
456
+ one axis.
457
+
458
+ PyTorch
459
+ -------
460
+ repeat factor : int
461
+ This function resolves the target length, computes `repeatFactor = len_target // len_t`, and
462
+ applies `torch.Tensor.repeat_interleave` [1]. When the resolved target length already equals
463
+ `t.shape[dim]`, the function returns the original tensor object instead of allocating a new
464
+ tensor. In `dreamer4` [2], this behavior repeats per-sequence `time_lens` after spatial
465
+ packing so the hierarchical temporal transformer receives one length per packed token stream.
466
+
467
+ Examples
468
+ --------
469
+ This example simplifies the hierarchical temporal length expansion in `dreamer4` [2].
470
+
471
+ ```python
472
+ from torch_einops_kit import repeat_interleave_to_match import torch
473
+
474
+ time_lens = torch.tensor([6, 12]) tokens = torch.randn(4, 32, 512)
475
+
476
+ h_net_lens = repeat_interleave_to_match(time_lens, tokens) assert h_net_lens.tolist() == [6,
477
+ 6, 12, 12]
478
+ ```
479
+
480
+ References
481
+ ----------
482
+ [1] torch.Tensor.repeat_interleave - PyTorch documentation
483
+ https://pytorch.org/docs/stable/generated/torch.Tensor.repeat_interleave.html
484
+ [2] lucidrains/dreamer4 `dreamer4.py`
485
+ https://github.com/lucidrains/dreamer4/blob/main/dreamer4/dreamer4.py
486
+ """
487
+ len_t: int = t.shape[dim]
488
+ len_target: int = target if isinstance(target, int) else target.shape[default(target_dim, dim)]
489
+
490
+ if len_t == len_target:
491
+ return t
492
+
493
+ if not divisible_by(len_target, len_t):
494
+ message: str = f'I received `{len_target = }` and `{len_t = }`, but I need `len_target` to be divisible by `len_t`.'
495
+ raise ValueError(message)
496
+
497
+ return t.repeat_interleave(len_target // len_t, dim=dim)
498
+
499
+ """
500
+ Some of the logic in this module may be protected by the following.
501
+
502
+ MIT License
503
+
504
+ Copyright (c) 2026 Phil Wang
505
+
506
+ Permission is hereby granted, free of charge, to any person obtaining a copy
507
+ of this software and associated documentation files (the "Software"), to deal
508
+ in the Software without restriction, including without limitation the rights
509
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
510
+ copies of the Software, and to permit persons to whom the Software is
511
+ furnished to do so, subject to the following conditions:
512
+
513
+ The above copyright notice and this permission notice shall be included in all
514
+ copies or substantial portions of the Software.
515
+
516
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
517
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
518
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
519
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
520
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
521
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
522
+ SOFTWARE.
523
+ """