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,441 @@
1
+ from __future__ import annotations
2
+
3
+ from functools import wraps
4
+ from typing import Concatenate, overload, TYPE_CHECKING, TypeGuard
5
+
6
+ if TYPE_CHECKING:
7
+ from collections.abc import Callable, Iterable, Sequence
8
+ from torch import Tensor
9
+ from torch_einops_kit import IdentityCallable, PSpec, RVar, SupportsIntIndex, T_co, TVar
10
+
11
+ def compact(arr: Iterable[T_co | None]) -> list[T_co]:
12
+ """Filter `None` values from `arr` and return the remaining elements as a `list`.
13
+
14
+ You can use `compact` to remove all `None` values from an iterable, producing a typed `list` of
15
+ non-`None` elements. `compact` applies `exists` [1] as the predicate for `filter` [2]. The `safe`
16
+ [3] decorator uses `compact` to strip `None` values from a `Sequence` of `Tensor` before passing
17
+ the result to the decorated function.
18
+
19
+ Parameters
20
+ ----------
21
+ arr : Iterable[T_co | None]
22
+ An iterable that may contain a mix of non-`None` values and `None` values to discard.
23
+
24
+ Returns
25
+ -------
26
+ compacted : list[T_co]
27
+ A `list` containing only the non-`None` elements of `arr`, in iteration order.
28
+
29
+ See Also
30
+ --------
31
+ exists : Test whether a value is not `None`.
32
+ safe : Decorator that applies `compact` to filter `None` values before calling the wrapped function.
33
+
34
+ References
35
+ ----------
36
+ [1] torch_einops_kit.exists
37
+
38
+ [2] filter - Python documentation
39
+ https://docs.python.org/3/library/functions.html#filter
40
+ [3] torch_einops_kit.safe
41
+ """
42
+ return [*filter(exists, arr)]
43
+
44
+ def default(v: TVar | None, d: TVar) -> TVar:
45
+ """Return `v` when `v` is not `None`, or `d` when `v` is `None`.
46
+
47
+ You can use `default` to supply a fallback value for optional parameters and accumulators.
48
+ `default` calls `exists` [1] to test `v`. When `exists(v)` is `True`, `default` returns `v`
49
+ unchanged. When `v` is `None`, `default` returns `d`. Two overloads ensure the return type
50
+ narrows correctly under static analysis.
51
+
52
+ Parameters
53
+ ----------
54
+ v : TVar | None
55
+ The primary value to test.
56
+ d : TVar
57
+ The fallback value returned when `v` is `None`.
58
+
59
+ Returns
60
+ -------
61
+ result : TVar
62
+ `v` when `v` is not `None`, otherwise `d`.
63
+
64
+ See Also
65
+ --------
66
+ exists : Test whether a value is not `None`.
67
+
68
+ References
69
+ ----------
70
+ [1] torch_einops_kit.exists
71
+ """
72
+ return v if exists(v) else d
73
+
74
+ def divisible_by(num: float, den: float) -> bool:
75
+ """Test whether `num` is evenly divisible by `den`.
76
+
77
+ You can use `divisible_by` to check divisibility without raising a `ZeroDivisionError` when `den`
78
+ is zero. `divisible_by` returns `False` whenever `den` is zero, and otherwise returns `True` when
79
+ `num % den == 0`.
80
+
81
+ Parameters
82
+ ----------
83
+ num : float
84
+ The numerator to test.
85
+ den : float
86
+ The denominator.
87
+
88
+ Returns
89
+ -------
90
+ is_divisible : bool
91
+ `True` when `den != 0` and `num % den == 0`, otherwise `False`.
92
+ """
93
+ return (den != 0) and ((num % den) == 0)
94
+
95
+ def exists(v: TVar | None) -> TypeGuard[TVar]:
96
+ """Test whether `v` is not `None`.
97
+
98
+ You can use `exists` as a `None`-guard throughout this package. `exists` returns `True` for any
99
+ value that is not `None`, including falsy values such as `0`, `False`, and empty collections. The
100
+ return type is annotated as `TypeGuard[TVar]` [1] so that static analyzers narrow the type of `v`
101
+ to `TVar` in branches guarded by `exists`.
102
+
103
+ Parameters
104
+ ----------
105
+ v : TVar | None
106
+ The value to test.
107
+
108
+ Returns
109
+ -------
110
+ result : bool
111
+ `True` when `v is not None`, otherwise `False`.
112
+
113
+ See Also
114
+ --------
115
+ default : Return a fallback value when `v` is `None`.
116
+ compact : Filter `None` values from an iterable.
117
+
118
+ Examples
119
+ --------
120
+ From `torch_einops_kit.lens_to_mask` [2], guarding optional parameter `max_len` before use:
121
+
122
+ ```python
123
+ if not exists(max_len):
124
+ max_len = lens.amax().item()
125
+ ```
126
+
127
+ References
128
+ ----------
129
+ [1] TypeGuard - Python typing documentation
130
+ https://docs.python.org/3/library/typing.html#typing.TypeGuard
131
+ [2] torch_einops_kit.lens_to_mask
132
+ """
133
+ return v is not None
134
+
135
+ def first(arr: SupportsIntIndex[TVar]) -> TVar:
136
+ """Return the element at index `0` of `arr`.
137
+
138
+ You can use `first` to retrieve the first element of any sequence that supports integer indexing
139
+ via `SupportsIntIndex` [1]. `first` delegates to `arr[0]`.
140
+
141
+ Parameters
142
+ ----------
143
+ arr : SupportsIntIndex[TVar]
144
+ A sequence that supports integer indexing. Access with index `0` must be valid.
145
+
146
+ Returns
147
+ -------
148
+ element : TVar
149
+ The element at position `0` in `arr`.
150
+
151
+ References
152
+ ----------
153
+ [1] torch_einops_kit.SupportsIntIndex
154
+ """
155
+ return arr[0]
156
+
157
+ def identity(t: TVar, *_args: object, **_kwargs: object) -> TVar:
158
+ """Return `t` unchanged, ignoring all other arguments.
159
+
160
+ You can use `identity` as a no-op callable in contexts that require a function but no
161
+ transformation. `identity` accepts and discards any additional positional or keyword arguments,
162
+ making `identity` a drop-in substitute for any unary or multi-argument callable.
163
+ `torch_einops_kit.maybe` [1] returns `identity` when its `fn` argument is `None`.
164
+
165
+ Parameters
166
+ ----------
167
+ t : TVar
168
+ The value to return unchanged.
169
+ *args : Any
170
+ Additional positional arguments. Accepted and discarded.
171
+ **kwargs : Any
172
+ Additional keyword arguments. Accepted and discarded.
173
+
174
+ Returns
175
+ -------
176
+ result : TVar
177
+ `t`, the same object that was passed as the first argument.
178
+
179
+ See Also
180
+ --------
181
+ maybe : Return `identity` when `fn` is `None`, otherwise wrap `fn` to skip `None` inputs.
182
+
183
+ References
184
+ ----------
185
+ [1] torch_einops_kit.identity
186
+ """
187
+ return t
188
+
189
+ def map_values(fn: Callable[[TVar], TVar], v: TVar) -> TVar:
190
+ """Apply `fn` to every leaf value in a nested `list`, `tuple`, or `dict` structure.
191
+
192
+ You can use `map_values` to transform the leaf values of an arbitrarily nested container without
193
+ changing its shape. `map_values` recurses into `list` and `tuple` elements and into `dict`
194
+ values, reassembling each container using its original type. Any value that is not a `list`,
195
+ `tuple`, or `dict` is treated as a leaf and passed directly to `fn`. `dehydrate_config` [1] and
196
+ `rehydrate_config` [2] both use `map_values` to traverse nested checkpoint configuration
197
+ structures.
198
+
199
+ Parameters
200
+ ----------
201
+ fn : Callable[[TVar], TVar]
202
+ The function to apply to each leaf value. `fn` receives each non-container value and must
203
+ return a value of the same type.
204
+ v : TVar
205
+ The value to transform. May be a `list`, `tuple`, `dict`, or any leaf value.
206
+
207
+ Returns
208
+ -------
209
+ transformed : TVar
210
+ The input structure with all leaf values replaced by the results of `fn`.
211
+
212
+ See Also
213
+ --------
214
+ dehydrate_config : Serialize nested `Module` instances using `map_values`.
215
+ rehydrate_config : Reconstruct nested `Module` instances using `map_values`.
216
+
217
+ References
218
+ ----------
219
+ [1] torch_einops_kit.save_load.dehydrate_config
220
+
221
+ [2] torch_einops_kit.save_load.rehydrate_config
222
+
223
+ [3] tests.test_helpers.test_map_values_transforms_structure
224
+ """
225
+ if isinstance(v, (list, tuple)):
226
+ return type(v)(map_values(fn, el) for el in v) # pyright: ignore[reportUnknownVariableType, reportUnknownArgumentType]
227
+
228
+ if isinstance(v, dict):
229
+ v = {key: map_values(fn, val) for key, val in v.items()} # pyright: ignore[reportAssignmentType, reportUnknownArgumentType, reportUnknownVariableType] # ty:ignore[invalid-assignment]
230
+
231
+ return fn(v)
232
+
233
+ @overload
234
+ def maybe(fn: Callable[Concatenate[TVar, PSpec], RVar]) -> Callable[Concatenate[TVar | None, PSpec], RVar | None]: ...
235
+ @overload
236
+ def maybe(fn: None) -> IdentityCallable: ...
237
+ def maybe(fn: Callable[Concatenate[TVar, PSpec], RVar] | None) -> Callable[Concatenate[TVar | None, PSpec], RVar | None] | IdentityCallable:
238
+ """Wrap `fn` so that the wrapped function returns `None` when the first argument is `None`.
239
+
240
+ You can use this function to conditionally apply `fn` without adding an explicit `if`/`else`
241
+ guard at every call site. The returned callable passes all positional and keyword arguments to
242
+ `fn` unchanged when the first argument is not `None`, and returns `None` immediately when the
243
+ first argument is `None`. When `fn` is `None`, the function returns `identity` [1], which passes
244
+ its first argument through without modification.
245
+
246
+ Parameters
247
+ ----------
248
+ fn : Callable[Concatenate[TVar, PSpec], RVar] | None
249
+ The callable to wrap, or `None`. The first positional parameter of `fn` is the value that may
250
+ be `None`. Pass `None` to receive an identity function.
251
+
252
+ Returns
253
+ -------
254
+ wrapped : Callable[Concatenate[TVar | None, PSpec], RVar | None] | Callable[..., TVar]
255
+ A wrapped version of `fn` that short-circuits to `None` when the first argument is `None`, or
256
+ `identity` when `fn` is `None`.
257
+
258
+ See Also
259
+ --------
260
+ identity : Return the first argument unchanged.
261
+
262
+ Examples
263
+ --------
264
+ Skip the function when the first argument is `None` [2]:
265
+
266
+ ```python
267
+ from torch_einops_kit import maybe
268
+
269
+ result = maybe(lambda t: t + 1)(None)
270
+ # result is None
271
+ ```
272
+
273
+ Pass `None` as `fn` to receive an identity function [2]:
274
+
275
+ ```python
276
+ result = maybe(None)(1)
277
+ # result == 1
278
+ ```
279
+
280
+ Conditionally convert episode lengths to a mask [3]:
281
+
282
+ ```python
283
+ from torch_einops_kit import maybe, lens_to_mask
284
+
285
+ mask = maybe(lens_to_mask)(episode_lens, seq_len)
286
+ # mask is None when episode_lens is None,
287
+ # otherwise mask == lens_to_mask(episode_lens, seq_len)
288
+ ```
289
+
290
+ References
291
+ ----------
292
+ [1] torch_einops_kit.identity
293
+
294
+ [2] tests.test_utils.test_maybe
295
+
296
+ [3] metacontroller.metacontroller.ratio_loss
297
+ https://context7.com/lucidrains/metacontroller
298
+ """
299
+ if not exists(fn):
300
+ return identity
301
+
302
+ @wraps(fn)
303
+ def workhorse(t: TVar | None, *args: PSpec.args, **kwargs: PSpec.kwargs) -> RVar | None:
304
+ if not exists(t):
305
+ return None
306
+
307
+ return fn(t, *args, **kwargs)
308
+
309
+ return workhorse
310
+
311
+ def once(fn: Callable[PSpec, RVar]) -> Callable[PSpec, RVar | None]:
312
+ """Wrap a callable so the callable executes at most once.
313
+
314
+ You can use this function to restrict `fn` (***f***u***n***ction) to a single execution. On all
315
+ subsequent calls, `fn` returns `None`.
316
+
317
+ Parameters
318
+ ----------
319
+ fn : Callable[PSpec, RVar]
320
+ (***f***u***n***ction) The `Callable` to wrap.
321
+
322
+ Returns
323
+ -------
324
+ single_use_fn : Callable[PSpec, RVar | None]
325
+ A wrapper that invokes fn on the first call and returns None on all subsequent
326
+ calls. The wrapper accepts the same arguments as fn.
327
+
328
+ Examples
329
+ --------
330
+ This example creates a variant of the built-in `print` that emits output only once:
331
+
332
+ ```python
333
+ print_once = once(print)
334
+
335
+ if device_properties.major == 8 and device_properties.minor == 0:
336
+ print_once('A100 GPU detected, using flash attention if input tensor is on cuda')
337
+ ```
338
+
339
+ References
340
+ ----------
341
+ [1] functools.wraps - Python standard library
342
+ https://docs.python.org/3/library/functools.html#functools.wraps
343
+ [2] torch_einops_kit (PSpec, RVar)
344
+ """
345
+ called: bool = False
346
+
347
+ @wraps(fn)
348
+ def workhorse(*args: PSpec.args, **kwargs: PSpec.kwargs) -> RVar | None:
349
+ nonlocal called
350
+
351
+ if called:
352
+ return None
353
+
354
+ called = True
355
+ return fn(*args, **kwargs)
356
+
357
+ return workhorse
358
+
359
+ @overload
360
+ def safe(fn: Callable[Concatenate[Sequence[Tensor], PSpec], RVar]) -> Callable[Concatenate[Sequence[Tensor | None], PSpec], RVar]: ...
361
+ @overload
362
+ def safe(fn: Callable[Concatenate[tuple[Tensor, ...] | list[Tensor], PSpec], RVar]) -> Callable[Concatenate[tuple[Tensor | None, ...] | list[Tensor | None], PSpec], RVar]: ...
363
+ def safe(
364
+ fn: Callable[Concatenate[Sequence[Tensor], PSpec], RVar] | Callable[Concatenate[tuple[Tensor, ...] | list[Tensor], PSpec], RVar],
365
+ ) -> (
366
+ Callable[Concatenate[Sequence[Tensor | None], PSpec], RVar]
367
+ | Callable[Concatenate[tuple[Tensor | None, ...] | list[Tensor | None], PSpec], RVar]
368
+ ):
369
+ """Wrap `fn` so that `None` values are filtered from the first argument before the call.
370
+
371
+ You can use `safe` as a decorator to make a function that accepts a `Sequence[Tensor]` tolerate
372
+ `None` values in the sequence. The decorated function accepts a `Sequence[Tensor | None]`. Before
373
+ calling `fn`, `safe` applies `compact` [1] to the first argument to remove all `None` values, then
374
+ passes the compacted `list[Tensor]` to `fn`. `safe` always calls `fn`; the behavior when the
375
+ compacted sequence is empty is determined by `fn` itself.
376
+
377
+ `safe` is applied as a decorator to `safe_stack` [2] and `safe_cat` [3] to produce null-safe
378
+ stacking and concatenation. `safe` is also applied to `reduce_masks` [4] to produce null-safe mask
379
+ reduction.
380
+
381
+ Parameters
382
+ ----------
383
+ fn : Callable[Concatenate[Sequence[Tensor], PSpec], RVar]
384
+ A callable whose first argument is a `Sequence[Tensor]`. `fn` receives a compacted
385
+ `list[Tensor]` with all `None` values removed. `fn` must handle an empty list if the input may
386
+ contain only `None` values.
387
+
388
+ Returns
389
+ -------
390
+ wrapped : Callable[Concatenate[Sequence[Tensor | None], PSpec], RVar]
391
+ A wrapped version of `fn` that accepts `None` values in the first argument, filtering them out
392
+ before forwarding to `fn`.
393
+
394
+ See Also
395
+ --------
396
+ compact : Filter `None` values from an iterable.
397
+ safe_cat : Concatenate tensors along an existing dimension, skipping `None` values.
398
+ safe_stack : Stack tensors along a new dimension, skipping `None` values.
399
+
400
+ References
401
+ ----------
402
+ [1] torch_einops_kit.compact
403
+
404
+ [2] torch_einops_kit.safe_stack
405
+
406
+ [3] torch_einops_kit.safe_cat
407
+
408
+ [4] torch_einops_kit.reduce_masks
409
+ """
410
+
411
+ @wraps(fn)
412
+ def workhorse(tensors: Sequence[Tensor | None], *args: PSpec.args, **kwargs: PSpec.kwargs) -> RVar:
413
+ return fn(compact(tensors), *args, **kwargs)
414
+
415
+ return workhorse
416
+
417
+ """
418
+ Some of the logic in this module may be protected by the following.
419
+
420
+ MIT License
421
+
422
+ Copyright (c) 2026 Phil Wang
423
+
424
+ Permission is hereby granted, free of charge, to any person obtaining a copy
425
+ of this software and associated documentation files (the "Software"), to deal
426
+ in the Software without restriction, including without limitation the rights
427
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
428
+ copies of the Software, and to permit persons to whom the Software is
429
+ furnished to do so, subject to the following conditions:
430
+
431
+ The above copyright notice and this permission notice shall be included in all
432
+ copies or substantial portions of the Software.
433
+
434
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
435
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
436
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
437
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
438
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
439
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
440
+ SOFTWARE.
441
+ """