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,326 @@
|
|
|
1
|
+
"""Determine the compute device of a `torch.nn.Module` instance and route `Tensor` arguments to that device or an explicit target `Device`.
|
|
2
|
+
|
|
3
|
+
You can use this Python module to determine the compute device on which a `torch.nn.Module` instance
|
|
4
|
+
resides and to decorate callables so that `Tensor` arguments are automatically moved to the
|
|
5
|
+
appropriate compute device before each call. These utilities remove explicit `.to(device)` calls from
|
|
6
|
+
each call site and centralize device routing in a single Python decorator.
|
|
7
|
+
|
|
8
|
+
Contents
|
|
9
|
+
--------
|
|
10
|
+
Functions
|
|
11
|
+
module_device
|
|
12
|
+
Infer the `torch.device` of a `torch.nn.Module` instance from its first `torch.nn.Parameter`
|
|
13
|
+
or registered `torch.Tensor` buffer.
|
|
14
|
+
move_inputs_to_device
|
|
15
|
+
Create a Python decorator that moves all `Tensor` arguments to a fixed target compute device.
|
|
16
|
+
move_inputs_to_module_device
|
|
17
|
+
Wrap a callable so that all `Tensor` arguments are moved to the `torch.device` of the first
|
|
18
|
+
`torch.nn.Module` argument before each call.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from functools import wraps
|
|
24
|
+
from itertools import chain
|
|
25
|
+
from torch_einops_kit import exists, PSpec, TorchNNModule, tree_map_tensor, TVar
|
|
26
|
+
from typing import Concatenate, TYPE_CHECKING
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from collections.abc import Callable
|
|
30
|
+
from torch import device, Tensor
|
|
31
|
+
from torch.nn import Module
|
|
32
|
+
from torch.types import Device
|
|
33
|
+
|
|
34
|
+
def module_device(m: Module) -> device | None:
|
|
35
|
+
"""Infer the `torch.device` of a `torch.nn.Module` instance from its first `torch.nn.Parameter` or registered `torch.Tensor` buffer.
|
|
36
|
+
|
|
37
|
+
You can use `module_device` to determine the compute device of a `torch.nn.Module` instance
|
|
38
|
+
without reading the instance's internals directly. `module_device` checks the learnable
|
|
39
|
+
`torch.nn.Parameter` values of `m` before checking the registered `torch.Tensor` buffer values of
|
|
40
|
+
`m`, and returns the `torch.device` of the first tensor found. If `m` has no learnable
|
|
41
|
+
`torch.nn.Parameter` values and no registered `torch.Tensor` buffer values, `module_device`
|
|
42
|
+
returns `None`.
|
|
43
|
+
|
|
44
|
+
PyTorch Details
|
|
45
|
+
---------------
|
|
46
|
+
A `torch.nn.Module` instance tracks two kinds of tensors that reside on a specific compute
|
|
47
|
+
device: learnable `torch.nn.Parameter` values, returned by `Module.parameters` [2], and
|
|
48
|
+
registered `torch.Tensor` buffer values, returned by `Module.buffers` [3]. A registered
|
|
49
|
+
`torch.Tensor` buffer is a named tensor registered via `Module.register_buffer` [4] that
|
|
50
|
+
participates in device movement through `.to()` and `.cuda()` but is not updated by
|
|
51
|
+
gradient-based optimizers. `module_device` passes the return of `Module.parameters` and the
|
|
52
|
+
return of `Module.buffers` to `itertools.chain` [5], takes the first element, and returns that
|
|
53
|
+
tensor's `.device` attribute.
|
|
54
|
+
|
|
55
|
+
Parameters
|
|
56
|
+
----------
|
|
57
|
+
m : Module
|
|
58
|
+
The `torch.nn.Module` instance whose compute device is to be inferred.
|
|
59
|
+
|
|
60
|
+
Returns
|
|
61
|
+
-------
|
|
62
|
+
inferredDevice : torch.device | None
|
|
63
|
+
The `torch.device` of the first `torch.nn.Parameter` or registered `torch.Tensor` buffer in
|
|
64
|
+
`m`, or `None` if `m` has no `torch.nn.Parameter` values and no registered `torch.Tensor`
|
|
65
|
+
buffer values.
|
|
66
|
+
|
|
67
|
+
See Also
|
|
68
|
+
--------
|
|
69
|
+
move_inputs_to_module_device : Wrap a callable so that all `Tensor` arguments are moved to the
|
|
70
|
+
`torch.device` of the first `torch.nn.Module` argument before each call.
|
|
71
|
+
|
|
72
|
+
Examples
|
|
73
|
+
--------
|
|
74
|
+
Retrieve the `torch.device` of a `torch.nn.Module` instance with `torch.nn.Parameter` values [6]:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
import torch
|
|
78
|
+
from torch import nn
|
|
79
|
+
from torch_einops_kit.device import module_device
|
|
80
|
+
|
|
81
|
+
linear = nn.Linear(3, 5)
|
|
82
|
+
inferredDevice = module_device(linear)
|
|
83
|
+
# inferredDevice == torch.device('cpu')
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Returns `None` for a `torch.nn.Module` instance that has no `torch.nn.Parameter` values and no
|
|
87
|
+
registered `torch.Tensor` buffer values:
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
empty = nn.Identity()
|
|
91
|
+
inferredDevice = module_device(empty)
|
|
92
|
+
# inferredDevice is None
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
References
|
|
96
|
+
----------
|
|
97
|
+
[1] torch.nn.Module - PyTorch documentation
|
|
98
|
+
https://pytorch.org/docs/stable/generated/torch.nn.Module.html
|
|
99
|
+
[2] torch.nn.Module.parameters - PyTorch documentation
|
|
100
|
+
https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.parameters
|
|
101
|
+
[3] torch.nn.Module.buffers - PyTorch documentation
|
|
102
|
+
https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.buffers
|
|
103
|
+
[4] torch.nn.Module.register_buffer - PyTorch documentation
|
|
104
|
+
https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_buffer
|
|
105
|
+
[5] itertools.chain - Python documentation
|
|
106
|
+
https://docs.python.org/3/library/itertools.html#itertools.chain
|
|
107
|
+
[6] tests.test_device_part2.test_module_device_returns_expected_device
|
|
108
|
+
|
|
109
|
+
"""
|
|
110
|
+
first_param_or_buffer: Tensor | None = next(chain(m.parameters(), m.buffers()), None)
|
|
111
|
+
|
|
112
|
+
if not exists(first_param_or_buffer):
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
return first_param_or_buffer.device
|
|
116
|
+
|
|
117
|
+
def move_inputs_to_device(device: Device) -> Callable[[Callable[PSpec, TVar]], Callable[PSpec, TVar]]:
|
|
118
|
+
"""Create a Python decorator that moves all `Tensor` arguments to a target compute device before each call.
|
|
119
|
+
|
|
120
|
+
You can use `move_inputs_to_device` to wrap a callable so that every `Tensor` in its positional
|
|
121
|
+
and keyword arguments is moved to the compute device identified by `device` before the wrapped
|
|
122
|
+
callable is called. Non-`Tensor` arguments pass through without modification.
|
|
123
|
+
`move_inputs_to_device` uses `tree_map_tensor` [2] to recurse into containers such as `tuple` and
|
|
124
|
+
`dict`, so `Tensor` values nested inside those containers are moved as well.
|
|
125
|
+
|
|
126
|
+
PyTorch Details
|
|
127
|
+
---------------
|
|
128
|
+
The `device` argument accepts any `Device` value [3], including a `str` such as `"cpu"` or
|
|
129
|
+
`"cuda"`, an `int` CUDA device index, a `torch.device` instance, or `None`. `tree_map_tensor`
|
|
130
|
+
applies `Tensor.to(device)` [4] to every `Tensor` found recursively in `args` and `kwargs`. The
|
|
131
|
+
wrapped callable's signature is preserved by `functools.wraps`.
|
|
132
|
+
|
|
133
|
+
Parameters
|
|
134
|
+
----------
|
|
135
|
+
device : Device
|
|
136
|
+
The target compute device to which all `Tensor` arguments are moved. Accepts any value valid
|
|
137
|
+
for `Tensor.to` [4], such as `"cpu"`, `"cuda"`, an integer CUDA device index, or a
|
|
138
|
+
`torch.device` instance.
|
|
139
|
+
|
|
140
|
+
Returns
|
|
141
|
+
-------
|
|
142
|
+
decorator : Callable[[Callable[PSpec, TVar]], Callable[PSpec, TVar]]
|
|
143
|
+
A Python decorator that wraps the given callable, moving its `Tensor` arguments to the
|
|
144
|
+
compute device identified by `device` before each call while preserving the original
|
|
145
|
+
callable's signature.
|
|
146
|
+
|
|
147
|
+
See Also
|
|
148
|
+
--------
|
|
149
|
+
move_inputs_to_module_device : Infer the target compute device from a `torch.nn.Module` instance
|
|
150
|
+
rather than accepting an explicit `Device` argument.
|
|
151
|
+
|
|
152
|
+
Examples
|
|
153
|
+
--------
|
|
154
|
+
Wrap a callable so all `Tensor` arguments are moved to the `meta` compute device [5]:
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
import torch
|
|
158
|
+
from torch_einops_kit.device import move_inputs_to_device
|
|
159
|
+
|
|
160
|
+
targetDevice = torch.device('meta')
|
|
161
|
+
|
|
162
|
+
@move_inputs_to_device(targetDevice)
|
|
163
|
+
def collectDeviceTypes(
|
|
164
|
+
positionTensor: torch.Tensor, nestedTuple: tuple[torch.Tensor, str], *, keywordTensor: torch.Tensor
|
|
165
|
+
) -> tuple[torch.device, torch.device, torch.device]:
|
|
166
|
+
return positionTensor.device, nestedTuple[0].device, keywordTensor.device
|
|
167
|
+
|
|
168
|
+
cpuTensor = torch.tensor([1.0, 2.0])
|
|
169
|
+
result = collectDeviceTypes(cpuTensor, (cpuTensor, 'north'), keywordTensor=cpuTensor)
|
|
170
|
+
# result[0] == torch.device("meta")
|
|
171
|
+
# result[1] == torch.device("meta")
|
|
172
|
+
# result[2] == torch.device("meta")
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
References
|
|
176
|
+
----------
|
|
177
|
+
[1] torch.Tensor - PyTorch documentation
|
|
178
|
+
https://pytorch.org/docs/stable/tensors.html
|
|
179
|
+
[2] torch_einops_kit.tree_map_tensor
|
|
180
|
+
|
|
181
|
+
[3] torch.types.Device - PyTorch documentation
|
|
182
|
+
https://pytorch.org/docs/stable/tensor_attributes.html
|
|
183
|
+
[4] torch.Tensor.to - PyTorch documentation
|
|
184
|
+
https://pytorch.org/docs/stable/generated/torch.Tensor.to.html
|
|
185
|
+
[5] tests.test_device_part2.test_move_inputs_to_device_moves_tensor_arguments_in_nested_structures
|
|
186
|
+
|
|
187
|
+
"""
|
|
188
|
+
|
|
189
|
+
def decorator(fn: Callable[PSpec, TVar]) -> Callable[PSpec, TVar]:
|
|
190
|
+
@wraps(fn)
|
|
191
|
+
def workhorse(*args: PSpec.args, **kwargs: PSpec.kwargs) -> TVar:
|
|
192
|
+
args, kwargs = tree_map_tensor(lambda t: t.to(device), (args, kwargs))
|
|
193
|
+
|
|
194
|
+
return fn(*args, **kwargs)
|
|
195
|
+
|
|
196
|
+
return workhorse
|
|
197
|
+
|
|
198
|
+
return decorator
|
|
199
|
+
|
|
200
|
+
def move_inputs_to_module_device(fn: Callable[Concatenate[TorchNNModule, PSpec], TVar]) -> Callable[Concatenate[TorchNNModule, PSpec], TVar]:
|
|
201
|
+
"""Wrap a callable so that all `Tensor` arguments are moved to the `torch.device` of the first `torch.nn.Module` argument before each call.
|
|
202
|
+
|
|
203
|
+
You can use `move_inputs_to_module_device` as a Python decorator on methods of `torch.nn.Module`
|
|
204
|
+
subclasses [1] to automatically move all `Tensor` arguments to the compute device of the
|
|
205
|
+
`torch.nn.Module` instance. `move_inputs_to_module_device` inspects the first argument (`self`)
|
|
206
|
+
using `module_device` [2] to determine the target `torch.device`, then uses `tree_map_tensor` [3]
|
|
207
|
+
to move every `Tensor` found in the remaining positional and keyword arguments. If the
|
|
208
|
+
`torch.nn.Module` instance has no `torch.nn.Parameter` values and no registered `torch.Tensor`
|
|
209
|
+
buffer values, the `Tensor` arguments pass through without modification.
|
|
210
|
+
|
|
211
|
+
The first argument of the decorated callable must be a `torch.nn.Module` instance.
|
|
212
|
+
|
|
213
|
+
PyTorch Details
|
|
214
|
+
---------------
|
|
215
|
+
`typing.Concatenate` [4] expresses the constraint that the first argument of `fn` is a
|
|
216
|
+
`torch.nn.Module` instance while the remaining arguments form `PSpec`. The `TypeVar` `TorchNNModule`
|
|
217
|
+
is bound to `Module`, so the type of the first argument reflects the specific `torch.nn.Module`
|
|
218
|
+
subclass. `tree_map_tensor` applies `Tensor.to(device)` to every `Tensor` found recursively in
|
|
219
|
+
the non-`self` arguments. The wrapped callable's signature is preserved by `functools.wraps`.
|
|
220
|
+
|
|
221
|
+
Parameters
|
|
222
|
+
----------
|
|
223
|
+
fn : Callable[Concatenate[TorchNNModule, PSpec], TVar]
|
|
224
|
+
The callable to wrap. The first positional argument must be a `torch.nn.Module` instance
|
|
225
|
+
whose `torch.device` is used as the routing target.
|
|
226
|
+
|
|
227
|
+
Returns
|
|
228
|
+
-------
|
|
229
|
+
wrappedMethod : Callable[Concatenate[TorchNNModule, PSpec], TVar]
|
|
230
|
+
The wrapped callable with the same signature as `fn`, where all `Tensor` arguments after the
|
|
231
|
+
first `torch.nn.Module` argument are moved to the `torch.device` of that instance before each
|
|
232
|
+
call.
|
|
233
|
+
|
|
234
|
+
See Also
|
|
235
|
+
--------
|
|
236
|
+
module_device : Infer the `torch.device` of a `torch.nn.Module` instance from its first
|
|
237
|
+
`torch.nn.Parameter` or registered `torch.Tensor` buffer.
|
|
238
|
+
move_inputs_to_device : Move `Tensor` arguments to an explicit target compute device rather than
|
|
239
|
+
inferring it from a `torch.nn.Module` instance.
|
|
240
|
+
|
|
241
|
+
Examples
|
|
242
|
+
--------
|
|
243
|
+
Decorate a method so all `Tensor` arguments are moved to the `torch.device` of the
|
|
244
|
+
`torch.nn.Module` instance [5]:
|
|
245
|
+
|
|
246
|
+
```python
|
|
247
|
+
import torch
|
|
248
|
+
from torch import nn, Tensor
|
|
249
|
+
from torch_einops_kit.device import move_inputs_to_module_device
|
|
250
|
+
|
|
251
|
+
class EchoModule(nn.Module):
|
|
252
|
+
def __init__(self) -> None:
|
|
253
|
+
super().__init__()
|
|
254
|
+
self.scale = nn.Parameter(torch.tensor([2.0], device=torch.device('meta')))
|
|
255
|
+
|
|
256
|
+
@move_inputs_to_module_device
|
|
257
|
+
def forward(self, tensorValue: Tensor) -> Tensor:
|
|
258
|
+
return tensorValue
|
|
259
|
+
|
|
260
|
+
module = EchoModule()
|
|
261
|
+
cpuTensor = torch.tensor([1.0, 2.0])
|
|
262
|
+
result = module.forward(cpuTensor)
|
|
263
|
+
# result.device == torch.device("meta")
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
Decorate a standalone callable and attach it to a `torch.nn.Module` subclass as a method [6]:
|
|
267
|
+
|
|
268
|
+
```python
|
|
269
|
+
@move_inputs_to_module_device
|
|
270
|
+
def policy_loss(model, state, old_log_probs, actions, advantages, mask=None): ...
|
|
271
|
+
|
|
272
|
+
MetaController.policy_loss = policy_loss
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
References
|
|
276
|
+
----------
|
|
277
|
+
[1] torch.nn.Module - PyTorch documentation
|
|
278
|
+
https://pytorch.org/docs/stable/generated/torch.nn.Module.html
|
|
279
|
+
[2] torch_einops_kit.device.module_device
|
|
280
|
+
|
|
281
|
+
[3] torch_einops_kit.tree_map_tensor
|
|
282
|
+
|
|
283
|
+
[4] typing.Concatenate - Python documentation
|
|
284
|
+
https://docs.python.org/3/library/typing.html#typing.Concatenate
|
|
285
|
+
[5] tests.test_device_part2._echo_module_with_parameter
|
|
286
|
+
|
|
287
|
+
[6] metacontroller.metacontroller.policy_loss
|
|
288
|
+
https://context7.com/lucidrains/metacontroller
|
|
289
|
+
"""
|
|
290
|
+
|
|
291
|
+
@wraps(fn)
|
|
292
|
+
def workhorse(self: TorchNNModule, *args: PSpec.args, **kwargs: PSpec.kwargs) -> TVar:
|
|
293
|
+
theDevice: device | None = module_device(self)
|
|
294
|
+
|
|
295
|
+
if exists(theDevice):
|
|
296
|
+
args, kwargs = tree_map_tensor(lambda t: t.to(theDevice), (args, kwargs))
|
|
297
|
+
|
|
298
|
+
return fn(self, *args, **kwargs) # ty:ignore[invalid-argument-type]
|
|
299
|
+
|
|
300
|
+
return workhorse
|
|
301
|
+
|
|
302
|
+
"""
|
|
303
|
+
Some of the logic in this module may be protected by the following.
|
|
304
|
+
|
|
305
|
+
MIT License
|
|
306
|
+
|
|
307
|
+
Copyright (c) 2026 Phil Wang
|
|
308
|
+
|
|
309
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
310
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
311
|
+
in the Software without restriction, including without limitation the rights
|
|
312
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
313
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
314
|
+
furnished to do so, subject to the following conditions:
|
|
315
|
+
|
|
316
|
+
The above copyright notice and this permission notice shall be included in all
|
|
317
|
+
copies or substantial portions of the Software.
|
|
318
|
+
|
|
319
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
320
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
321
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
322
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
323
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
324
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
325
|
+
SOFTWARE.
|
|
326
|
+
"""
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Provide `einops` pack, unpack, and paired inverse utilities.
|
|
2
|
+
|
|
3
|
+
You can use this module to pack one or more `torch.Tensor` objects using an `einops` pattern [1]
|
|
4
|
+
and to recover the original shapes through paired inverse functions. `pack_one` and `unpack_one`
|
|
5
|
+
handle the single-tensor case. `pack_with_inverse` handles both the single-tensor and
|
|
6
|
+
list-of-tensors case and is re-exported from the package root [2].
|
|
7
|
+
|
|
8
|
+
Contents
|
|
9
|
+
--------
|
|
10
|
+
Functions
|
|
11
|
+
pack_one
|
|
12
|
+
Pack one `Tensor` and return shape metadata for paired reconstruction.
|
|
13
|
+
pack_with_inverse
|
|
14
|
+
Pack `t` with an einops pattern and return a paired inverse unpacking function.
|
|
15
|
+
unpack_one
|
|
16
|
+
Unpack one `Tensor` using packed-shape metadata produced by `pack_one`.
|
|
17
|
+
|
|
18
|
+
References
|
|
19
|
+
----------
|
|
20
|
+
[1] einops pack/unpack API
|
|
21
|
+
https://einops.rocks/api/pack_unpack/
|
|
22
|
+
[2] torch_einops_kit
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
from einops import pack, unpack
|
|
28
|
+
from torch import is_tensor, Tensor
|
|
29
|
+
from torch_einops_kit import default, first
|
|
30
|
+
from typing import overload, TYPE_CHECKING
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from collections.abc import Sequence
|
|
34
|
+
from torch_einops_kit import InversePackListTensors, InversePackTensor
|
|
35
|
+
|
|
36
|
+
def pack_one(t: Tensor, pattern: str) -> tuple[Tensor, Sequence[tuple[int, ...] | list[int]]]:
|
|
37
|
+
"""Pack one `Tensor` and return shape metadata for paired reconstruction.
|
|
38
|
+
|
|
39
|
+
You can use `pack_one` to wrap a single `Tensor` in the `einops.pack` [1] interface,
|
|
40
|
+
capturing packed-shape metadata needed to restore the original shape with `unpack_one` [2].
|
|
41
|
+
|
|
42
|
+
Parameters
|
|
43
|
+
----------
|
|
44
|
+
t : Tensor
|
|
45
|
+
Input `Tensor` to pack.
|
|
46
|
+
pattern : str
|
|
47
|
+
Einops packing pattern string passed to `einops.pack` [1].
|
|
48
|
+
|
|
49
|
+
Returns
|
|
50
|
+
-------
|
|
51
|
+
packedTensorAndPackedShape : tuple[Tensor, Sequence[tuple[int, ...] | list[int]]]
|
|
52
|
+
Packed `Tensor` output and packed-shape metadata for reconstruction.
|
|
53
|
+
|
|
54
|
+
See Also
|
|
55
|
+
--------
|
|
56
|
+
unpack_one : Reconstruct one `Tensor` using packed-shape metadata from `pack_one`.
|
|
57
|
+
|
|
58
|
+
References
|
|
59
|
+
----------
|
|
60
|
+
[1] einops pack/unpack API
|
|
61
|
+
https://einops.rocks/api/pack_unpack/
|
|
62
|
+
[2] torch_einops_kit.einops.unpack_one
|
|
63
|
+
"""
|
|
64
|
+
return pack([t], pattern)
|
|
65
|
+
|
|
66
|
+
@overload
|
|
67
|
+
def pack_with_inverse(t: Tensor, pattern: str) -> tuple[Tensor, InversePackTensor]: ...
|
|
68
|
+
@overload
|
|
69
|
+
def pack_with_inverse(t: list[Tensor], pattern: str) -> tuple[Tensor, InversePackListTensors]: ...
|
|
70
|
+
def pack_with_inverse(t: Tensor | list[Tensor], pattern: str) -> tuple[Tensor, InversePackTensor] | tuple[Tensor, InversePackListTensors]:
|
|
71
|
+
"""Pack `t` with `pattern` and return a paired inverse unpacking function.
|
|
72
|
+
|
|
73
|
+
You can use this function to merge one `Tensor` or one `list[Tensor]` into one packed `Tensor`
|
|
74
|
+
with `einops.pack` [1] and to carry forward an inverse callable tied to the captured packed-shape
|
|
75
|
+
metadata. The returned `inverse` callable accepts a packed or transformed `Tensor` `out`,
|
|
76
|
+
optionally accepts an override unpacking pattern `inv_pattern`, and reconstructs either one
|
|
77
|
+
`Tensor` or `list[Tensor]` to match the kind of `t`.
|
|
78
|
+
|
|
79
|
+
Parameters
|
|
80
|
+
----------
|
|
81
|
+
t : Tensor | list[Tensor]
|
|
82
|
+
One `Tensor` or one `list[Tensor]` to pack.
|
|
83
|
+
pattern : str
|
|
84
|
+
Einops pack pattern string passed to `einops.pack` [1]. The `*` axis marks the dimensions to
|
|
85
|
+
collect into the packed axis.
|
|
86
|
+
|
|
87
|
+
Returns
|
|
88
|
+
-------
|
|
89
|
+
packed : Tensor
|
|
90
|
+
The packed tensor produced by `einops.pack` [1].
|
|
91
|
+
inverse : InversePackTensor | InversePackListTensors
|
|
92
|
+
Paired inverse callable. When `t` is one `Tensor`, `inverse` has type `InversePackTensor` [2]
|
|
93
|
+
and returns one `Tensor`. When `t` is a `list[Tensor]`, `inverse` has type
|
|
94
|
+
`InversePackListTensors` [3] and returns `list[Tensor]`.
|
|
95
|
+
|
|
96
|
+
Output Kind
|
|
97
|
+
-----------
|
|
98
|
+
tensor input : dispatch
|
|
99
|
+
Passing one `Tensor` returns an `inverse` callable that unwraps the single unpacked result.
|
|
100
|
+
list input : dispatch
|
|
101
|
+
Passing `list[Tensor]` returns an `inverse` callable that preserves the unpacked list
|
|
102
|
+
structure.
|
|
103
|
+
|
|
104
|
+
Unpacking Pattern
|
|
105
|
+
-----------------
|
|
106
|
+
`inv_pattern` override : pattern reuse
|
|
107
|
+
The returned `inverse` reuses `pattern` when `inv_pattern` is `None`. Passing `inv_pattern`
|
|
108
|
+
forwards `inv_pattern` to `einops.unpack` [4] so `inverse` can unpack a derived `Tensor`, as
|
|
109
|
+
long as `inv_pattern` remains compatible with the packed-shape metadata captured during
|
|
110
|
+
packing.
|
|
111
|
+
|
|
112
|
+
See Also
|
|
113
|
+
--------
|
|
114
|
+
pack_one :
|
|
115
|
+
Pack one `Tensor` and return shape metadata for paired reconstruction.
|
|
116
|
+
tree_flatten_with_inverse :
|
|
117
|
+
Flatten a PyTree and return an inverse reconstruction function.
|
|
118
|
+
unpack_one :
|
|
119
|
+
Unpack one `Tensor` using metadata produced by `pack_one`.
|
|
120
|
+
|
|
121
|
+
Examples
|
|
122
|
+
--------
|
|
123
|
+
Pack one tensor and recover the original shape.
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
import torch
|
|
127
|
+
|
|
128
|
+
from torch_einops_kit import pack_with_inverse
|
|
129
|
+
|
|
130
|
+
t = torch.randn(3, 12, 2, 2)
|
|
131
|
+
packed, inverse = pack_with_inverse(t, 'b * d')
|
|
132
|
+
|
|
133
|
+
assert packed.shape == (3, 24, 2)
|
|
134
|
+
|
|
135
|
+
recovered = inverse(packed)
|
|
136
|
+
assert recovered.shape == (3, 12, 2, 2)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
References
|
|
140
|
+
----------
|
|
141
|
+
[1] einops.pack - einops documentation
|
|
142
|
+
https://einops.rocks/api/pack/
|
|
143
|
+
[2] torch_einops_kit.InversePackTensor
|
|
144
|
+
|
|
145
|
+
[3] torch_einops_kit.InversePackListTensors
|
|
146
|
+
|
|
147
|
+
[4] einops pack/unpack API
|
|
148
|
+
https://einops.rocks/api/pack_unpack/
|
|
149
|
+
|
|
150
|
+
"""
|
|
151
|
+
if is_tensor(t):
|
|
152
|
+
is_one = True
|
|
153
|
+
sequenceT: Sequence[Tensor] = [t]
|
|
154
|
+
else:
|
|
155
|
+
is_one = False
|
|
156
|
+
sequenceT = t
|
|
157
|
+
|
|
158
|
+
packed, packed_shape = pack(sequenceT, pattern)
|
|
159
|
+
|
|
160
|
+
def inverse_is_one(out: Tensor, inv_pattern: str | None = None) -> Tensor:
|
|
161
|
+
inv_pattern = default(inv_pattern, pattern)
|
|
162
|
+
unpacked: list[Tensor] = unpack(out, packed_shape, inv_pattern)
|
|
163
|
+
|
|
164
|
+
return first(unpacked)
|
|
165
|
+
|
|
166
|
+
def inverse_is_list(out: Tensor, inv_pattern: str | None = None) -> list[Tensor]:
|
|
167
|
+
inv_pattern = default(inv_pattern, pattern)
|
|
168
|
+
unpacked: list[Tensor] = unpack(out, packed_shape, inv_pattern)
|
|
169
|
+
|
|
170
|
+
return unpacked
|
|
171
|
+
|
|
172
|
+
if is_one:
|
|
173
|
+
return packed, inverse_is_one
|
|
174
|
+
return packed, inverse_is_list
|
|
175
|
+
|
|
176
|
+
def unpack_one(t: Tensor, ps: Sequence[tuple[int, ...] | list[int]], pattern: str) -> Tensor:
|
|
177
|
+
"""Unpack one `Tensor` using packed-shape metadata produced by `pack_one`.
|
|
178
|
+
|
|
179
|
+
You can use `unpack_one` with metadata from a paired `pack_one` [1] call to reconstruct the
|
|
180
|
+
original `Tensor` shape. The function delegates to `einops.unpack` [2] and extracts the single
|
|
181
|
+
unpacked output.
|
|
182
|
+
|
|
183
|
+
Parameters
|
|
184
|
+
----------
|
|
185
|
+
t : Tensor
|
|
186
|
+
Packed `Tensor` produced by `pack_one` [1].
|
|
187
|
+
ps : Sequence[tuple[int, ...] | list[int]]
|
|
188
|
+
Packed-shape metadata returned by `pack_one` [1].
|
|
189
|
+
pattern : str
|
|
190
|
+
Einops unpacking pattern string passed to `einops.unpack` [2].
|
|
191
|
+
|
|
192
|
+
Returns
|
|
193
|
+
-------
|
|
194
|
+
unpackedTensor : Tensor
|
|
195
|
+
Reconstructed `Tensor` matching the original shape before packing.
|
|
196
|
+
|
|
197
|
+
See Also
|
|
198
|
+
--------
|
|
199
|
+
pack_one : Pack one `Tensor` and return shape metadata for paired reconstruction.
|
|
200
|
+
|
|
201
|
+
References
|
|
202
|
+
----------
|
|
203
|
+
[1] torch_einops_kit.einops.pack_one
|
|
204
|
+
|
|
205
|
+
[2] einops pack/unpack API
|
|
206
|
+
https://einops.rocks/api/pack_unpack/
|
|
207
|
+
"""
|
|
208
|
+
return unpack(t, list(ps), pattern)[0]
|
|
209
|
+
|
|
210
|
+
"""
|
|
211
|
+
Some of the logic in this module may be protected by the following.
|
|
212
|
+
|
|
213
|
+
MIT License
|
|
214
|
+
|
|
215
|
+
Copyright (c) 2026 Phil Wang
|
|
216
|
+
|
|
217
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
218
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
219
|
+
in the Software without restriction, including without limitation the rights
|
|
220
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
221
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
222
|
+
furnished to do so, subject to the following conditions:
|
|
223
|
+
|
|
224
|
+
The above copyright notice and this permission notice shall be included in all
|
|
225
|
+
copies or substantial portions of the Software.
|
|
226
|
+
|
|
227
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
228
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
229
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
230
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
231
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
232
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
233
|
+
SOFTWARE.
|
|
234
|
+
"""
|