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,172 @@
1
+ """Access PyTorch tensor-shaping, masking, padding, `nn.Module` adaptation, and checkpoint utilities.
2
+
3
+ You can use this package for optional-value handling, tensor slicing, rank alignment, mask
4
+ construction from lengths or delimiter values, safe concatenation, sequence padding and shifting,
5
+ PyTree traversal, lightweight `nn.Module` adapters, and `einops` pattern tensor packing.
6
+
7
+ Helpers
8
+ -------
9
+ compact
10
+ Filter `None` values from an iterable and return a `list` of the remaining values.
11
+ default
12
+ Return a fallback value when the primary value is `None`.
13
+ divisible_by
14
+ Test whether one numeric value is evenly divisible by another.
15
+ exists
16
+ Test whether a value is not `None`.
17
+ first
18
+ Return the element at index `0` of an integer-indexable object.
19
+ identity
20
+ Return the first argument unchanged while ignoring all other arguments.
21
+ map_values
22
+ Apply a function to every leaf value in a nested `list`, `tuple`, or `dict` structure.
23
+ maybe
24
+ Wrap a callable so it skips work when the first argument is `None`.
25
+ once
26
+ Wrap a callable so the callable executes at most once.
27
+ safe
28
+ Wrap a callable so `None` values are removed from the first tensor sequence argument.
29
+
30
+ Slicing and reshaping
31
+ ---------------------
32
+ shape_with_replace
33
+ Compute a derived shape by replacing selected dimension sizes.
34
+ slice_at_dim
35
+ Apply an arbitrary `slice` to one tensor dimension.
36
+ slice_left_at_dim
37
+ Select a prefix of a tensor dimension.
38
+ slice_right_at_dim
39
+ Select a suffix of a tensor dimension.
40
+
41
+ Adding dimensions
42
+ -----------------
43
+ align_dims_left
44
+ Pad trailing singleton dimensions across several tensors to a shared rank.
45
+ pad_left_ndim
46
+ Prepend a fixed number of singleton dimensions.
47
+ pad_left_ndim_to
48
+ Prepend singleton dimensions until a tensor reaches a target rank.
49
+ pad_ndim
50
+ Insert singleton dimensions on both sides of a tensor shape.
51
+ pad_right_ndim
52
+ Append a fixed number of singleton dimensions.
53
+ pad_right_ndim_to
54
+ Append singleton dimensions until a tensor reaches a target rank.
55
+
56
+ Mask tools
57
+ ----------
58
+ and_masks
59
+ Combine boolean masks with element-wise logical AND.
60
+ lens_to_mask
61
+ Convert length values into boolean masks.
62
+ mask_after
63
+ Keep positions through the first delimiter value along a dimension.
64
+ mask_before
65
+ Keep positions from the last delimiter value to the end of a dimension.
66
+ or_masks
67
+ Combine boolean masks with element-wise logical OR.
68
+ reduce_masks
69
+ Reduce a sequence of boolean masks with a caller-supplied binary operator.
70
+
71
+ Concatenating and stacking
72
+ --------------------------
73
+ broadcast_cat
74
+ Broadcast tensor groups before concatenation.
75
+ safe_cat
76
+ Concatenate tensors while skipping `None` values.
77
+ safe_stack
78
+ Stack tensors while skipping `None` values.
79
+
80
+ Padding
81
+ -------
82
+ pad_at_dim
83
+ Pad or trim a tensor along one dimension.
84
+ pad_left_at_dim
85
+ Pad the left side of one tensor dimension by an explicit count.
86
+ pad_left_at_dim_to
87
+ Pad the left side of one tensor dimension until it reaches a target length.
88
+ pad_right_at_dim
89
+ Pad the right side of one tensor dimension by an explicit count.
90
+ pad_right_at_dim_to
91
+ Pad the right side of one tensor dimension until it reaches a target length.
92
+ pad_sequence
93
+ Pad a sequence of tensors to a shared length and optionally stack them.
94
+ pad_sequence_and_cat
95
+ Pad a sequence of tensors to a shared length and concatenate the padded tensors.
96
+ shift
97
+ Shift tensor values along one dimension while filling vacated positions.
98
+ shift_left
99
+ Shift tensor values toward smaller indices along one dimension.
100
+ shift_right
101
+ Shift tensor values toward larger indices along one dimension.
102
+
103
+ Utilities
104
+ ---------
105
+ tree_flatten_with_inverse
106
+ Flatten a PyTree and return an inverse reconstruction function.
107
+ tree_map_tensor
108
+ Apply a function to every tensor leaf in a PyTree.
109
+
110
+ Modules
111
+ -------
112
+ device
113
+ Determine `torch.nn.Module` devices and decorate callables to move `Tensor` arguments
114
+ automatically.
115
+ einops
116
+ Pack and unpack `Tensor` objects with `einops` patterns and paired inverse functions.
117
+ nn
118
+ Adapt callables and optional module sequences to the `torch.nn.Module` interface.
119
+ save_load
120
+ Decorate `torch.nn.Module` subclasses with checkpoint save, load, and reconstruction helpers.
121
+ scaleValues
122
+ Compute exclusive prefix sums, normalize feature vectors, and compute masked means.
123
+ """
124
+
125
+ # isort: split
126
+ from __future__ import annotations
127
+
128
+ from torch_einops_kit._theTypes import (
129
+ ConfigArgsKwargs as ConfigArgsKwargs, DehydratedCheckpoint as DehydratedCheckpoint, DehydratedTorchNNModule as DehydratedTorchNNModule,
130
+ DimAndValue as DimAndValue, IdentityCallable as IdentityCallable, InversePackListTensors as InversePackListTensors,
131
+ InversePackTensor as InversePackTensor, PSpec as PSpec, RVar as RVar, StrPath as StrPath, SupportsIntIndex as SupportsIntIndex,
132
+ T_co as T_co, TorchNNModule as TorchNNModule, TVar as TVar, 木 as 木)
133
+
134
+ # isort: split
135
+ from torch_einops_kit._helpers import (
136
+ compact as compact, default as default, divisible_by as divisible_by, exists as exists, first as first, identity as identity,
137
+ map_values as map_values, maybe as maybe, once as once, safe as safe)
138
+
139
+ # isort: split
140
+ from torch_einops_kit._slicing import (
141
+ shape_with_replace as shape_with_replace, slice_at_dim as slice_at_dim, slice_left_at_dim as slice_left_at_dim,
142
+ slice_right_at_dim as slice_right_at_dim)
143
+
144
+ # isort: split
145
+ from torch_einops_kit._dimensions import (
146
+ align_dims_left as align_dims_left, pad_left_ndim as pad_left_ndim, pad_left_ndim_to as pad_left_ndim_to, pad_ndim as pad_ndim,
147
+ pad_right_ndim as pad_right_ndim, pad_right_ndim_to as pad_right_ndim_to,
148
+ pad_right_ndim_to_and_expand_as as pad_right_ndim_to_and_expand_as, repeat_interleave_to_match as repeat_interleave_to_match)
149
+
150
+ # isort: split
151
+ from torch_einops_kit._cat_and_stack import (
152
+ broadcast_cat as broadcast_cat, broadcat as broadcat, safe_cat as safe_cat, safe_stack as safe_stack)
153
+
154
+ # isort: split
155
+ from torch_einops_kit._padding import (
156
+ pad_at_dim as pad_at_dim, pad_left_at_dim as pad_left_at_dim, pad_left_at_dim_to as pad_left_at_dim_to,
157
+ pad_right_at_dim as pad_right_at_dim, pad_right_at_dim_to as pad_right_at_dim_to, pad_sequence as pad_sequence,
158
+ pad_sequence_and_cat as pad_sequence_and_cat, shift as shift, shift_left as shift_left, shift_right as shift_right)
159
+
160
+ # isort: split
161
+ from torch_einops_kit._masking import (
162
+ and_masks as and_masks, lens_to_mask as lens_to_mask, mask_after as mask_after, mask_before as mask_before, or_masks as or_masks,
163
+ reduce_masks as reduce_masks)
164
+
165
+ # isort: split
166
+ from torch_einops_kit.utils import tree_flatten_with_inverse as tree_flatten_with_inverse, tree_map_tensor as tree_map_tensor
167
+
168
+ # isort: split
169
+ # NOTE These imports are for backwards compatibility. Linters ought to tell users to import from the correct submodules.
170
+ from torch_einops_kit.einops import pack_with_inverse # pyright: ignore[reportUnusedImport]
171
+ from torch_einops_kit.nn import Identity, Lambda, Sequential # pyright: ignore[reportUnusedImport]
172
+ from torch_einops_kit.scaleValues import exclusive_cumsum, l2norm, masked_mean, reverse_cumsum # pyright: ignore[reportUnusedImport]
@@ -0,0 +1,197 @@
1
+ from __future__ import annotations
2
+
3
+ from torch import broadcast_tensors, cat, stack, Tensor # pyright: ignore[reportUnknownVariableType]
4
+ from torch_einops_kit import safe
5
+ from typing import cast, TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from collections.abc import Sequence
9
+
10
+ def broadcast_cat(tensors: Sequence[Tensor], dim: int = -1) -> Tensor:
11
+ """Broadcast tensor groups before concatenation.
12
+
13
+ You can use this function to concatenate tensor objects that differ only by broadcastable
14
+ singleton dimensions. `broadcast_cat` first applies `torch.broadcast_tensors` [1] and then
15
+ concatenates the aligned tensor objects with `torch.cat` [1].
16
+
17
+ Parameters
18
+ ----------
19
+ tensors : Sequence[Tensor]
20
+ Iterable of tensor objects that must be broadcast-compatible before concatenation.
21
+ dim : int = -1
22
+ Dimension along which to concatenate the broadcasted tensor objects.
23
+
24
+ Returns
25
+ -------
26
+ concatenated : Tensor
27
+ Concatenated tensor object produced after broadcasting every tensor object in `tensors`.
28
+
29
+ References
30
+ ----------
31
+ [1] PyTorch - Context7
32
+ https://context7.com/pytorch/pytorch
33
+ """
34
+ return cat(cast('list[Tensor]', broadcast_tensors(*tensors)), dim)
35
+
36
+ # NOTE `broadcat` is the identifier used in lucidrains packages.
37
+ broadcat = broadcast_cat
38
+
39
+ @safe
40
+ def safe_cat(tensors: tuple[Tensor, ...] | list[Tensor], dim: int = 0) -> Tensor | None:
41
+ """Concatenate tensors from `tensors` along an existing dimension, skipping `None` values.
42
+
43
+ You can use `safe_cat` to concatenate a mixed sequence of `Tensor` and `None` values. The `safe`
44
+ [1] decorator filters out `None` values from `tensors` before passing the remaining `Tensor`
45
+ values to `torch.cat` [2]. If `tensors` contains no non-`None` values, `safe_cat` returns `None`.
46
+
47
+ A common pattern is iterative accumulation where the accumulator starts as `None`. On the first
48
+ iteration, `safe_cat` receives one non-`None` `Tensor` and returns it unchanged. On subsequent
49
+ iterations, `safe_cat` concatenates the accumulator with the new `Tensor`.
50
+
51
+ Parameters
52
+ ----------
53
+ tensors : tuple[Tensor | None, ...] | list[Tensor | None]
54
+ A sequence of `Tensor` or `None` values. `None` values are filtered out before concatenation.
55
+ All non-`None` `Tensor` values must have the same shape in every dimension except `dim`.
56
+ dim : int = 0
57
+ The dimension along which to concatenate.
58
+
59
+ Returns
60
+ -------
61
+ concatenated : Tensor | None
62
+ The concatenated `Tensor`, or `None` if `tensors` contains no non-`None` values.
63
+
64
+ See Also
65
+ --------
66
+ safe_stack : Stack tensors along a new dimension, skipping `None` values.
67
+
68
+ Examples
69
+ --------
70
+ From the test suite [3]:
71
+
72
+ >>> import torch
73
+ >>> from torch_einops_kit import safe_cat
74
+ >>> t1, t2 = torch.randn(2, 3), torch.randn(2, 3)
75
+ >>> safe_cat([]) is None
76
+ True
77
+ >>> safe_cat([None]) is None
78
+ True
79
+ >>> safe_cat([t1, None]).shape # None is skipped; only t1 is returned
80
+ torch.Size([2, 3])
81
+ >>> safe_cat([t1, t2]).shape
82
+ torch.Size([4, 3])
83
+
84
+ From sdft_pytorch [4], accumulating per-step token losses across a generation loop where
85
+ `token_kl_div_losses` is initialized to `None` before the loop:
86
+
87
+ ```python
88
+ token_kl_div_losses = safe_cat((token_kl_div_losses, token_kl_div), dim=1)
89
+ ```
90
+
91
+ References
92
+ ----------
93
+ [1] torch_einops_kit.safe
94
+
95
+ [2] torch.cat - PyTorch documentation
96
+ https://pytorch.org/docs/stable/generated/torch.cat.html
97
+ [3] tests/test_utils.py
98
+
99
+ [4] lucidrains/sdft-pytorch
100
+ https://github.com/lucidrains/sdft-pytorch
101
+ """
102
+ return None if len(tensors) == 0 else cat(tensors, dim=dim)
103
+
104
+ @safe
105
+ def safe_stack(tensors: tuple[Tensor, ...] | list[Tensor], dim: int = 0) -> Tensor | None:
106
+ """Stack tensors from `tensors` along a new dimension, skipping `None` values.
107
+
108
+ You can use `safe_stack` to stack a mixed sequence of `Tensor` and `None` values. The `safe` [1]
109
+ decorator filters out `None` values from `tensors` before passing the remaining `Tensor` values
110
+ to `torch.stack` [2]. If `tensors` contains no non-`None` values, `safe_stack` returns `None`.
111
+
112
+ Parameters
113
+ ----------
114
+ tensors : tuple[Tensor | None, ...] | list[Tensor | None]
115
+ A sequence of `Tensor` or `None` values. `None` values are filtered out before stacking.
116
+ All non-`None` `Tensor` values must have the same shape.
117
+ dim : int = 0
118
+ The dimension along which to stack. The result has one more dimension than each input
119
+ `Tensor`.
120
+
121
+ Returns
122
+ -------
123
+ stacked : Tensor | None
124
+ The stacked `Tensor`, or `None` if `tensors` contains no non-`None` values.
125
+
126
+ See Also
127
+ --------
128
+ safe_cat : Concatenate tensors along an existing dimension, skipping `None` values.
129
+
130
+ Examples
131
+ --------
132
+ From the test suite [3]:
133
+
134
+ >>> import torch
135
+ >>> from torch_einops_kit import safe_stack
136
+ >>> t1, t2 = torch.randn(2, 3), torch.randn(2, 3)
137
+ >>> safe_stack([]) is None
138
+ True
139
+ >>> safe_stack([None]) is None
140
+ True
141
+ >>> safe_stack([t1]).shape
142
+ torch.Size([1, 2, 3])
143
+ >>> safe_stack([t1, None]).shape # None is skipped; only t1 is stacked
144
+ torch.Size([1, 2, 3])
145
+ >>> safe_stack([t1, t2]).shape
146
+ torch.Size([2, 2, 3])
147
+
148
+ From dreamer4 [4], collecting optional per-layer intermediates where some layers
149
+ may not produce output (returning `None`):
150
+
151
+ ```python
152
+ intermediates = TransformerIntermediates(
153
+ stack(time_attn_kv_caches),
154
+ safe_stack(normed_time_attn_inputs),
155
+ safe_stack(normed_space_attn_inputs),
156
+ safe_stack(rnn_hiddens),
157
+ hiddens,
158
+ )
159
+
160
+ References
161
+ ----------
162
+ [1] torch_einops_kit.safe
163
+
164
+ [2] torch.stack - PyTorch documentation
165
+ https://pytorch.org/docs/stable/generated/torch.stack.html
166
+ [3] tests/test_utils.py
167
+
168
+ [4] lucidrains/dreamer4
169
+ https://github.com/lucidrains/dreamer4
170
+ """
171
+ return None if len(tensors) == 0 else stack(tensors, dim=dim)
172
+
173
+ """
174
+ Some of the logic in this module may be protected by the following.
175
+
176
+ MIT License
177
+
178
+ Copyright (c) 2026 Phil Wang
179
+
180
+ Permission is hereby granted, free of charge, to any person obtaining a copy
181
+ of this software and associated documentation files (the "Software"), to deal
182
+ in the Software without restriction, including without limitation the rights
183
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
184
+ copies of the Software, and to permit persons to whom the Software is
185
+ furnished to do so, subject to the following conditions:
186
+
187
+ The above copyright notice and this permission notice shall be included in all
188
+ copies or substantial portions of the Software.
189
+
190
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
191
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
192
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
193
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
194
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
195
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
196
+ SOFTWARE.
197
+ """