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,482 @@
1
+ Metadata-Version: 2.4
2
+ Name: torch-einops-kit
3
+ Version: 0.1.8
4
+ Summary: Typed tensor-shaping, masking, padding, device-routing, and checkpoint utilities for PyTorch and `einops`. A superset of `lucidrains/torch-einops-utils` with similar utilities from other lucidrains packages. Adds strict typing, extensive tests, and comprehensive docstrings.
5
+ Keywords: artificial intelligence,einops,machine learning,pytorch,torch
6
+ Author: Hunter Hogan
7
+ Author-email: Hunter Hogan <HunterHogan@pm.me>
8
+ License-Expression: CC-BY-NC-4.0
9
+ License-File: LICENSE
10
+ License-File: LICENSE-WANG
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Environment :: GPU :: NVIDIA CUDA
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Natural Language :: English
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Utilities
22
+ Classifier: Typing :: Typed
23
+ Requires-Dist: einops>=0.8.2
24
+ Requires-Dist: huntermakespy>=0.7.0
25
+ Requires-Dist: torch>=2.0.0
26
+ Requires-Dist: typing-extensions>=4.0.0
27
+ Maintainer: Hunter Hogan
28
+ Maintainer-email: Hunter Hogan <HunterHogan@pm.me>
29
+ Requires-Python: >=3.10
30
+ Project-URL: Context7, https://context7.com/hunterhogan/torch_einops_kit
31
+ Project-URL: Donate, https://www.patreon.com/integrated
32
+ Project-URL: Download, https://pypi.org/project/torch_einops_kit
33
+ Project-URL: Homepage, https://github.com/hunterhogan/torch_einops_kit
34
+ Project-URL: Issues, https://github.com/hunterhogan/torch_einops_kit/issues
35
+ Project-URL: Repository, https://github.com/hunterhogan/torch_einops_kit.git
36
+ Description-Content-Type: text/markdown
37
+
38
+ # torch_einops_kit
39
+
40
+ Typed tensor-shaping, masking, padding, device-routing, lightweight `nn.Module` adapters, and checkpoint utilities for PyTorch and `einops`.
41
+
42
+ [![pip install torch-einops-kit](https://img.shields.io/badge/pip_install-torch--einops--kit-gray.svg?labelColor=blue)](https://pypi.org/project/torch-einops-kit/)
43
+ [![uv add torch-einops-kit](https://img.shields.io/badge/uv_add-torch--einops--kit-gray.svg?labelColor=blue)](https://pypi.org/project/torch-einops-kit/)
44
+
45
+ This repository is a superset of [`lucidrains/torch-einops-utils`](https://github.com/lucidrains/torch-einops-utils). The upstream repository is a compact collection of small utilities that show up repeatedly in lucidrains model repositories. `torch_einops_kit` keeps that role. The main difference is emphasis. This fork adds roughly 6000 lines of tests, typing, and docstrings, optimizes some of the original utility functions, and expands the original test suite from about 30 tests to roughly 1230 tests total so the utility layer is easier to trust, easier to search, and easier to apply correctly.
46
+
47
+ `torch_einops_kit` is most useful when combined with other lucidrains repositories. Repositories such as [`dreamer4`](https://github.com/lucidrains/dreamer4), [`metacontroller`](https://github.com/lucidrains/metacontroller), [`mimic-video`](https://github.com/lucidrains/mimic-video), [`pi-zero-pytorch`](https://github.com/lucidrains/pi-zero-pytorch), [`sdft-pytorch`](https://github.com/lucidrains/sdft-pytorch), and [`locoformer`](https://github.com/lucidrains/locoformer) repeatedly need operations such as `align_dims_left`, `shape_with_replace`, `lens_to_mask`, `pad_sequence`, `safe_cat`, and `pack_with_inverse`. This package centralizes those operations in one typed import surface instead of re-implementing the same tensor utility layer in each model repository.
48
+
49
+ If you already know `torch-einops-utils`, `torch_einops_kit` began as a typed substitute for that package and has since grown into a superset. In addition to everything from `torch-einops-utils`, this repository centralizes small utility functions that appear repeatedly in other lucidrains model repositories but were never collected in one place, such as `l2norm`, `once`, `pack_one`, and `unpack_one`. The function family remains the same kind: small PyTorch and `einops` helpers for shape work, masks, padding, optional tensors, PyTree traversal, device routing, lightweight `nn.Module` adaptation, and checkpoint reconstruction. The import path is `torch_einops_kit`, not `torch_einops_utils`. The relationship is conceptual, not literal import-path compatibility.
50
+
51
+ Use `torch_einops_kit` when you want strict typing, a `py.typed` marker, focused modules, extensive tests, and docstrings written for both humans and AI assistants. Use upstream when you want the most compact possible version of the same idea.
52
+
53
+ ## At a glance
54
+
55
+ - Project name: `torch_einops_kit`.
56
+ - Import path: `torch_einops_kit`.
57
+ - Python requirement: `>=3.10`.
58
+ - Runtime dependencies: `torch`, `einops`, and `typing-extensions`.
59
+ - Root package exports: helper functions, slicing helpers, rank-alignment helpers, mask helpers, safe concatenation helpers, padding helpers, normalization helpers, and PyTree / `einops` helpers.
60
+ - Submodules with dedicated imports: `torch_einops_kit.device`, `torch_einops_kit.einops`, `torch_einops_kit.nn`, `torch_einops_kit.save_load`, and `torch_einops_kit.scaleValues`.
61
+ - Typing status: the package ships a `py.typed` marker and the repository uses strict type checking.
62
+
63
+ ## Installation
64
+
65
+ ### `uv`
66
+
67
+ ```bash
68
+ uv add torch_einops_kit
69
+ ```
70
+
71
+ ### `pip`
72
+
73
+ ```bash
74
+ pip install torch_einops_kit
75
+ ```
76
+
77
+ ## Import map
78
+
79
+ Import most tensor helpers from the package root:
80
+
81
+ ```python
82
+ from torch_einops_kit import (
83
+ align_dims_left,
84
+ and_masks,
85
+ broadcast_cat,
86
+ lens_to_mask,
87
+ mask_after,
88
+ mask_before,
89
+ maybe,
90
+ once,
91
+ or_masks,
92
+ pad_sequence,
93
+ pad_sequence_and_cat,
94
+ reverse_cumsum,
95
+ safe_cat,
96
+ safe_stack,
97
+ shape_with_replace,
98
+ shift,
99
+ shift_left,
100
+ shift_right,
101
+ slice_at_dim,
102
+ tree_flatten_with_inverse,
103
+ tree_map_tensor,
104
+ )
105
+ ```
106
+
107
+ Import einops pack and unpack helpers from `torch_einops_kit.einops`:
108
+
109
+ ```python
110
+ from torch_einops_kit.einops import (
111
+ pack_one,
112
+ pack_with_inverse,
113
+ unpack_one,
114
+ )
115
+ ```
116
+
117
+ Import device decorators from `torch_einops_kit.device`:
118
+
119
+ ```python
120
+ from torch_einops_kit.device import (
121
+ module_device,
122
+ move_inputs_to_device,
123
+ move_inputs_to_module_device,
124
+ )
125
+ ```
126
+
127
+ Import lightweight `nn.Module` adapters from `torch_einops_kit.nn`:
128
+
129
+ ```python
130
+ from torch_einops_kit.nn import (
131
+ Identity,
132
+ Lambda,
133
+ Sequential,
134
+ )
135
+ ```
136
+
137
+ Import checkpoint decorators from `torch_einops_kit.save_load`:
138
+
139
+ ```python
140
+ from torch_einops_kit.save_load import (
141
+ dehydrate_config,
142
+ rehydrate_config,
143
+ save_load,
144
+ )
145
+ ```
146
+
147
+ Import normalization and masked-reduction helpers from `torch_einops_kit.scaleValues`:
148
+
149
+ ```python
150
+ from torch_einops_kit.scaleValues import (
151
+ exclusive_cumsum,
152
+ l2norm,
153
+ RMSNorm,
154
+ masked_mean,
155
+ reverse_cumsum,
156
+ )
157
+ ```
158
+
159
+ ## Quick examples
160
+
161
+ ### Batch variable-length tensors and build a mask
162
+
163
+ This example comes directly from the test suite.
164
+
165
+ ```python
166
+ import torch
167
+
168
+ from torch_einops_kit import lens_to_mask, pad_sequence
169
+
170
+ x = torch.randn(2, 4, 5)
171
+ y = torch.randn(2, 3, 5)
172
+ z = torch.randn(2, 1, 5)
173
+
174
+ packed, lens = pad_sequence([x, y, z], dim=1, return_lens=True)
175
+ mask = lens_to_mask(lens)
176
+
177
+ assert packed.shape == (3, 2, 4, 5)
178
+ assert lens.tolist() == [4, 3, 1]
179
+ assert torch.allclose(mask.sum(dim=-1), lens)
180
+ ```
181
+
182
+ ### Pack with `einops` and keep an inverse function
183
+
184
+ This example also comes directly from the test suite.
185
+
186
+ ```python
187
+ import torch
188
+
189
+ from torch_einops_kit import pack_with_inverse
190
+
191
+ t = torch.randn(3, 12, 2, 2)
192
+ packed, inverse = pack_with_inverse(t, "b * d")
193
+
194
+ assert packed.shape == (3, 24, 2)
195
+
196
+ restored = inverse(packed)
197
+ assert restored.shape == (3, 12, 2, 2)
198
+ ```
199
+
200
+ ### Decorate a module with save / load helpers
201
+
202
+ This example is adapted from `tests/test_save_load.py`.
203
+
204
+ ```python
205
+ from pathlib import Path
206
+
207
+ from torch import Tensor, nn
208
+
209
+ from torch_einops_kit.save_load import save_load
210
+
211
+
212
+ @save_load()
213
+ class SimpleNet(nn.Module):
214
+ def __init__(self, dim: int, hidden_dim: int) -> None:
215
+ super().__init__()
216
+ self.dim = dim
217
+ self.hidden_dim = hidden_dim
218
+ self.net = nn.Linear(dim, hidden_dim)
219
+
220
+ def forward(self, x: Tensor) -> Tensor:
221
+ return self.net(x)
222
+
223
+
224
+ path = Path("model.pt")
225
+ model = SimpleNet(10, 20)
226
+ model.save(str(path))
227
+
228
+ restored = SimpleNet.init_and_load(str(path))
229
+ assert restored.dim == 10
230
+ assert restored.hidden_dim == 20
231
+ ```
232
+
233
+ ## Root API reference
234
+
235
+ ### Optional-value and structure helpers
236
+
237
+ | Name | Contract |
238
+ | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
239
+ | `exists(v)` | Returns `True` exactly when `v is not None`. Falsy values such as `0`, `False`, and `[]` still count as existing values. The return type is a `TypeGuard`, so static analyzers narrow the type after the check. |
240
+ | `default(v, d)` | Returns `v` when `v` exists. Returns `d` when `v is None`. |
241
+ | `compact(arr)` | Removes every `None` value from `arr` and returns a `list` of the remaining values. |
242
+ | `divisible_by(num, den)` | Returns `False` when `den == 0`. Otherwise returns whether `num % den == 0`. |
243
+ | `identity(t, *args, **kwargs)` | Returns `t` unchanged and ignores every extra argument. Useful as a no-op callable. |
244
+ | `first(arr)` | Returns `arr[0]`. Use `first` when the sequence supports integer indexing and index `0` is valid. |
245
+ | `map_values(fn, v)` | Recursively applies `fn` to every leaf value inside nested `list`, `tuple`, and `dict` structures. Container shape is preserved. |
246
+ | `maybe(fn)` | Wraps `fn` so the wrapped callable returns `None` when the first argument is `None`. When `fn` itself is `None`, `maybe(None)` returns `identity`. |
247
+ | `once(fn)` | Wraps `fn` so the wrapped callable executes at most once. On the first call the function runs and returns its result. On every subsequent call the wrapper returns `None` without calling `fn`. |
248
+ | `safe(fn)` | Decorator for callables whose first argument is `Sequence[Tensor]`. The decorator removes `None` values from that first argument before the call. If no tensors remain, the decorator returns `None` instead of calling `fn`. |
249
+
250
+ ### Shape and slicing helpers
251
+
252
+ | Name | Contract |
253
+ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
254
+ | `shape_with_replace(t, replace_dict=None)` | Returns a derived `torch.Size` based on `t.shape`. The function does not modify `t`. Keys in `replace_dict` must be non-negative integers less than `t.ndim`. |
255
+ | `slice_at_dim(t, slc, dim=-1)` | Applies `slc` to one dimension and preserves every other dimension. Negative `dim` values are normalized before indexing. |
256
+ | `slice_left_at_dim(t, length, dim=-1)` | Keeps the first `length` values along `dim`. When `length == 0`, the function returns an empty slice along `dim`. |
257
+ | `slice_right_at_dim(t, length, dim=-1)` | Keeps the last `length` values along `dim`. When `length == 0`, the function returns an empty slice along `dim`. |
258
+
259
+ ### Rank-alignment and singleton-dimension helpers
260
+
261
+ These functions change shape by inserting singleton dimensions. These functions do not add numeric padding values.
262
+
263
+ | Name | Contract |
264
+ | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
265
+ | `pad_ndim(t, (left, right))` | Returns a reshaped view of `t` with `left` leading singleton dimensions and `right` trailing singleton dimensions. Raises `ValueError` when either count is negative. |
266
+ | `pad_left_ndim(t, ndims)` | Prepends `ndims` singleton dimensions. |
267
+ | `pad_right_ndim(t, ndims)` | Appends `ndims` singleton dimensions. |
268
+ | `pad_left_ndim_to(t, ndims)` | Ensures that `t.ndim >= ndims` by prepending singleton dimensions when needed. Returns `t` unchanged when `t.ndim >= ndims`. |
269
+ | `pad_right_ndim_to(t, ndims)` | Ensures that `t.ndim >= ndims` by appending singleton dimensions when needed. Returns `t` unchanged when `t.ndim >= ndims`. |
270
+ | `align_dims_left(tensors, ndim=None)` | Aligns every tensor to a shared rank by appending trailing singleton dimensions. Existing dimensions stay left-aligned. When `ndim is None`, the target rank is the maximum rank across the input tensors. |
271
+
272
+ ### Mask helpers
273
+
274
+ | Name | Contract |
275
+ | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
276
+ | `lens_to_mask(lens, max_len=None)` | Converts integer length values to a boolean mask with shape `(*lens.shape, max_len)`. Position `i` in the final axis is `True` when `i < lens[...]`. |
277
+ | `mask_after(t, value, dim=-1, inclusive=True)` | Returns a boolean mask that stays `True` until the first occurrence of `value` along `dim`. When `inclusive=True`, the matching position remains `True`; when `inclusive=False`, it becomes `False`. If `value` never appears in a slice, the whole slice remains `True`. |
278
+ | `mask_before(t, value, dim=-1, inclusive=True)` | Returns a boolean mask that stays `True` from the last occurrence of `value` through the end of each slice along `dim`. When `inclusive=True`, the matching position remains `True`; when `inclusive=False`, it becomes `False`. If `value` never appears in a slice, the whole slice remains `True`. |
279
+ | `reduce_masks(masks, op)` | Filters out `None` values, then reduces the remaining masks left-to-right with `op`. Returns `None` when no non-`None` masks remain. |
280
+ | `and_masks(masks)` | Equivalent to `reduce_masks(masks, torch.logical_and)`. Returns `None` when no active mask remains. |
281
+ | `or_masks(masks)` | Equivalent to `reduce_masks(masks, torch.logical_or)`. Returns `None` when no active mask remains. |
282
+
283
+ ### Concatenation and stacking helpers
284
+
285
+ | Name | Contract |
286
+ | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
287
+ | `broadcast_cat(tensors, dim=0)` | Broadcasts tensor groups before concatenation. |
288
+ | `safe_stack(tensors, dim=0)` | Removes `None` values, then applies `torch.stack`. Returns `None` when no active tensor remains. Even a single tensor is stacked, so the result gains a new dimension. |
289
+ | `safe_cat(tensors, dim=0)` | Removes `None` values, then applies `torch.cat`. Returns `None` when no active tensor remains. A single surviving tensor is returned unchanged because `torch.cat` over one tensor is identity. |
290
+
291
+ ### Numeric padding and batching helpers
292
+
293
+ These functions add numeric padding values along an existing tensor dimension.
294
+
295
+ | Name | Contract |
296
+ | ------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
297
+ | `pad_at_dim(t, (left, right), dim=-1, value=0.0)` | Pads or trims `t` along one dimension. Positive values add elements. Negative values trim elements. |
298
+ | `pad_left_at_dim(t, pad, dim=-1, value=0.0)` | Prepends `pad` values along `dim`. |
299
+ | `pad_right_at_dim(t, pad, dim=-1, value=0.0)` | Appends `pad` values along `dim`. |
300
+ | `pad_left_at_dim_to(t, length, dim=-1, value=0.0)` | Ensures that `t.shape[dim] >= length` by left-padding when needed. Returns `t` unchanged when the target length is already satisfied. |
301
+ | `pad_right_at_dim_to(t, length, dim=-1, value=0.0)` | Ensures that `t.shape[dim] >= length` by right-padding when needed. Returns `t` unchanged when the target length is already satisfied. |
302
+ | `pad_sequence(tensors, ...)` | Pads every tensor in `tensors` to the maximum length along `dim`. The function can return a stacked tensor or a list of padded tensors. The function can also return original lengths or padding widths. Returns `None` for empty input. |
303
+ | `pad_sequence_and_cat(tensors, dim_cat=0, dim=-1, value=0.0, left=False)` | Equivalent to `pad_sequence(..., return_stacked=False)` followed by `torch.cat(..., dim=dim_cat)`. Returns `None` for empty input. |
304
+ | `shift(t, amount=1, dim=-1, pad_value=0.0)` | Shifts tensor values along `dim` while keeping the shape unchanged. Positive `amount` shifts toward larger indices, negative `amount` shifts toward smaller indices, and vacated positions are filled with `pad_value`. |
305
+ | `shift_left(t, amount=1, dim=-1, pad_value=0.0)` | Equivalent to `shift(t, -amount, ...)`. Moves values toward smaller indices and fills the opened positions at the end of `dim` with `pad_value`. |
306
+ | `shift_right(t, amount=1, dim=-1, pad_value=0.0)` | Equivalent to `shift(t, amount, ...)`. Moves values toward larger indices and fills the opened positions at the beginning of `dim` with `pad_value`. |
307
+
308
+ #### `pad_sequence` return modes
309
+
310
+ `pad_sequence` is overloaded. The return type depends on `return_stacked` and `return_lens`.
311
+
312
+ | `return_stacked` | `return_lens` | Return type |
313
+ | ---------------- | ------------- | ------------------------------------- |
314
+ | `True` | `False` | `Tensor \| None` |
315
+ | `True` | `True` | `tuple[Tensor, Tensor] \| None` |
316
+ | `False` | `False` | `list[Tensor] \| None` |
317
+ | `False` | `True` | `tuple[list[Tensor], Tensor] \| None` |
318
+
319
+ When `pad_lens=True` and `return_lens=True`, the second tensor contains padding widths rather than original lengths.
320
+
321
+ ### PyTree helpers
322
+
323
+ | Name | Contract |
324
+ | --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
325
+ | `tree_map_tensor(fn, tree)` | Applies `fn` to every tensor leaf in a PyTree and leaves non-tensor leaves unchanged. |
326
+ | `tree_flatten_with_inverse(tree)` | Returns a flat list of leaves and an inverse function that reconstructs the original PyTree shape from a replacement iterable of leaves. |
327
+
328
+ ## `scaleValues` submodule reference
329
+
330
+ The `torch_einops_kit.scaleValues` submodule contains exclusive and reverse cumulative sums, vector normalization, masked mean computation, and the `RMSNorm` layer.
331
+
332
+ | Name | Contract |
333
+ | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
334
+ | `exclusive_cumsum(t, dim=-1)` | Computes the exclusive prefix sum of `t` along `dim`. Each output position receives the sum of all elements that strictly precede it along `dim`. The element at index zero is always zero. |
335
+ | `l2norm(t)` | Normalizes each vector in `t` to unit length along the last dimension. Delegates to `torch.nn.functional.normalize` with `p=2` and `dim=-1`. |
336
+ | `masked_mean(t, mask=None, dim=None, eps=1e-5)` | Computes a masked mean. When `mask is None`, the function falls back to `t.mean(...)`. When no masked position is selected and `dim is None`, the function returns zero by summing over the empty selection. When `mask.ndim < t.ndim`, the function right-pads mask rank before broadcasting. |
337
+ | `reverse_cumsum(t, dim=-1, keepdim=True)` | Computes the reverse cumulative sum of `t` along `dim`, so each output position receives the sum of the current element and all later elements along that dimension. With `keepdim=True`, the summed dimension is retained before the total is broadcast back across `t`. |
338
+ | `RMSNorm(dim)` | `torch.nn.Module` that normalizes the last feature axis to unit length, multiplies by `√dim`, and applies a learned per-feature `gamma` parameter. Use as a pre-normalization layer before attention, feedforward, or linear projection sublayers in transformer-style modules. |
339
+
340
+ ## `einops` submodule reference
341
+
342
+ The `torch_einops_kit.einops` submodule contains pack and unpack utilities with paired inverse functions.
343
+
344
+ | Name | Contract |
345
+ | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
346
+ | `pack_one(t, pattern)` | Packs one tensor using an einops pattern and returns the packed tensor and shape metadata for paired reconstruction with `unpack_one`. |
347
+ | `pack_with_inverse(t, pattern)` | Wraps `einops.pack` and stores the corresponding inverse. Input `t` may be one tensor or a `list[Tensor]`. When `t` is one tensor, the inverse has type `InversePackTensor` and returns one tensor. When `t` is a `list[Tensor]`, the inverse has type `InversePackListTensors` and returns `list[Tensor]`. The inverse optionally accepts a different `inv_pattern` for unpacking. |
348
+ | `unpack_one(t, ps, pattern)` | Unpacks one tensor using packed-shape metadata produced by `pack_one`. |
349
+
350
+ ## `device` submodule reference
351
+
352
+ The `torch_einops_kit.device` submodule contains three utilities for device inference and automatic tensor movement.
353
+
354
+ | Name | Contract |
355
+ | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
356
+ | `module_device(m)` | Returns the device of the first parameter or registered buffer in `m`. Returns `None` when `m` has neither parameters nor buffers. |
357
+ | `move_inputs_to_device(device)` | Decorator that recursively moves every tensor inside positional and keyword arguments to `device` before calling the wrapped function. Non-tensor values pass through unchanged. |
358
+ | `move_inputs_to_module_device(fn)` | Decorator for methods whose first argument is a `torch.nn.Module`. The decorator infers the target device with `module_device(self)` and moves every tensor argument after `self` to that device. If `module_device(self)` returns `None`, the call is a no-op. |
359
+
360
+ ## `nn` submodule reference
361
+
362
+ The `torch_einops_kit.nn` submodule contains lightweight `torch.nn.Module` adapters and a `Sequential` constructor that ignores `None` values.
363
+
364
+ | Name | Contract |
365
+ | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
366
+ | `Sequential(*modules)` | Equivalent to `nn.Sequential(*compact(modules))`. Every `None` argument is discarded before construction. |
367
+ | `Identity()` | `torch.nn.Module` wrapper around `identity`. Unlike `torch.nn.Identity`, `Identity.forward` accepts additional positional arguments and keyword arguments and returns the first positional argument unchanged. |
368
+ | `Lambda(fn)` | `torch.nn.Module` wrapper that stores `fn` on `self.fn` and delegates `forward(*args, **kwargs)` to `fn(*args, **kwargs)` without changing the argument structure. |
369
+
370
+ ## `save_load` submodule reference
371
+
372
+ The `torch_einops_kit.save_load` submodule contains the checkpoint decorator and the two advanced configuration helpers that support nested decorated modules.
373
+
374
+ | Name | Contract |
375
+ | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
376
+ | `save_load(...)` | Class decorator for `torch.nn.Module` subclasses. The decorator records constructor arguments on each instance and adds instance save / load methods plus a classmethod that reconstructs a new instance from a checkpoint. |
377
+ | `dehydrate_config(config, config_instance_var_name)` | Walks nested `list`, `tuple`, and `dict` structures and replaces decorated module instances with reconstruction records. |
378
+ | `rehydrate_config(config)` | Walks nested `list`, `tuple`, and `dict` structures and reconstructs decorated modules from the stored reconstruction records. |
379
+
380
+ ### Default `save_load` method names
381
+
382
+ The default decorator call is `@save_load()`. That default adds:
383
+
384
+ - `save(path, overwrite=True)`
385
+ - `load(path, strict=True)`
386
+ - `init_and_load(path, strict=True)`
387
+
388
+ The decorator can rename all three methods and can rename the instance attribute that stores constructor configuration.
389
+
390
+ ### Checkpoint contents
391
+
392
+ The generated checkpoint payload stores:
393
+
394
+ - `model`: the result of `state_dict()`.
395
+ - `config`: a pickled constructor-configuration payload.
396
+ - `version`: an optional version string.
397
+
398
+ ### Nested module reconstruction
399
+
400
+ Nested module graphs are a first-class use case. If one decorated module is passed as a constructor argument to another decorated module, `save_load` can dehydrate that nested module graph during save and rehydrate that nested module graph during `init_and_load`.
401
+
402
+ ### Version behavior
403
+
404
+ When both the checkpoint version and the current decorator version exist and differ, `load` emits `UserWarning` and still loads the checkpoint state.
405
+
406
+ ## Edge-case conventions
407
+
408
+ These conventions matter for both humans and AI assistants.
409
+
410
+ - `exists` tests only `None`. `0`, `False`, empty strings, empty lists, and empty dictionaries still count as existing values.
411
+ - `maybe(fn)` short-circuits on the first argument only. `maybe(fn)(None, ...)` returns `None` without calling `fn`.
412
+ - `safe`, `safe_cat`, `safe_stack`, `reduce_masks`, `and_masks`, and `or_masks` all treat `None` values as absent values rather than false values.
413
+ - `safe_cat`, `safe_stack`, `reduce_masks`, `and_masks`, `or_masks`, `pad_sequence`, and `pad_sequence_and_cat` can return `None` for empty effective input. Generated code must account for that return path.
414
+ - `pad_left_at_dim_to`, `pad_right_at_dim_to`, `pad_left_ndim_to`, and `pad_right_ndim_to` return the original tensor unchanged when no growth is needed.
415
+ - `shape_with_replace` accepts only non-negative dimension keys. `slice_at_dim`, `slice_left_at_dim`, and `slice_right_at_dim` do accept negative `dim` values.
416
+ - `module_device` returns `None` for stateless modules such as `nn.Identity()`.
417
+ - `move_inputs_to_module_device` becomes a no-op when `module_device(self)` returns `None`.
418
+ - `save_load.load` may warn on version mismatch but still restore model state.
419
+ - `save_load.init_and_load` requires a checkpoint that contains serialized constructor configuration.
420
+
421
+ ## Typing and AI-assistant notes
422
+
423
+ This repository is written to be readable by humans, machine translation systems, search tools, and AI assistants.
424
+
425
+ - The package ships a `py.typed` marker.
426
+ - The repository uses strict type checking in `pyrightconfig.json`.
427
+ - `exists` uses `TypeGuard`, so a type checker can narrow `T | None` to `T` after an `exists(...)` check.
428
+ - `pad_sequence`, `pack_with_inverse`, and `maybe` use overloads so type checkers can preserve useful return information.
429
+ - The documentation keeps identifier names stable. `pad_sequence` always means `pad_sequence`. `safe_cat` always means `safe_cat`. This consistency helps retrieval and generated code.
430
+
431
+ If you are an AI assistant adapting code from `torch-einops-utils`, use these translation rules:
432
+
433
+ - Replace `from torch_einops_utils import ...` with `from torch_einops_kit import ...` for root helpers.
434
+ - Replace upstream `save_load` imports with `from torch_einops_kit.save_load import save_load`.
435
+ - Replace upstream device decorator imports with `from torch_einops_kit.device import ...`.
436
+ - Do not erase `None`-return paths with unconditional casts. Several helpers intentionally return `None` for empty effective input.
437
+ - Do not assume `pad_sequence` always returns a stacked tensor. Read `return_stacked` and `return_lens` first.
438
+
439
+ ## Differences from upstream `torch-einops-utils`
440
+
441
+ This repository is not a repackaged mirror of upstream. This repository makes a different trade-off.
442
+
443
+ - Upstream is intentionally compact.
444
+ - This fork splits the implementation across focused modules such as `_helpers.py`, `_padding.py`, `device.py`, `nn.py`, and `save_load.py` while still re-exporting most tensor helpers from the package root.
445
+ - This fork adds strict typing, a `py.typed` marker, extensive tests, detailed docstrings, some function optimizations, and roughly 1200 additional tests beyond the original 30-test suite.
446
+ - This fork is best treated as a typed, documented branch of the same utility idea rather than a literal import-path-compatible drop-in replacement.
447
+
448
+ ## Repository layout
449
+
450
+ - `src/torch_einops_kit/` — package source.
451
+ - `src/torch_einops_kit/device.py` — device inference and input-routing decorators.
452
+ - `src/torch_einops_kit/nn.py` — lightweight `torch.nn.Module` adapters and a `Sequential` constructor that ignores `None` modules.
453
+ - `src/torch_einops_kit/save_load.py` — checkpoint save / load decorator and nested reconstruction helpers.
454
+ - `src/torch_einops_kit/scaleValues.py` — exclusive and reverse cumulative sums, vector normalization, masked mean, and the `RMSNorm` layer.
455
+ - `tests/` — regression tests and usage examples for helpers, masks, padding, device routing, and checkpoint reconstruction.
456
+
457
+ ## Development
458
+
459
+ Set up the repository:
460
+
461
+ ```bash
462
+ uv sync
463
+ ```
464
+
465
+ Run the test suite:
466
+
467
+ ```bash
468
+ pytest
469
+ ```
470
+
471
+ Run static analysis:
472
+
473
+ ```bash
474
+ ruff check .
475
+ ```
476
+
477
+ ## My recovery
478
+
479
+ [![Static Badge](https://img.shields.io/badge/2011_August-Homeless_since-blue?style=flat)](https://HunterThinks.com/support)
480
+ [![YouTube Channel Subscribers](https://img.shields.io/youtube/channel/subscribers/UC3Gx7kz61009NbhpRtPP7tw)](https://www.youtube.com/@HunterHogan)
481
+
482
+ [![CC-BY-NC-4.0](https://raw.githubusercontent.com/hunterhogan/torch_einops_kit/refs/heads/main/.github/CC-BY-NC-4.0.png)](https://creativecommons.org/licenses/by-nc/4.0/)
@@ -0,0 +1,20 @@
1
+ torch_einops_kit/__init__.py,sha256=lGr3HplyQC0JPsu1FC8cC0k4Faet5ac2aA7Ul4zan00,6984
2
+ torch_einops_kit/_cat_and_stack.py,sha256=QrRbM8HzMwWa21NaIW4_b68bkKLDoOpbYlnnMF2kQbk,6804
3
+ torch_einops_kit/_dimensions.py,sha256=ifvtl4W8ufuOdYprVGTY6_6Wh5b9XxXcj0dF2tP3ORw,18550
4
+ torch_einops_kit/_helpers.py,sha256=CmN-v_LGGEDau1K2fTMxu5kbUmGw3T2sDPn3eJFu6dQ,14459
5
+ torch_einops_kit/_masking.py,sha256=W3Kjg8GO86NnAll3w3Vls7DbLAsSscYtbgBzx5yO_DI,12235
6
+ torch_einops_kit/_padding.py,sha256=Ym_euKkORWSpIivrVunMkmSI5yYNeRe_8u51Qrng31Y,22935
7
+ torch_einops_kit/_slicing.py,sha256=Xo2n1Cew-Vn-LVt5skxZJACAOxpRC3PdFxRQGJEvtK0,9669
8
+ torch_einops_kit/_theTypes.py,sha256=zqjcp_1txgdFwi2UtrWu9wYNzRkfza-IxS-ACdo0rLk,17821
9
+ torch_einops_kit/device.py,sha256=Sj8D5oO2hPhHnUjEHaORkm_nO2uXJ3tONk4Il_0trzQ,13417
10
+ torch_einops_kit/einops.py,sha256=bJmsZVIPkVcXFJwMZCuFcclaaudUURxzoMcYYN6jzZ4,7910
11
+ torch_einops_kit/nn.py,sha256=NluQadWTQIEYbRTGxSvniK8936sufFuijbiqCpTO1ZQ,6526
12
+ torch_einops_kit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ torch_einops_kit/save_load.py,sha256=1Anem267vBDUtxmqXt5osAG7o0UIYoA-W4BC-sQhprM,20682
14
+ torch_einops_kit/scaleValues.py,sha256=vijKTcDrLMfqGxoh2uxDAI6ZEVt8IAy-fmUjuobhe84,14611
15
+ torch_einops_kit/utils.py,sha256=oL4qMC0wojY8VqLXWjc3eDYmQxQ67wqruPMGLfiI5vs,5776
16
+ torch_einops_kit-0.1.8.dist-info/licenses/LICENSE,sha256=NxH5Y8BdC-gNU-WSMwim3uMbID2iNDXJz7fHtuTdXhk,19346
17
+ torch_einops_kit-0.1.8.dist-info/licenses/LICENSE-WANG,sha256=odg9S5AChe-7cC-aGPHGVZCfFSduYbzqQOl5uaq-Kew,1136
18
+ torch_einops_kit-0.1.8.dist-info/WHEEL,sha256=8ZlpUMJ7mlDirmlHRhDirEx_nPnARrwDjeE92mlk68E,81
19
+ torch_einops_kit-0.1.8.dist-info/METADATA,sha256=Ft00bWmSXUqz2bkkTRohBvCKj0vZndXz8u4tncm8CbA,39406
20
+ torch_einops_kit-0.1.8.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.11.21
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any