torch-einops-kit 0.1.6__tar.gz → 0.1.7__tar.gz

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.
Files changed (21) hide show
  1. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/PKG-INFO +2 -1
  2. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/pyproject.toml +5 -10
  3. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/__init__.py +2 -4
  4. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/_dimensions.py +155 -2
  5. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/_helpers.py +1 -2
  6. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/_padding.py +2 -1
  7. torch_einops_kit-0.1.6/src/torch_einops_kit/_semiotics.py +0 -137
  8. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/LICENSE +0 -0
  9. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/LICENSE-WANG +0 -0
  10. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/README.md +0 -0
  11. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/_cat_and_stack.py +0 -0
  12. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/_masking.py +0 -0
  13. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/_slicing.py +0 -0
  14. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/_theTypes.py +0 -0
  15. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/device.py +0 -0
  16. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/einops.py +0 -0
  17. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/nn.py +0 -0
  18. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/py.typed +0 -0
  19. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/save_load.py +0 -0
  20. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/scaleValues.py +0 -0
  21. {torch_einops_kit-0.1.6 → torch_einops_kit-0.1.7}/src/torch_einops_kit/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: torch-einops-kit
3
- Version: 0.1.6
3
+ Version: 0.1.7
4
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
5
  Keywords: artificial intelligence,einops,machine learning,pytorch,torch
6
6
  Author: Hunter Hogan
@@ -21,6 +21,7 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
21
  Classifier: Topic :: Utilities
22
22
  Classifier: Typing :: Typed
23
23
  Requires-Dist: einops>=0.8.2
24
+ Requires-Dist: huntermakespy>=0.7.0
24
25
  Requires-Dist: torch>=2.0.0
25
26
  Requires-Dist: typing-extensions>=4.0.0
26
27
  Maintainer: Hunter Hogan
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "torch-einops-kit"
3
- version = "0.1.6"
3
+ version = "0.1.7"
4
4
  description = "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
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -31,6 +31,7 @@ classifiers = [
31
31
  ]
32
32
  dependencies = [
33
33
  "einops>=0.8.2",
34
+ "huntermakespy>=0.7.0",
34
35
  "torch>=2.0.0",
35
36
  "typing-extensions>=4.0.0",
36
37
  ]
@@ -44,14 +45,8 @@ Issues = "https://github.com/hunterhogan/torch_einops_kit/issues"
44
45
  Repository = "https://github.com/hunterhogan/torch_einops_kit.git"
45
46
 
46
47
  [dependency-groups]
47
- dev = [
48
- "pytest-cov",
49
- ]
50
- testing = [
51
- "more-itertools",
52
- "numpy>=2.0.0",
53
- "pytest",
54
- ]
48
+ dev = ["pytest-cov"]
49
+ testing = ["more-itertools", "numpy>=2.0.0", "pytest"]
55
50
 
56
51
  [build-system]
57
52
  requires = ["uv_build>=0.11.8,<0.12.0"]
@@ -73,4 +68,4 @@ filenameCitationDOTcff = "CITATION.cff"
73
68
  pathFilenameCitationSSOT = "citations/CITATION.cff"
74
69
 
75
70
  [tool.uv]
76
- default-groups = ["testing"]
71
+ default-groups = ["dev", "testing"]
@@ -125,9 +125,6 @@ scaleValues
125
125
  # isort: split
126
126
  from __future__ import annotations
127
127
 
128
- from torch_einops_kit._semiotics import decreasing as decreasing, zeroIndexed as zeroIndexed
129
-
130
- # isort: split
131
128
  from torch_einops_kit._theTypes import (
132
129
  ConfigArgsKwargs as ConfigArgsKwargs, DehydratedCheckpoint as DehydratedCheckpoint, DehydratedTorchNNModule as DehydratedTorchNNModule,
133
130
  DimAndValue as DimAndValue, IdentityCallable as IdentityCallable, InversePackListTensors as InversePackListTensors,
@@ -147,7 +144,8 @@ from torch_einops_kit._slicing import (
147
144
  # isort: split
148
145
  from torch_einops_kit._dimensions import (
149
146
  align_dims_left as align_dims_left, pad_left_ndim as pad_left_ndim, pad_left_ndim_to as pad_left_ndim_to, pad_ndim as pad_ndim,
150
- pad_right_ndim as pad_right_ndim, pad_right_ndim_to as pad_right_ndim_to)
147
+ pad_right_ndim as pad_right_ndim, pad_right_ndim_to as pad_right_ndim_to,
148
+ pad_right_ndim_to_and_expand_as as pad_right_ndim_to_and_expand_as, repeat_interleave_to_match as repeat_interleave_to_match)
151
149
 
152
150
  # isort: split
153
151
  from torch_einops_kit._cat_and_stack import (
@@ -1,6 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
- from torch_einops_kit import exists
3
+ from torch_einops_kit import default, divisible_by, exists
4
4
  from typing import TYPE_CHECKING
5
5
 
6
6
  if TYPE_CHECKING:
@@ -343,8 +343,161 @@ def pad_right_ndim_to(t: Tensor, ndims: int) -> Tensor:
343
343
 
344
344
  return pad_right_ndim(t, ndims - t.ndim)
345
345
 
346
+ def pad_right_ndim_to_and_expand_as(source: Tensor, target: Tensor) -> Tensor:
347
+ """Expand `source` across the trailing axes of `target`.
348
+
349
+ You can use this function to prepare `source` for `torch.Tensor.gather` [1] or other
350
+ rank-sensitive PyTorch operations against `target`. The function pads `source` with trailing
351
+ singleton dimensions until `source` has the same rank as `target`, then expands `source` across
352
+ the trailing shape contributed by `target`. The function returns a view when PyTorch can represent
353
+ the result without copying data.
354
+
355
+ Parameters
356
+ ----------
357
+ source : Tensor
358
+ The tensor to pad and expand.
359
+ target : Tensor
360
+ The reference tensor whose trailing axes determine the expanded shape.
361
+
362
+ Returns
363
+ -------
364
+ expanded : Tensor
365
+ A tensor view with shape `source.shape + target.shape[source.ndim:]` when `target.ndim >
366
+ source.ndim`. When `target.ndim <= source.ndim`, the returned tensor keeps `source.shape`.
367
+
368
+ See Also
369
+ --------
370
+ `pad_right_ndim_to`
371
+ Pad trailing singleton dimensions without expanding values.
372
+ `align_dims_left`
373
+ Align several tensors for broadcasting by padding trailing singleton dimensions.
374
+
375
+ PyTorch
376
+ -------
377
+ expansion : Tensor view
378
+ This function calls `pad_right_ndim_to` [2] and then `torch.Tensor.expand` [3]. The expansion
379
+ repeats metadata rather than materializing copies, so a gather index tensor can be broadcast
380
+ from shape `(b, k)` to `(b, k, d)` before `torch.Tensor.gather` [1].
381
+
382
+ Examples
383
+ --------
384
+ This example simplifies the flattened gather pattern from `rigidformer` [4].
385
+
386
+ ```python
387
+ from torch_einops_kit import pad_right_ndim_to_and_expand_as
388
+
389
+ safe_idx = pad_right_ndim_to_and_expand_as(safe_idx, all_pos) other_pos = all_pos.gather(1,
390
+ safe_idx)
391
+ ```
392
+
393
+ This example mirrors `gather_vectors()` in `worldparticle` [5].
394
+
395
+ ```python
396
+ from torch_einops_kit import pad_right_ndim_to_and_expand_as
397
+
398
+ expanded_indices = pad_right_ndim_to_and_expand_as(indices, src) gathered = src.gather(1,
399
+ expanded_indices)
400
+ ```
401
+
402
+ References
403
+ ----------
404
+ [1] torch.Tensor.gather - PyTorch documentation
405
+ https://pytorch.org/docs/stable/generated/torch.Tensor.gather.html
406
+ [2] `pad_right_ndim_to`
407
+
408
+ [3] torch.Tensor.expand - PyTorch documentation
409
+ https://pytorch.org/docs/stable/generated/torch.Tensor.expand.html
410
+ [4] lucidrains/rigidformer `rigidformer.py`
411
+ https://github.com/lucidrains/rigidformer/blob/main/rigidformer/rigidformer.py
412
+ [5] lucidrains/worldparticle `worldparticle.py`
413
+ https://github.com/lucidrains/worldparticle/blob/main/worldparticle/worldparticle.py
414
+ """
415
+ shape: list[int] = [*source.shape, *target.shape[source.ndim:None]]
416
+ source = pad_right_ndim_to(source, target.ndim)
417
+ return source.expand(shape)
418
+
419
+ def repeat_interleave_to_match(t: Tensor, target: Tensor | int, dim: int = 0, target_dim: int | None = None) -> Tensor:
420
+ """Repeat slices of `t` along `dim` until `t` matches the target length.
421
+
422
+ You can use this function to align the length of `t` along `dim` with an integer target length or
423
+ with the size of `Tensor` `target` along `target_dim`. The function returns `t` unchanged when the
424
+ lengths already match. Otherwise the function repeats each slice of `t` the same number of times
425
+ with `torch.Tensor.repeat_interleave` [1].
426
+
427
+ Parameters
428
+ ----------
429
+ t : Tensor
430
+ The tensor whose size along `dim` will be matched to the resolved target length.
431
+ target : Tensor | int
432
+ Either the target length directly, or a tensor whose size provides the target length.
433
+ dim : int = 0
434
+ The axis of `t` whose length will be repeated.
435
+ target_dim : int | None = None
436
+ The axis of `target` whose length will be used when `target` is a tensor. When `target_dim` is
437
+ `None`, the function uses `dim`.
438
+
439
+ Returns
440
+ -------
441
+ matched : Tensor
442
+ `t` itself when the resolved target length already equals `t.shape[dim]`. Otherwise a tensor
443
+ whose size along `dim` equals the resolved target length.
444
+
445
+ Raises
446
+ ------
447
+ ValueError
448
+ When the resolved target length is not divisible by `t.shape[dim]`.
449
+
450
+ See Also
451
+ --------
452
+ `align_dims_left`
453
+ Align tensor ranks for broadcasting without material repetition.
454
+ `pad_right_ndim_to_and_expand_as`
455
+ Expand a tensor across trailing axes of a reference tensor instead of repeating values along
456
+ one axis.
457
+
458
+ PyTorch
459
+ -------
460
+ repeat factor : int
461
+ This function resolves the target length, computes `repeatFactor = len_target // len_t`, and
462
+ applies `torch.Tensor.repeat_interleave` [1]. When the resolved target length already equals
463
+ `t.shape[dim]`, the function returns the original tensor object instead of allocating a new
464
+ tensor. In `dreamer4` [2], this behavior repeats per-sequence `time_lens` after spatial
465
+ packing so the hierarchical temporal transformer receives one length per packed token stream.
466
+
467
+ Examples
468
+ --------
469
+ This example simplifies the hierarchical temporal length expansion in `dreamer4` [2].
470
+
471
+ ```python
472
+ from torch_einops_kit import repeat_interleave_to_match import torch
473
+
474
+ time_lens = torch.tensor([6, 12]) tokens = torch.randn(4, 32, 512)
475
+
476
+ h_net_lens = repeat_interleave_to_match(time_lens, tokens) assert h_net_lens.tolist() == [6,
477
+ 6, 12, 12]
478
+ ```
479
+
480
+ References
481
+ ----------
482
+ [1] torch.Tensor.repeat_interleave - PyTorch documentation
483
+ https://pytorch.org/docs/stable/generated/torch.Tensor.repeat_interleave.html
484
+ [2] lucidrains/dreamer4 `dreamer4.py`
485
+ https://github.com/lucidrains/dreamer4/blob/main/dreamer4/dreamer4.py
486
+ """
487
+ len_t: int = t.shape[dim]
488
+ len_target: int = target if isinstance(target, int) else target.shape[default(target_dim, dim)]
489
+
490
+ if len_t == len_target:
491
+ return t
492
+
493
+ if not divisible_by(len_target, len_t):
494
+ message: str = f'I received `{len_target = }` and `{len_t = }`, but I need `len_target` to be divisible by `len_t`.'
495
+ raise ValueError(message)
496
+
497
+ return t.repeat_interleave(len_target // len_t, dim=dim)
498
+
346
499
  """
347
- Some or all of the logic in this module may be protected by the following.
500
+ Some of the logic in this module may be protected by the following.
348
501
 
349
502
  MIT License
350
503
 
@@ -83,8 +83,7 @@ def divisible_by(num: float, den: float) -> bool:
83
83
  num : float
84
84
  The numerator to test.
85
85
  den : float
86
- The denominator. When `den` is `0`, `divisible_by` returns `False` without evaluating `num %
87
- den`.
86
+ The denominator.
88
87
 
89
88
  Returns
90
89
  -------
@@ -1,7 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from hunterMakesPy import decreasing, zeroIndexed
3
4
  from torch import cat, stack, Tensor, tensor
4
- from torch_einops_kit import decreasing, DimAndValue, first, zeroIndexed
5
+ from torch_einops_kit import DimAndValue, first
5
6
  from typing import Literal, overload, TYPE_CHECKING
6
7
  from typing_extensions import Unpack
7
8
  import torch
@@ -1,137 +0,0 @@
1
- """Variables to replace numeric literals with semantically meaningful identifiers.
2
-
3
- These are from the semiotics module in `hunterMakesPy`. https://github.com/hunterhogan/hunterMakesPy
4
- """
5
-
6
- from __future__ import annotations
7
-
8
- decreasing: int = -1
9
- """Express descending iteration or a reverse direction.
10
-
11
- The identifier `decreasing` holds the value `-1` and serves as a semantic replacement for
12
- numeric literals in contexts where direction or ordering matters. You can use `decreasing`
13
- as an addend to adjust boundary values, as a multiplicand to reverse sign or direction,
14
- or in both roles simultaneously to express complex transformations.
15
-
16
- You can use `decreasing` wherever `-1` would appear but where the meaning "descending order"
17
- or "reverse direction" is more important than the specific numeric value. Using `decreasing`
18
- makes the code's intent explicit and communicates the semantic purpose to readers who might
19
- not immediately recognize `-1` as a directional indicator.
20
-
21
- Common contexts include: reverse iteration through sequences, computing predecessors or
22
- backward offsets, negating dimensions or indices, and constructing `range` objects that
23
- count downward.
24
-
25
- Examples
26
- --------
27
- You can use `decreasing` as an addend to compute a loop boundary:
28
-
29
- >>> for countDown in range(dimension - 2 + decreasing, decreasing, decreasing):
30
- ... processValue(countDown)
31
-
32
- In this example, `dimension - 2 + decreasing` computes the starting index (equivalent to
33
- `dimension - 3`), the second `decreasing` stops iteration at `-1` (to include `0`), and
34
- the third `decreasing` specifies the step direction (counting down by `1`).
35
-
36
- You can use `decreasing` as a multiplicand to reverse sign:
37
-
38
- >>> negatedOffset = baseOffset * decreasing
39
-
40
- You can use `decreasing` as both multiplicand and addend in a single expression:
41
-
42
- >>> adjustedIndex = dimensionHeadSecond * decreasing + decreasing
43
-
44
- This pattern appears when converting between coordinate systems or computing reverse-indexed
45
- positions with additional boundary adjustments.
46
-
47
- You can use `decreasing` as the step parameter in `range` [1] to iterate backward:
48
-
49
- >>> for leaf in range(leavesTotal + decreasing, 1, decreasing):
50
- ... processLeaf(leaf)
51
-
52
- You can combine `decreasing` with other semantic constants:
53
-
54
- >>> boundaryRange = range(
55
- ... (start + inclusive) * decreasing,
56
- ... (stop + inclusive) * decreasing,
57
- ... decreasing
58
- ... )
59
-
60
- References
61
- ----------
62
- [1] Built-in Functions - `range` (Python documentation)
63
- https://docs.python.org/3/library/functions.html#func-range
64
-
65
- """
66
-
67
- zeroIndexed: int = 1
68
- """Express that the adjustment to a value is due to zero-based indexing.
69
-
70
- The identifier `zeroIndexed` holds the value `1` and serves as a semantic replacement
71
- for the numeric literal `1` when converting between zero-based indexing (Python's default)
72
- and one-based indexing (common in mathematical notation, human-readable numbering, and
73
- many domain-specific conventions). You can use `zeroIndexed` as an addend or subtrahend
74
- to adjust index values, counts, or boundary computations.
75
-
76
- You can use `zeroIndexed` wherever `1` would appear but where the meaning "adjust for
77
- indexing convention" is more important than the specific numeric value. Using `zeroIndexed`
78
- makes the code's intent explicit: the adjustment exists to reconcile indexing systems, not
79
- to perform arbitrary arithmetic.
80
-
81
- The most common usage is `count - zeroIndexed` to convert a one-based count ("there are N
82
- items") to the zero-based index of the last item (`N - 1`). You can also use `+ zeroIndexed`
83
- when converting from zero-based indices back to one-based positions or counts, or when
84
- adjusting formulas that assume one-based indexing.
85
-
86
- Common contexts include: computing final indices from counts, converting between mathematical
87
- notation (often one-based) and Python code (zero-based), accessing the last valid index of
88
- a sequence, and boundary calculations in algorithms that mix indexing conventions.
89
-
90
- Examples
91
- --------
92
- You can use `- zeroIndexed` to convert a count to the last valid zero-based index:
93
-
94
- >>> lastDimensionIndex = dimensionsTotal - zeroIndexed
95
-
96
- If `dimensionsTotal` is `3` (representing three dimensions), then `lastDimensionIndex`
97
- becomes `2`, which correctly identifies the index of the third dimension in a zero-indexed
98
- array `[0, 1, 2]`.
99
-
100
- You can use `- zeroIndexed` when accessing elements by position:
101
-
102
- >>> voodooMath: int = creaseAnteAt二Ante首[
103
- ... largestPossibleLengthOfListOfCreases - zeroIndexed
104
- ... ]
105
-
106
- Here, `largestPossibleLengthOfListOfCreases` represents a count ("how many elements"),
107
- and subtracting `zeroIndexed` produces the index of the last element.
108
-
109
- You can use `- zeroIndexed` in `range` [1] boundary computations:
110
-
111
- >>> listIndicesCreasePostToKeep.extend(
112
- ... range(
113
- ... dimensionsTotal - dimensionHead + 1,
114
- ... dimensionsTotal - zeroIndexed
115
- ... )
116
- ... )
117
-
118
- You can use `- zeroIndexed` in conditional expressions:
119
-
120
- >>> if dimensionsTotal - zeroIndexed - dimensionHead == zerosAtThe首:
121
- ... applySpecialCase()
122
-
123
- You can use `+ zeroIndexed` when the adjustment goes in the opposite direction:
124
-
125
- >>> productsOfDimensionsTruncator: int = (
126
- ... dimensionFrom首 - (dimensionsTotal + zeroIndexed)
127
- ... )
128
-
129
- In this example, `dimensionsTotal + zeroIndexed` adjusts the total count upward before
130
- subtraction, compensating for a formula that expects one-based indexing.
131
-
132
- References
133
- ----------
134
- [1] Built-in Functions - `range` (Python documentation)
135
- https://docs.python.org/3/library/functions.html#func-range
136
-
137
- """