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,391 @@
|
|
|
1
|
+
"""Provide exclusive and reverse cumulative sums, vector normalization, masked mean computation, and learned RMS normalization.
|
|
2
|
+
|
|
3
|
+
You can use this module to compute exclusive prefix sums of tensors, compute reverse cumulative
|
|
4
|
+
sums that accumulate values from the current position to the end of a dimension, normalize
|
|
5
|
+
feature vectors to unit length, compute masked mean reductions over selected tensor positions,
|
|
6
|
+
and apply learned root-mean-square normalization to transformer and neural network feature
|
|
7
|
+
channels.
|
|
8
|
+
|
|
9
|
+
Contents
|
|
10
|
+
--------
|
|
11
|
+
Functions
|
|
12
|
+
exclusive_cumsum
|
|
13
|
+
Compute the exclusive prefix sum of a `Tensor` along a dimension.
|
|
14
|
+
l2norm
|
|
15
|
+
Normalize `Tensor` vectors to unit length along the last dimension.
|
|
16
|
+
masked_mean
|
|
17
|
+
Compute the mean of a tensor over positions selected by a boolean mask.
|
|
18
|
+
reverse_cumsum
|
|
19
|
+
Compute the reverse cumulative sum of a `Tensor` along a dimension.
|
|
20
|
+
|
|
21
|
+
Classes
|
|
22
|
+
RMSNorm
|
|
23
|
+
Normalize feature vectors with root-mean-square scaling and a learned `gamma` parameter.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
from torch import nn, SymInt, Tensor
|
|
29
|
+
from torch.nn import Module
|
|
30
|
+
from torch_einops_kit import exists, pad_right_ndim
|
|
31
|
+
import torch
|
|
32
|
+
import torch.nn.functional as F
|
|
33
|
+
|
|
34
|
+
def exclusive_cumsum(t: Tensor, dim: int = -1) -> Tensor:
|
|
35
|
+
"""Compute the exclusive prefix sum of `Tensor` `t` along its dimension `dim`.
|
|
36
|
+
|
|
37
|
+
You can use `exclusive_cumsum` to produce a shifted cumulative sum where each output position
|
|
38
|
+
accumulates only the elements that strictly precede it along `dim`. The element at index zero is
|
|
39
|
+
always zero. This operation is useful for converting absolute segment lengths into starting
|
|
40
|
+
offsets.
|
|
41
|
+
|
|
42
|
+
Parameters
|
|
43
|
+
----------
|
|
44
|
+
t : Tensor
|
|
45
|
+
Input `Tensor` to reduce.
|
|
46
|
+
dim : int = -1
|
|
47
|
+
Dimension along which to compute the exclusive prefix sum. Negative values index from the last
|
|
48
|
+
axis.
|
|
49
|
+
|
|
50
|
+
Returns
|
|
51
|
+
-------
|
|
52
|
+
exclusivePrefixSum : Tensor
|
|
53
|
+
`Tensor` with the same shape as `t` where `exclusivePrefixSum[..., i, ...]` equals the sum of
|
|
54
|
+
all elements of `t` with index strictly less than `i` along `dim`.
|
|
55
|
+
|
|
56
|
+
Mathematical Basis
|
|
57
|
+
------------------
|
|
58
|
+
Let t = [t₀, t₁, ..., tₙ₋₁] be the elements of `t` along `dim`. The exclusive prefix sum S is
|
|
59
|
+
defined element-wise as:
|
|
60
|
+
|
|
61
|
+
S[i] = Σⱼ₌₀^(i−1) tⱼ, with S[0] = 0.
|
|
62
|
+
|
|
63
|
+
Equivalently, S equals the inclusive cumulative sum minus `t`:
|
|
64
|
+
|
|
65
|
+
S = cumsum(t, dim) − t.
|
|
66
|
+
|
|
67
|
+
References
|
|
68
|
+
----------
|
|
69
|
+
[1] torch.Tensor.cumsum - PyTorch documentation
|
|
70
|
+
https://pytorch.org/docs/stable/generated/torch.Tensor.cumsum.html
|
|
71
|
+
"""
|
|
72
|
+
return t.cumsum(dim=dim) - t
|
|
73
|
+
|
|
74
|
+
def l2norm(t: Tensor) -> Tensor:
|
|
75
|
+
"""Normalize `Tensor` vectors to unit length.
|
|
76
|
+
|
|
77
|
+
You can use `l2norm` to normalize attention query and key vectors before computing similarity
|
|
78
|
+
scores. Normalizing query and key vectors prevents those with large magnitudes from dominating
|
|
79
|
+
similarity scores.
|
|
80
|
+
|
|
81
|
+
Parameters
|
|
82
|
+
----------
|
|
83
|
+
t : Tensor
|
|
84
|
+
Input `Tensor` to normalize.
|
|
85
|
+
|
|
86
|
+
Returns
|
|
87
|
+
-------
|
|
88
|
+
normalizedTensor : Tensor
|
|
89
|
+
`Tensor` with each vector scaled to unit length.
|
|
90
|
+
|
|
91
|
+
torch
|
|
92
|
+
-----
|
|
93
|
+
`l2norm` calls `torch.nn.functional.normalize` [1] with `p=2` and `dim=-1`, which divides each
|
|
94
|
+
vector by its Euclidean length (L2 norm) along the last dimension.
|
|
95
|
+
|
|
96
|
+
Examples
|
|
97
|
+
--------
|
|
98
|
+
Normalize `Tensor` attention query, `q`, and `Tensor` attention key, `k`, before computing
|
|
99
|
+
similarity scores: [2]
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
q, k = map(l2norm, (q, k))
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
References
|
|
106
|
+
----------
|
|
107
|
+
[1] torch.nn.functional.normalize
|
|
108
|
+
https://pytorch.org/docs/stable/generated/torch.nn.functional.normalize.html
|
|
109
|
+
[2] BS-RoFormer.mel_band_roformer.LinearAttention
|
|
110
|
+
https://github.com/lucidrains/BS-RoFormer
|
|
111
|
+
"""
|
|
112
|
+
return F.normalize(t, dim=-1, p=2)
|
|
113
|
+
|
|
114
|
+
def masked_mean(t: Tensor, mask: Tensor | None = None, dim: torch.Size | list[int] | tuple[int, ...] | int | None = None, eps: float = 1e-5
|
|
115
|
+
, *, keepdim: bool = False) -> Tensor:
|
|
116
|
+
"""Compute the mean of `t` over positions selected by `mask`.
|
|
117
|
+
|
|
118
|
+
You can use this function to average only the elements of `t` where `mask` is `True`, ignoring
|
|
119
|
+
masked-out positions. When `mask` is `None`, the function falls back to the standard
|
|
120
|
+
`torch.Tensor.mean` [1]. When `mask` has fewer dimensions than `t`, the function right-pads `mask`
|
|
121
|
+
with singleton dimensions using `pad_right_ndim` [2] before broadcasting. When all positions in
|
|
122
|
+
`mask` are `False` and `dim` is `None`, the function returns zero by summing over the empty
|
|
123
|
+
selection.
|
|
124
|
+
|
|
125
|
+
Parameters
|
|
126
|
+
----------
|
|
127
|
+
t : Tensor
|
|
128
|
+
The input tensor to be averaged.
|
|
129
|
+
mask : Tensor | None = None
|
|
130
|
+
A boolean tensor selecting which positions contribute to the mean. When `mask` has fewer
|
|
131
|
+
dimensions than `t`, singleton dimensions are appended on the right before broadcasting. Pass
|
|
132
|
+
`None` to compute an unmasked mean.
|
|
133
|
+
dim : torch.Size | list[int] | tuple[int, ...] | int | None = None
|
|
134
|
+
The dimension or dimensions along which to compute the mean. Pass `None` to reduce over all
|
|
135
|
+
dimensions.
|
|
136
|
+
eps : float = 1e-5
|
|
137
|
+
A small value added to the denominator to prevent division by zero when computing the masked
|
|
138
|
+
mean along a dimension.
|
|
139
|
+
keepdim : bool = False
|
|
140
|
+
When `True`, the reduced dimension is retained as a size-one dimension in `result`, allowing
|
|
141
|
+
`result` to broadcast against `t`.
|
|
142
|
+
|
|
143
|
+
Returns
|
|
144
|
+
-------
|
|
145
|
+
result : Tensor
|
|
146
|
+
The masked mean of `t`. The shape matches `t` with the reduced dimension removed when `dim` is
|
|
147
|
+
specified, or a scalar tensor when `dim` is `None`.
|
|
148
|
+
|
|
149
|
+
See Also
|
|
150
|
+
--------
|
|
151
|
+
pad_right_ndim : Pad singleton dimensions on the right of a tensor to reach a target number of
|
|
152
|
+
dimensions.
|
|
153
|
+
|
|
154
|
+
Examples
|
|
155
|
+
--------
|
|
156
|
+
Compute the mean of all elements with no mask [3]:
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from torch import tensor from torch_einops_kit import masked_mean
|
|
160
|
+
|
|
161
|
+
t = tensor([1.0, 2.0, 3.0, 4.0]) result = masked_mean(t) # result == tensor(2.5)
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Select only the `True` positions using a boolean mask [3]:
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
mask = tensor([True, False, True, False]) result = masked_mean(t, mask=mask) # result ==
|
|
168
|
+
tensor(2.0)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Average along a specific dimension [3]:
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
t = tensor([[1.0, 2.0], [3.0, 4.0]]) mask = tensor([[True, False], [True, True]]) result =
|
|
175
|
+
masked_mean(t, mask=mask, dim=1) # result == tensor([1.0, 3.5])
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Compute the sequence-level mean of transformer activations with `keepdim=True` to preserve the
|
|
179
|
+
sequence dimension for broadcasting, used in the mean-variance split residual update [4][5]:
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
mean_x = masked_mean(x, mask=mask, dim=-2, keepdim=True) mean_residual = masked_mean(residual,
|
|
183
|
+
mask=mask, dim=-2, keepdim=True) centered_x = x - mean_x
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
References
|
|
187
|
+
----------
|
|
188
|
+
[1] torch.Tensor.mean - PyTorch documentation
|
|
189
|
+
https://pytorch.org/docs/stable/generated/torch.Tensor.mean.html
|
|
190
|
+
[2] torch_einops_kit.pad_right_ndim
|
|
191
|
+
|
|
192
|
+
[3] tests.test_utils.test_masked_mean
|
|
193
|
+
|
|
194
|
+
[4] Lu, P. (2026). Mean Mode Screaming: Mean-Variance Split Residuals for 1000-Layer Diffusion
|
|
195
|
+
Transformers. arXiv:2605.06169. https://arxiv.org/abs/2605.06169
|
|
196
|
+
[5] x_transformers.x_transformers.MVSplitResidualUpdate.forward - lucidrains/x-transformers
|
|
197
|
+
https://github.com/lucidrains/x-transformers
|
|
198
|
+
|
|
199
|
+
"""
|
|
200
|
+
if not exists(mask):
|
|
201
|
+
mask = torch.ones_like(t, dtype=torch.bool)
|
|
202
|
+
|
|
203
|
+
mask = pad_right_ndim(mask, max(0, t.ndim - mask.ndim)).expand_as(t)
|
|
204
|
+
|
|
205
|
+
num: Tensor = (t * mask).sum(dim=dim, keepdim=keepdim)
|
|
206
|
+
den: Tensor = mask.sum(dim=dim, keepdim=keepdim)
|
|
207
|
+
|
|
208
|
+
return num / den.clamp(min=eps)
|
|
209
|
+
|
|
210
|
+
def reverse_cumsum(t: Tensor, dim: int = -1, *, keepdim: bool = True) -> Tensor:
|
|
211
|
+
"""Compute the reverse cumulative sum of input `Tensor` `t` along dimension `dim`.
|
|
212
|
+
|
|
213
|
+
You can use `reverse_cumsum` to accumulate values from the current position to the end of `t`
|
|
214
|
+
along `dim`. `reverse_cumsum` complements `exclusive_cumsum` [1] and is useful when each position
|
|
215
|
+
needs the sum of the value at that position and all later values along `dim`.
|
|
216
|
+
|
|
217
|
+
PyTorch
|
|
218
|
+
-------
|
|
219
|
+
broadcasting of `keepdim` : behavior
|
|
220
|
+
`reverse_cumsum` computes `t.sum(dim=dim, keepdim=keepdim)` [2], subtracts `t.cumsum(dim=dim)`
|
|
221
|
+
[3], and adds `t`. With `keepdim=True`, the total sum keeps the reduced dimension so the total
|
|
222
|
+
sum broadcasts across `t` for any valid `dim`. With `keepdim=False`, the total sum omits the
|
|
223
|
+
reduced dimension and the call succeeds only when PyTorch broadcasting semantics [4] can align
|
|
224
|
+
the reduced result with `t`.
|
|
225
|
+
|
|
226
|
+
Parameters
|
|
227
|
+
----------
|
|
228
|
+
t : Tensor
|
|
229
|
+
Input `Tensor` to reduce.
|
|
230
|
+
dim : int = -1
|
|
231
|
+
Dimension along which to compute the reverse cumulative sum. Negative values index from the
|
|
232
|
+
last axis.
|
|
233
|
+
keepdim : bool = True
|
|
234
|
+
Whether `t.sum(dim=dim, keepdim=keepdim)` keeps the reduced dimension before the total sum is
|
|
235
|
+
broadcast back across `t`.
|
|
236
|
+
|
|
237
|
+
Returns
|
|
238
|
+
-------
|
|
239
|
+
reverseCumulativeSum : Tensor
|
|
240
|
+
`Tensor` where `reverseCumulativeSum[..., i, ...]` equals the sum of all elements of `t` with
|
|
241
|
+
index greater than or equal to `i` along `dim`. When the computation broadcasts successfully,
|
|
242
|
+
`reverseCumulativeSum` has the same shape as `t`.
|
|
243
|
+
|
|
244
|
+
See Also
|
|
245
|
+
--------
|
|
246
|
+
exclusive_cumsum : Compute the exclusive prefix sum of a `Tensor` along a dimension.
|
|
247
|
+
|
|
248
|
+
References
|
|
249
|
+
----------
|
|
250
|
+
[1] torch_einops_kit.exclusive_cumsum
|
|
251
|
+
|
|
252
|
+
[2] torch.Tensor.sum - PyTorch documentation
|
|
253
|
+
https://pytorch.org/docs/stable/generated/torch.Tensor.sum.html
|
|
254
|
+
[3] torch.Tensor.cumsum - PyTorch documentation
|
|
255
|
+
https://pytorch.org/docs/stable/generated/torch.Tensor.cumsum.html
|
|
256
|
+
[4] Broadcasting semantics - PyTorch documentation
|
|
257
|
+
https://pytorch.org/docs/stable/notes/broadcasting.html
|
|
258
|
+
"""
|
|
259
|
+
return t.sum(dim=dim, keepdim=keepdim) - t.cumsum(dim=dim) + t
|
|
260
|
+
|
|
261
|
+
class RMSNorm(Module):
|
|
262
|
+
"""Normalize feature vectors with root-mean-square scaling and a learned rescaling parameter.
|
|
263
|
+
|
|
264
|
+
You can use `RMSNorm` as a pre-normalization layer before attention, feedforward, or linear
|
|
265
|
+
projection sublayers in transformer-style modules. `RMSNorm` normalizes each feature vector along
|
|
266
|
+
the last axis to unit length, scales the result by `√dim` to restore the original magnitude range,
|
|
267
|
+
and then applies the learned per-feature `gamma` parameter.
|
|
268
|
+
|
|
269
|
+
The normalization is mathematically equivalent to dividing each vector by its root mean square
|
|
270
|
+
[1]. This formulation omits the mean-centering step of `torch.nn.LayerNorm` [2], which the
|
|
271
|
+
original paper [1] found to be unnecessary for stable training. The implementation delegates the
|
|
272
|
+
per-vector division to `torch.nn.functional.normalize` [3] and carries the `√dim` factor in a
|
|
273
|
+
stored `scale` attribute.
|
|
274
|
+
|
|
275
|
+
Parameters
|
|
276
|
+
----------
|
|
277
|
+
dim : int | SymInt
|
|
278
|
+
Feature dimension of the last axis normalized by `RMSNorm`.
|
|
279
|
+
|
|
280
|
+
Attributes
|
|
281
|
+
----------
|
|
282
|
+
scale : float
|
|
283
|
+
Fixed multiplier equal to `√dim`. Stored so the value is computed once at construction time
|
|
284
|
+
rather than recomputed on every forward pass.
|
|
285
|
+
gamma : nn.Parameter
|
|
286
|
+
Learned per-feature rescaling weights of shape `(dim,)`. Initialized to ones so `RMSNorm`
|
|
287
|
+
starts as an identity-scale transform.
|
|
288
|
+
|
|
289
|
+
See Also
|
|
290
|
+
--------
|
|
291
|
+
l2norm : Normalize `Tensor` vectors to unit length along the last dimension.
|
|
292
|
+
|
|
293
|
+
Examples
|
|
294
|
+
--------
|
|
295
|
+
Apply `RMSNorm` as a pre-norm before a linear projection, following the lucidrains BS-RoFormer
|
|
296
|
+
pattern [4] [5]:
|
|
297
|
+
|
|
298
|
+
```python
|
|
299
|
+
from torch import nn from torch_einops_kit.scaleValues import RMSNorm
|
|
300
|
+
|
|
301
|
+
dim = 128 pre_norm_proj = nn.Sequential(
|
|
302
|
+
RMSNorm(dim), nn.Linear(dim, dim * 4),
|
|
303
|
+
)
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
Store a `RMSNorm` instance on an `Attention` module and call it in `forward`, following the
|
|
307
|
+
lucidrains BS-RoFormer pattern [4] [5]:
|
|
308
|
+
|
|
309
|
+
```python
|
|
310
|
+
class Attention(nn.Module):
|
|
311
|
+
def __init__(self, dim: int) -> None:
|
|
312
|
+
super().__init__() self.norm = RMSNorm(dim) self.to_qkv = nn.Linear(dim, dim * 3,
|
|
313
|
+
bias=False)
|
|
314
|
+
|
|
315
|
+
def forward(self, x):
|
|
316
|
+
x = self.norm(x) # ... query, key, value projection follows
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
References
|
|
320
|
+
----------
|
|
321
|
+
[1] Zhang, B., and Sennrich, R. (2019).
|
|
322
|
+
Root Mean Square Layer Normalization. NeurIPS 32.
|
|
323
|
+
https://papers.nips.cc/paper_files/paper/2019/hash/1e8a19426224ca89e83cef47f1e7f53b-Abstract.html
|
|
324
|
+
[2] torch.nn.LayerNorm - PyTorch documentation
|
|
325
|
+
https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html
|
|
326
|
+
[3] torch.nn.functional.normalize - PyTorch documentation
|
|
327
|
+
https://pytorch.org/docs/stable/generated/torch.nn.functional.normalize.html
|
|
328
|
+
[4] bs_roformer.bs_roformer - BS-RoFormer source
|
|
329
|
+
https://github.com/lucidrains/BS-RoFormer
|
|
330
|
+
[5] bs_roformer.mel_band_roformer - Mel-Band RoFormer source
|
|
331
|
+
https://github.com/lucidrains/BS-RoFormer
|
|
332
|
+
"""
|
|
333
|
+
|
|
334
|
+
def __init__(self, dim: int | SymInt) -> None:
|
|
335
|
+
super().__init__()
|
|
336
|
+
self.scale: float = float(dim) ** 0.5
|
|
337
|
+
self.gamma: nn.Parameter = nn.Parameter(torch.ones((dim,)))
|
|
338
|
+
|
|
339
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
340
|
+
"""Return feature activations after RMS normalization and learned rescaling.
|
|
341
|
+
|
|
342
|
+
This method normalizes `x` along the last axis to unit length, multiplies the normalized
|
|
343
|
+
result by `self.scale` (`√dim`), and applies the learned per-feature `self.gamma` parameter
|
|
344
|
+
element-wise.
|
|
345
|
+
|
|
346
|
+
Parameters
|
|
347
|
+
----------
|
|
348
|
+
x : Tensor
|
|
349
|
+
Input `Tensor` whose last axis stores feature channels. `x` may have any number of leading
|
|
350
|
+
batch or sequence dimensions.
|
|
351
|
+
|
|
352
|
+
Returns
|
|
353
|
+
-------
|
|
354
|
+
normalizedX : Tensor
|
|
355
|
+
`Tensor` with the same shape as `x` after RMS normalization and learned rescaling.
|
|
356
|
+
|
|
357
|
+
References
|
|
358
|
+
----------
|
|
359
|
+
[1] torch.nn.functional.normalize - PyTorch documentation
|
|
360
|
+
https://pytorch.org/docs/stable/generated/torch.nn.functional.normalize.html
|
|
361
|
+
[2] Zhang, B., and Sennrich, R. (2019).
|
|
362
|
+
Root Mean Square Layer Normalization. NeurIPS 32.
|
|
363
|
+
https://papers.nips.cc/paper_files/paper/2019/hash/1e8a19426224ca89e83cef47f1e7f53b-Abstract.html
|
|
364
|
+
"""
|
|
365
|
+
return F.normalize(x, dim=-1) * self.scale * self.gamma
|
|
366
|
+
|
|
367
|
+
"""
|
|
368
|
+
Some or all of the logic in this module may be protected by the following.
|
|
369
|
+
|
|
370
|
+
MIT License
|
|
371
|
+
|
|
372
|
+
Copyright (c) 2026 Phil Wang
|
|
373
|
+
|
|
374
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
375
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
376
|
+
in the Software without restriction, including without limitation the rights
|
|
377
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
378
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
379
|
+
furnished to do so, subject to the following conditions:
|
|
380
|
+
|
|
381
|
+
The above copyright notice and this permission notice shall be included in all
|
|
382
|
+
copies or substantial portions of the Software.
|
|
383
|
+
|
|
384
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
385
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
386
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
387
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
388
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
389
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
390
|
+
SOFTWARE.
|
|
391
|
+
"""
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Provide PyTree manipulation utilities for PyTorch tensors.
|
|
2
|
+
|
|
3
|
+
You can use this module to apply functions to tensor leaves in PyTree structures and to flatten
|
|
4
|
+
and reconstruct nested data.
|
|
5
|
+
|
|
6
|
+
Contents
|
|
7
|
+
--------
|
|
8
|
+
Functions
|
|
9
|
+
tree_flatten_with_inverse
|
|
10
|
+
Flatten a PyTree into a list of leaves and return a paired inverse function.
|
|
11
|
+
tree_map_tensor
|
|
12
|
+
Apply a function to every tensor leaf in a PyTree, leaving non-tensor leaves unchanged.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from torch import is_tensor, Tensor
|
|
18
|
+
from torch.utils._pytree import PyTree, tree_flatten, tree_map, tree_unflatten # noqa: PLC2701
|
|
19
|
+
from typing import Any, TYPE_CHECKING
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from collections.abc import Callable, Iterable
|
|
23
|
+
from torch_einops_kit import 木
|
|
24
|
+
|
|
25
|
+
def tree_map_tensor(fn: Callable[[Tensor], Tensor], tree: PyTree) -> PyTree:
|
|
26
|
+
"""Apply `fn` to every `torch.Tensor` leaf in `tree`, leaving non-tensor leaves unchanged.
|
|
27
|
+
|
|
28
|
+
You can use this function to transform only the tensor leaves of a PyTree [1] structure without
|
|
29
|
+
disturbing the non-tensor leaves. The function wraps `fn` with an identity pass-through for
|
|
30
|
+
non-tensor values and delegates structural traversal to `torch.utils._pytree.tree_map` [2].
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
fn : Callable[[Tensor], Tensor]
|
|
35
|
+
A function to apply to each `torch.Tensor` leaf in `tree`.
|
|
36
|
+
tree : PyTree
|
|
37
|
+
A nested Python structure such as a tuple, list, or dictionary containing a mix of
|
|
38
|
+
`torch.Tensor` values and other Python objects.
|
|
39
|
+
|
|
40
|
+
Returns
|
|
41
|
+
-------
|
|
42
|
+
mappedTree : PyTree
|
|
43
|
+
A PyTree with the same structure as `tree`, where each `torch.Tensor` leaf has been replaced
|
|
44
|
+
by the result of `fn(leaf)` and all non-tensor leaves are unchanged.
|
|
45
|
+
|
|
46
|
+
See Also
|
|
47
|
+
--------
|
|
48
|
+
tree_flatten_with_inverse : Flatten a PyTree into a list and return an inverse function.
|
|
49
|
+
|
|
50
|
+
Examples
|
|
51
|
+
--------
|
|
52
|
+
Increment only the tensor leaf while preserving non-tensor leaves [3]:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from torch import tensor
|
|
56
|
+
from torch_einops_kit import tree_map_tensor
|
|
57
|
+
|
|
58
|
+
tree = (1, tensor(2), 3)
|
|
59
|
+
result = tree_map_tensor(lambda t: t + 1, tree)
|
|
60
|
+
# result[0] == 1
|
|
61
|
+
# result[1] == tensor(3)
|
|
62
|
+
# result[2] == 3
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Detach all tensors nested inside a state container [4]:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from torch_einops_kit import tree_map_tensor
|
|
69
|
+
|
|
70
|
+
nextMemory = tree_map_tensor(lambda t: t.detach(), nextMemory)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
References
|
|
74
|
+
----------
|
|
75
|
+
[1] PyTree - PyTorch documentation
|
|
76
|
+
https://pytorch.org/docs/stable/pytree.html
|
|
77
|
+
[2] torch.utils._pytree.tree_map - PyTorch documentation
|
|
78
|
+
https://pytorch.org/docs/stable/pytree.html#torch.utils._pytree.tree_map
|
|
79
|
+
[3] tests.test_utils.test_tree_map_tensor
|
|
80
|
+
|
|
81
|
+
[4] fast_weight_attention.chunk_manager.ChunkManager.forward
|
|
82
|
+
https://context7.com/lucidrains/fast-weight-attention
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def func(t: object) -> object:
|
|
86
|
+
if is_tensor(t):
|
|
87
|
+
return fn(t)
|
|
88
|
+
return t
|
|
89
|
+
|
|
90
|
+
return tree_map(func, tree)
|
|
91
|
+
|
|
92
|
+
def tree_flatten_with_inverse(tree: 木) -> tuple[list[Any], Callable[[Iterable[Any]], 木]]:
|
|
93
|
+
"""Flatten `tree` into a list of leaves and return a paired inverse function.
|
|
94
|
+
|
|
95
|
+
You can use this function to decompose a nested PyTree [1] structure into a flat list of leaves
|
|
96
|
+
and to recover the original nested structure from a modified list. The paired inverse function
|
|
97
|
+
calls `torch.utils._pytree.tree_unflatten` [2] with the `TreeSpec` captured at flatten time, so
|
|
98
|
+
the structure can be reconstructed even after the leaves have been modified.
|
|
99
|
+
|
|
100
|
+
Parameters
|
|
101
|
+
----------
|
|
102
|
+
tree : PyTree
|
|
103
|
+
A nested Python structure such as a tuple, list, or dictionary to flatten.
|
|
104
|
+
|
|
105
|
+
Returns
|
|
106
|
+
-------
|
|
107
|
+
flattened : list[Any]
|
|
108
|
+
A flat list of all leaves in `tree` in left-to-right traversal order.
|
|
109
|
+
inverse : Callable[[Iterable[Any]], PyTree]
|
|
110
|
+
A function that accepts an iterable of leaves and reconstructs a PyTree with the same
|
|
111
|
+
structure as the original `tree`.
|
|
112
|
+
|
|
113
|
+
See Also
|
|
114
|
+
--------
|
|
115
|
+
tree_map_tensor : Apply a function to every tensor leaf in a PyTree.
|
|
116
|
+
|
|
117
|
+
Examples
|
|
118
|
+
--------
|
|
119
|
+
Modify a single leaf and reconstruct the original nested structure [3]:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from torch_einops_kit import tree_flatten_with_inverse
|
|
123
|
+
|
|
124
|
+
tree = (1, (2, 3), 4)
|
|
125
|
+
(first, *rest), inverse = tree_flatten_with_inverse(tree)
|
|
126
|
+
result = inverse((first + 1, *rest))
|
|
127
|
+
# result == (2, (2, 3), 4)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
References
|
|
131
|
+
----------
|
|
132
|
+
[1] PyTree - PyTorch documentation
|
|
133
|
+
https://pytorch.org/docs/stable/pytree.html
|
|
134
|
+
[2] torch.utils._pytree.tree_unflatten - PyTorch documentation
|
|
135
|
+
https://pytorch.org/docs/stable/pytree.html#torch.utils._pytree.tree_unflatten
|
|
136
|
+
[3] tests.test_utils.test_tree_flatten_with_inverse
|
|
137
|
+
|
|
138
|
+
"""
|
|
139
|
+
flattened, spec = tree_flatten(tree)
|
|
140
|
+
|
|
141
|
+
def inverse(out: Iterable[Any]) -> PyTree:
|
|
142
|
+
return tree_unflatten(out, spec)
|
|
143
|
+
|
|
144
|
+
return flattened, inverse
|
|
145
|
+
|
|
146
|
+
"""
|
|
147
|
+
Some or all of the logic in this module may be protected by the following.
|
|
148
|
+
|
|
149
|
+
MIT License
|
|
150
|
+
|
|
151
|
+
Copyright (c) 2026 Phil Wang
|
|
152
|
+
|
|
153
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
154
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
155
|
+
in the Software without restriction, including without limitation the rights
|
|
156
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
157
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
158
|
+
furnished to do so, subject to the following conditions:
|
|
159
|
+
|
|
160
|
+
The above copyright notice and this permission notice shall be included in all
|
|
161
|
+
copies or substantial portions of the Software.
|
|
162
|
+
|
|
163
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
164
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
165
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
166
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
167
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
168
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
169
|
+
SOFTWARE.
|
|
170
|
+
"""
|