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,318 @@
1
+ from __future__ import annotations
2
+
3
+ from einops import rearrange
4
+ from functools import reduce
5
+ from torch import arange, Tensor
6
+ from torch_einops_kit import exists, safe, shift_left, shift_right
7
+ from torch_einops_kit.scaleValues import reverse_cumsum
8
+ from typing import TYPE_CHECKING
9
+ import torch
10
+
11
+ if TYPE_CHECKING:
12
+ from collections.abc import Callable, Sequence
13
+ from torch.types import Number
14
+
15
+ def and_masks(masks: Sequence[Tensor | None]) -> Tensor | None:
16
+ """Reduce a `Sequence` of boolean mask `Tensor` values to a single mask using element-wise logical AND.
17
+
18
+ You can use `and_masks` to combine multiple boolean masks so that the result is `True` only where
19
+ all non-`None` input masks are `True`. `and_masks` calls `reduce_masks` [1] with
20
+ `torch.logical_and` [2]. `None` values in `masks` are filtered out before reduction. If all values
21
+ in `masks` are `None`, `and_masks` returns `None`.
22
+
23
+ Parameters
24
+ ----------
25
+ masks : Sequence[Tensor | None]
26
+ A `Sequence` of boolean `Tensor` or `None` values. `None` values are treated as absent and
27
+ filtered out before reduction. All non-`None` `Tensor` values must have the same shape.
28
+
29
+ Returns
30
+ -------
31
+ mask : Tensor | None
32
+ A boolean `Tensor` that is `True` only at positions where every non-`None` input mask is
33
+ `True`. Returns `None` if `masks` contains no non-`None` values.
34
+
35
+ See Also
36
+ --------
37
+ or_masks : Reduce masks using element-wise logical OR.
38
+ reduce_masks : Reduce masks using a caller-supplied binary operator.
39
+
40
+ Examples
41
+ --------
42
+ From sdft_pytorch [4], intersecting an end-of-sequence mask with an initial-token mask to exclude
43
+ padding and masked prefix positions from the loss calculation:
44
+
45
+ ```python
46
+ mask = and_masks([eos_mask, init_tokens_mask])
47
+ ```
48
+
49
+ References
50
+ ----------
51
+ [1] torch_einops_kit.reduce_masks
52
+
53
+ [2] torch.logical_and - PyTorch documentation
54
+ https://pytorch.org/docs/stable/generated/torch.logical_and.html
55
+ [4] lucidrains/sdft-pytorch
56
+ https://github.com/lucidrains/sdft-pytorch
57
+ """
58
+ return reduce_masks(masks, torch.logical_and)
59
+
60
+ def lens_to_mask(lens: Tensor, max_len: Number | None = None) -> Tensor:
61
+ """Convert a sequence of length values into a boolean mask `Tensor`.
62
+
63
+ You can use `lens_to_mask` to create sequence masks from integer length values. For each scalar in
64
+ `lens`, `lens_to_mask` produces a row of `True` values for positions less than that length value
65
+ and `False` values for all positions equal to or greater than it. The output `Tensor` has one more
66
+ dimension than `lens`, appended at the last axis, with length `max_len`.
67
+
68
+ Parameters
69
+ ----------
70
+ lens : Tensor
71
+ A `Tensor` of non-negative integers representing sequence lengths. `lens` may have any shape;
72
+ the output shape is `(*lens.shape, max_len)`.
73
+ max_len : int | None = None
74
+ The size of the last dimension of the output `Tensor`. If `None`, `max_len` is set to
75
+ `int(lens.amax().item())`.
76
+
77
+ Returns
78
+ -------
79
+ mask : Tensor
80
+ A boolean `Tensor` of shape `(*lens.shape, max_len)`. Position `i` along the last axis is
81
+ `True` if `i < lens[...]` for the corresponding element of `lens`.
82
+
83
+ Examples
84
+ --------
85
+ From dreamer4 [2], masking padded time steps in variable-length rollouts:
86
+
87
+ ```python
88
+ mask_for_gae = lens_to_mask(experience.lens, time)
89
+ ```
90
+
91
+ References
92
+ ----------
93
+ [2] lucidrains/dreamer4
94
+ https://github.com/lucidrains/dreamer4
95
+ """
96
+ device: torch.device = lens.device
97
+
98
+ if not exists(max_len):
99
+ max_len = lens.amax().item()
100
+
101
+ seq: Tensor = arange(max_len, device=device)
102
+ lens = rearrange(lens, '... -> ... 1')
103
+ return seq < lens
104
+
105
+ def mask_after(t: Tensor, value: Tensor | Number, dim: int = -1, *, inclusive: bool = True) -> Tensor:
106
+ """Compute a boolean mask over `t` that stays `True` through the first `value` along `dim`.
107
+
108
+ You can use `mask_after` to keep positions in `t` along `dim` until the first occurrence of
109
+ `value`. `mask_after` returns a boolean `Tensor` with the same shape as `t`. When
110
+ `inclusive=True`, the first matching position remains `True`. When `inclusive=False`, `mask_after`
111
+ sets the first matching position to `False` together with all later positions. `mask_after` uses
112
+ `shift_right` [1] and `Tensor.cumsum` [2] to build the result.
113
+
114
+ Parameters
115
+ ----------
116
+ t : Tensor
117
+ The input `Tensor` to scan for `value`.
118
+ value : Tensor | Number
119
+ The delimiter value to match against `t`. `value` may be a scalar `Number` or a `Tensor`
120
+ broadcastable to `t` for the element-wise comparison.
121
+ dim : int = -1
122
+ The dimension along which `mask_after` scans for the first occurrence of `value`.
123
+ inclusive : bool = True
124
+ When `True`, the first matching position in each slice of `t` remains `True`. When `False`,
125
+ the first matching position becomes `False`.
126
+
127
+ Returns
128
+ -------
129
+ mask : Tensor
130
+ A boolean `Tensor` with the same shape as `t`. For each slice of `t` along `dim`, `mask` is
131
+ `True` before the first occurrence of `value`, and also at the first occurrence when
132
+ `inclusive=True`. If a slice contains no occurrence of `value`, `mask` is `True` for the
133
+ entire slice.
134
+
135
+ See Also
136
+ --------
137
+ mask_before : Compute the complementary mask from the reverse direction.
138
+ lens_to_mask : Convert length values into prefix masks without searching for a delimiter.
139
+
140
+ Examples
141
+ --------
142
+ From `SAC_pytorch.SAC` [3], excluding critic-loss positions after the first terminal step in
143
+ each rollout sequence:
144
+
145
+ ```python
146
+ loss_mask = mask_after(done, True)
147
+ ```
148
+
149
+ From `train_chunked_fql.py` [4], combining the terminal-step mask with `lens_to_mask` [5] so
150
+ the loss excludes both post-terminal positions and padded positions:
151
+
152
+ ```python
153
+ loss_mask = mask_after(terminal, True) & lens_to_mask(n_step_lens, seq_len)
154
+ ```
155
+
156
+ References
157
+ ----------
158
+ [1] torch_einops_kit.shift_right
159
+
160
+ [2] torch.Tensor.cumsum - PyTorch documentation
161
+ https://pytorch.org/docs/stable/generated/torch.Tensor.cumsum.html
162
+ [3] lucidrains/SAC-pytorch `SAC_pytorch/SAC.py`
163
+ https://github.com/lucidrains/SAC-pytorch/blob/main/SAC_pytorch/SAC.py
164
+ [4] lucidrains/rectified-flow-pytorch `train_chunked_fql.py`
165
+ https://github.com/lucidrains/rectified-flow-pytorch/blob/main/train_chunked_fql.py
166
+ [5] torch_einops_kit.lens_to_mask
167
+ """
168
+ mask: Tensor = t == value
169
+ if inclusive:
170
+ mask = shift_right(mask, amount=1, dim=dim, pad_value=False)
171
+ return mask.int().cumsum(dim=dim) == 0
172
+
173
+ def mask_before(t: Tensor, value: Tensor | Number, dim: int = -1, *, inclusive: bool = True) -> Tensor:
174
+ """Compute a boolean mask over `t` that stays `True` from the last `value` onward along `dim`.
175
+
176
+ You can use `mask_before` to keep positions in `t` along `dim` from the last occurrence of `value`
177
+ to the end of each slice. `mask_before` returns a boolean `Tensor` with the same shape as `t`.
178
+ When `inclusive=True`, the last matching position remains `True`. When `inclusive=False`,
179
+ `mask_before` sets the last matching position to `False` and keeps only later positions `True`.
180
+ `mask_before` uses `shift_left` [1] and `reverse_cumsum` [2] to build the result.
181
+
182
+ Parameters
183
+ ----------
184
+ t : Tensor
185
+ The input `Tensor` to scan for `value`.
186
+ value : Tensor | Number
187
+ The delimiter value to match against `t`. `value` may be a scalar `Number` or a `Tensor`
188
+ broadcastable to `t` for the element-wise comparison.
189
+ dim : int = -1
190
+ The dimension along which `mask_before` scans for the last occurrence of `value`.
191
+ inclusive : bool = True
192
+ When `True`, the last matching position in each slice of `t` remains `True`. When `False`, the
193
+ last matching position becomes `False`.
194
+
195
+ Returns
196
+ -------
197
+ mask : Tensor
198
+ A boolean `Tensor` with the same shape as `t`. For each slice of `t` along `dim`, `mask` is
199
+ `True` after the last occurrence of `value`, and also at the last occurrence when
200
+ `inclusive=True`. If a slice contains no occurrence of `value`, `mask` is `True` for the
201
+ entire slice.
202
+
203
+ Delimiter handling
204
+ ------------------
205
+ repeated matches : behavior
206
+ `mask_before` uses `reverse_cumsum` [2], so the final occurrence of `value` along each slice
207
+ of `t` determines where `mask` becomes `True`. Earlier occurrences of `value` do not change
208
+ the final boundary.
209
+
210
+ See Also
211
+ --------
212
+ mask_after : Compute the complementary mask from the forward direction.
213
+ lens_to_mask : Convert length values into prefix masks without searching for a delimiter.
214
+
215
+ References
216
+ ----------
217
+ [1] torch_einops_kit.shift_left
218
+
219
+ [2] torch_einops_kit.reverse_cumsum
220
+ """
221
+ mask: Tensor = t == value
222
+ if inclusive:
223
+ mask = shift_left(mask, amount=1, dim=dim, pad_value=False)
224
+ return reverse_cumsum(mask.int(), dim=dim) == 0
225
+
226
+ def or_masks(masks: Sequence[Tensor | None]) -> Tensor | None:
227
+ """Reduce a sequence of boolean mask `Tensor` values to a single mask using element-wise logical OR.
228
+
229
+ You can use `or_masks` to combine multiple boolean masks so that the result is `True` wherever at
230
+ least one non-`None` input mask is `True`. `or_masks` calls `reduce_masks` [1] with
231
+ `torch.logical_or` [2]. `None` values in `masks` are filtered out before reduction. If all values
232
+ in `masks` are `None`, `or_masks` returns `None`.
233
+
234
+ Parameters
235
+ ----------
236
+ masks : Sequence[Tensor | None]
237
+ A sequence of boolean `Tensor` or `None` values. `None` values are treated as absent and
238
+ filtered out before reduction. All non-`None` `Tensor` values must have the same shape.
239
+
240
+ Returns
241
+ -------
242
+ mask : Tensor | None
243
+ A boolean `Tensor` that is `True` at any position where at least one non-`None` input mask is
244
+ `True`. Returns `None` if `masks` contains no non-`None` values.
245
+
246
+ See Also
247
+ --------
248
+ and_masks : Reduce masks using element-wise logical AND.
249
+ reduce_masks : Reduce masks using a caller-supplied binary operator.
250
+
251
+ References
252
+ ----------
253
+ [1] torch_einops_kit.reduce_masks
254
+
255
+ [2] torch.logical_or - PyTorch documentation
256
+ https://pytorch.org/docs/stable/generated/torch.logical_or.html
257
+ """
258
+ return reduce_masks(masks, torch.logical_or)
259
+
260
+ @safe
261
+ def reduce_masks(masks: Sequence[Tensor], op: Callable[[Tensor, Tensor], Tensor]) -> Tensor | None:
262
+ """Reduce a `Sequence` of `Tensor` values to a single `Tensor` using a binary operator.
263
+
264
+ You can use `reduce_masks` to apply any binary element-wise callable reduction over a sequence of
265
+ `Tensor` values. The `safe` [1] decorator filters out `None` values from `masks` before `op` is
266
+ applied. If `masks` contains no non-`None` values, `reduce_masks` returns `None`. Reduction
267
+ proceeds left-to-right over the elements of `masks`.
268
+
269
+ Parameters
270
+ ----------
271
+ masks : Sequence[Tensor | None]
272
+ A `Sequence` of `Tensor` or `None` values. `None` values are filtered out before `op` is
273
+ applied.
274
+ op : Callable[[Tensor, Tensor], Tensor]
275
+ A binary callable that accepts two `Tensor` arguments and returns a `Tensor`.
276
+
277
+ Returns
278
+ -------
279
+ mask : Tensor | None
280
+ The result of applying `op` cumulatively, left-to-right, over the non-`None` elements of
281
+ `masks`. Returns `None` if no non-`None` values remain after filtering.
282
+
283
+ See Also
284
+ --------
285
+ and_masks : Reduce masks using element-wise logical AND.
286
+ or_masks : Reduce masks using element-wise logical OR.
287
+
288
+ References
289
+ ----------
290
+ [1] torch_einops_kit.safe
291
+ """
292
+ return reduce(op, masks) if masks else None
293
+
294
+ """
295
+ Some of the logic in this module may be protected by the following.
296
+
297
+ MIT License
298
+
299
+ Copyright (c) 2026 Phil Wang
300
+
301
+ Permission is hereby granted, free of charge, to any person obtaining a copy
302
+ of this software and associated documentation files (the "Software"), to deal
303
+ in the Software without restriction, including without limitation the rights
304
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
305
+ copies of the Software, and to permit persons to whom the Software is
306
+ furnished to do so, subject to the following conditions:
307
+
308
+ The above copyright notice and this permission notice shall be included in all
309
+ copies or substantial portions of the Software.
310
+
311
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
312
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
313
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
314
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
315
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
316
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
317
+ SOFTWARE.
318
+ """