torch-einops-utils 0.0.9__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.
@@ -0,0 +1,36 @@
1
+ # This workflow will upload a Python Package using Twine when a release is created
2
+ # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries
3
+
4
+ # This workflow uses actions that are not certified by GitHub.
5
+ # They are provided by a third-party and are governed by
6
+ # separate terms of service, privacy policy, and support
7
+ # documentation.
8
+
9
+ name: Upload Python Package
10
+
11
+ on:
12
+ release:
13
+ types: [published]
14
+
15
+ jobs:
16
+ deploy:
17
+
18
+ runs-on: ubuntu-latest
19
+
20
+ steps:
21
+ - uses: actions/checkout@v2
22
+ - name: Set up Python
23
+ uses: actions/setup-python@v2
24
+ with:
25
+ python-version: '3.x'
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m pip install --upgrade pip
29
+ pip install build
30
+ - name: Build package
31
+ run: python -m build
32
+ - name: Publish package
33
+ uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
34
+ with:
35
+ user: __token__
36
+ password: ${{ secrets.PYPI_API_TOKEN }}
@@ -0,0 +1,18 @@
1
+ name: Pytest
2
+ on: [push, pull_request]
3
+
4
+ jobs:
5
+ build:
6
+
7
+ runs-on: ubuntu-latest
8
+
9
+ steps:
10
+ - uses: actions/checkout@v4
11
+ - name: Install uv
12
+ uses: astral-sh/setup-uv@v5
13
+ with:
14
+ enable-cache: true
15
+ python-version: "3.10"
16
+
17
+ - name: Test with pytest
18
+ run: uv run --extra test pytest tests/
@@ -0,0 +1,207 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Phil Wang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.4
2
+ Name: torch-einops-utils
3
+ Version: 0.0.9
4
+ Summary: Personal utility functions
5
+ Project-URL: Homepage, https://pypi.org/project/torch-einops-utils/
6
+ Project-URL: Repository, https://github.com/lucidrains/torch-einops-utils
7
+ Author-email: Phil Wang <lucidrains@gmail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2026 Phil Wang
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ License-File: LICENSE
30
+ Keywords: einops,torch
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Programming Language :: Python :: 3.9
35
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
36
+ Requires-Python: >=3.9
37
+ Requires-Dist: einops>=0.8.1
38
+ Requires-Dist: torch>=2.5
39
+ Provides-Extra: examples
40
+ Provides-Extra: test
41
+ Requires-Dist: pytest; extra == 'test'
42
+ Description-Content-Type: text/markdown
43
+
44
+ ## torch-einops-utils
45
+
46
+ Some utility functions to help myself (and perhaps others) go faster with ML/AI work
@@ -0,0 +1,3 @@
1
+ ## torch-einops-utils
2
+
3
+ Some utility functions to help myself (and perhaps others) go faster with ML/AI work
@@ -0,0 +1,56 @@
1
+ [project]
2
+ name = "torch-einops-utils"
3
+ version = "0.0.9"
4
+ description = "Personal utility functions"
5
+ authors = [
6
+ { name = "Phil Wang", email = "lucidrains@gmail.com" }
7
+ ]
8
+ readme = "README.md"
9
+ requires-python = ">= 3.9"
10
+ license = { file = "LICENSE" }
11
+ keywords = [
12
+ 'torch',
13
+ 'einops'
14
+ ]
15
+
16
+ classifiers=[
17
+ 'Development Status :: 4 - Beta',
18
+ 'Intended Audience :: Developers',
19
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
20
+ 'License :: OSI Approved :: MIT License',
21
+ 'Programming Language :: Python :: 3.9',
22
+ ]
23
+
24
+ dependencies = [
25
+ "torch>=2.5",
26
+ "einops>=0.8.1"
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://pypi.org/project/torch-einops-utils/"
31
+ Repository = "https://github.com/lucidrains/torch-einops-utils"
32
+
33
+ [project.optional-dependencies]
34
+ examples = []
35
+ test = [
36
+ "pytest"
37
+ ]
38
+
39
+ [tool.pytest.ini_options]
40
+ pythonpath = [
41
+ "."
42
+ ]
43
+
44
+ [build-system]
45
+ requires = ["hatchling"]
46
+ build-backend = "hatchling.build"
47
+
48
+ [tool.rye]
49
+ managed = true
50
+ dev-dependencies = []
51
+
52
+ [tool.hatch.metadata]
53
+ allow-direct-references = true
54
+
55
+ [tool.hatch.build.targets.wheel]
56
+ packages = ["torch_einops_utils"]
@@ -0,0 +1,94 @@
1
+ import torch
2
+ from torch import tensor
3
+
4
+ from torch_einops_utils.torch_einops_utils import (
5
+ exists,
6
+ pad_ndim,
7
+ align_dims_left,
8
+ pad_at_dim,
9
+ pad_left_at_dim,
10
+ pad_right_at_dim,
11
+ pad_sequence,
12
+ lens_to_mask,
13
+ and_masks,
14
+ or_masks,
15
+ tree_flatten_with_inverse,
16
+ pack_with_inverse,
17
+ )
18
+
19
+ def test_exist():
20
+ assert not exists(None)
21
+
22
+ def test_pad_ndim():
23
+ t = torch.randn(3)
24
+ t = pad_ndim(t, (1, 2))
25
+ assert t.shape == (1, 3, 1, 1)
26
+
27
+ def test_align_ndim_left():
28
+ t = torch.randn(3)
29
+ u = torch.randn(3, 5, 2)
30
+ v = torch.randn(3, 5)
31
+
32
+ t, u, v = align_dims_left((t, u, v))
33
+ assert t.shape == (3, 1, 1)
34
+ assert u.shape == (3, 5, 2)
35
+ assert v.shape == (3, 5, 1)
36
+
37
+ def test_pad_at_dim():
38
+ t = torch.randn(3, 6, 1)
39
+ padded = pad_at_dim(t, (0, 1), dim = 1)
40
+
41
+ assert padded.shape == (3, 7, 1)
42
+ assert torch.allclose(padded, pad_right_at_dim(t, 1, dim = 1))
43
+ assert not torch.allclose(padded, pad_left_at_dim(t, 1, dim = 1))
44
+
45
+ def test_tree_flatten_with_inverse():
46
+ tree = (1, (2, 3), 4)
47
+ (first, *rest), inverse = tree_flatten_with_inverse(tree)
48
+
49
+ out = inverse((first + 1, *rest))
50
+ assert out == (2, (2, 3), 4)
51
+
52
+ def test_pack_with_inverse():
53
+ t = torch.randn(3, 12, 2, 2)
54
+ t, inverse = pack_with_inverse(t, 'b * d')
55
+
56
+ assert t.shape == (3, 24, 2)
57
+ t = inverse(t)
58
+ assert t.shape == (3, 12, 2, 2)
59
+
60
+ u = torch.randn(3, 4, 2)
61
+ t, inverse = pack_with_inverse([t, u], 'b * d')
62
+ assert t.shape == (3, 28, 2)
63
+
64
+ t = t.sum(dim = -1)
65
+ t, u = inverse(t, 'b *')
66
+ assert t.shape == (3, 12, 2)
67
+ assert u.shape == (3, 4)
68
+
69
+ def test_better_pad_sequence():
70
+
71
+ x = torch.randn(2, 4, 5)
72
+ y = torch.randn(2, 3, 5)
73
+ z = torch.randn(2, 1, 5)
74
+
75
+ packed, lens = pad_sequence([x, y, z], dim = 1, return_lens = True)
76
+ assert packed.shape == (3, 2, 4, 5)
77
+ assert lens.tolist() == [4, 3, 1]
78
+
79
+ mask = lens_to_mask(lens)
80
+ assert torch.allclose(mask.sum(dim = -1), lens)
81
+
82
+ def test_and_masks():
83
+ assert not exists(and_masks([None]))
84
+
85
+ mask1 = tensor([True, True])
86
+ mask2 = tensor([True, False])
87
+ assert (and_masks([mask1, None, mask2]) == tensor([True, False])).all()
88
+
89
+ def test_or_masks():
90
+ assert not exists(or_masks([None]))
91
+
92
+ mask1 = tensor([True, True])
93
+ mask2 = tensor([True, False])
94
+ assert (or_masks([mask1, None, mask2]) == tensor([True, True])).all()
@@ -0,0 +1,26 @@
1
+
2
+ from torch_einops_utils.torch_einops_utils import (
3
+ pad_ndim,
4
+ pad_left_ndim,
5
+ pad_right_ndim,
6
+ align_dims_left,
7
+ )
8
+
9
+ from torch_einops_utils.torch_einops_utils import (
10
+ lens_to_mask
11
+ )
12
+
13
+ from torch_einops_utils.torch_einops_utils import (
14
+ pad_at_dim,
15
+ pad_left_at_dim,
16
+ pad_right_at_dim,
17
+ pad_sequence
18
+ )
19
+
20
+ from torch_einops_utils.torch_einops_utils import (
21
+ tree_flatten_with_inverse
22
+ )
23
+
24
+ from torch_einops_utils.torch_einops_utils import (
25
+ pack_with_inverse
26
+ )
@@ -0,0 +1,162 @@
1
+ from __future__ import annotations
2
+ from typing import Literal
3
+
4
+ import torch
5
+ from torch import tensor, is_tensor, cat, stack, arange
6
+ import torch.nn.functional as F
7
+
8
+ from torch.utils._pytree import tree_flatten, tree_unflatten
9
+
10
+ from einops import rearrange, repeat, reduce, pack, unpack
11
+
12
+ # helper functions
13
+
14
+ def exists(v):
15
+ return v is not None
16
+
17
+ def default(v, d):
18
+ return v if exists(v) else d
19
+
20
+ def first(arr):
21
+ return arr[0]
22
+
23
+ # exported functions
24
+
25
+ # dimensions
26
+
27
+ def pad_ndim(t, ndims: tuple[int, int]):
28
+ shape = t.shape
29
+ left, right = ndims
30
+
31
+ ones = (1,)
32
+ ones_left = ones * left
33
+ ones_right = ones * right
34
+ return t.reshape(*ones_left, *shape, *ones_right)
35
+
36
+ def pad_left_ndim(t, ndims: int):
37
+ return pad_ndim(t, (ndims, 0))
38
+
39
+ def pad_right_ndim(t, ndims: int):
40
+ return pad_ndim(t, (0, ndims))
41
+
42
+ def align_dims_left(
43
+ tensors,
44
+ *,
45
+ ndim = None
46
+ ):
47
+ if not exists(ndim):
48
+ ndim = max([t.ndim for t in tensors])
49
+
50
+ return tuple(pad_right_ndim(t, ndim - t.ndim) for t in tensors)
51
+
52
+ # masking
53
+
54
+ def lens_to_mask(lens, max_len = None):
55
+ device = lens.device
56
+
57
+ if not exists(max_len):
58
+ max_len = lens.amax().item()
59
+
60
+ seq = arange(max_len, device = device)
61
+ lens = rearrange(lens, '... -> ... 1')
62
+ return seq < lens
63
+
64
+ def reduce_masks(masks, op):
65
+ masks = [*filter(exists, masks)]
66
+
67
+ if len(masks) == 0:
68
+ return None
69
+ elif len(masks) == 1:
70
+ return first(masks)
71
+
72
+ mask, *rest_masks = masks
73
+
74
+ for rest_mask in rest_masks:
75
+ mask = op(mask, rest_mask)
76
+
77
+ return mask
78
+
79
+ def and_masks(masks):
80
+ return reduce_masks(masks, torch.logical_and)
81
+
82
+ def or_masks(masks):
83
+ return reduce_masks(masks, torch.logical_or)
84
+
85
+ # padding
86
+
87
+ def pad_at_dim(
88
+ t,
89
+ pad: tuple[int, int],
90
+ *,
91
+ dim = -1,
92
+ value = 0.
93
+ ):
94
+ dims_from_right = (- dim - 1) if dim < 0 else (t.ndim - dim - 1)
95
+ zeros = ((0, 0) * dims_from_right)
96
+ return F.pad(t, (*zeros, *pad), value = value)
97
+
98
+ def pad_left_at_dim(t, pad: int, **kwargs):
99
+ return pad_at_dim(t, (pad, 0), **kwargs)
100
+
101
+ def pad_right_at_dim(t, pad: int, **kwargs):
102
+ return pad_at_dim(t, (0, pad), **kwargs)
103
+
104
+ # better pad sequence
105
+
106
+ def pad_sequence(
107
+ tensors,
108
+ *,
109
+ dim = -1,
110
+ value = 0.,
111
+ left = False,
112
+ dim_stack = 0,
113
+ return_lens = False
114
+ ):
115
+ if len(tensors) == 0:
116
+ return None
117
+
118
+ device = first(tensors).device
119
+
120
+ lens = tensor([t.shape[dim] for t in tensors], device = device)
121
+ max_len = lens.amax().item()
122
+
123
+ pad_fn = pad_left_at_dim if left else pad_right_at_dim
124
+ padded_tensors = [pad_fn(t, max_len - t_len, dim = dim, value = value) for t, t_len in zip(tensors, lens)]
125
+
126
+ stacked = stack(padded_tensors, dim = dim_stack)
127
+
128
+ if not return_lens:
129
+ return stacked
130
+
131
+ return stacked, lens
132
+
133
+ # tree flatten with inverse
134
+
135
+ def tree_flatten_with_inverse(tree):
136
+ flattened, spec = tree_flatten(tree)
137
+
138
+ def inverse(out):
139
+ return tree_unflatten(out, spec)
140
+
141
+ return flattened, inverse
142
+
143
+ # einops pack
144
+
145
+ def pack_with_inverse(t, pattern):
146
+ is_one = is_tensor(t)
147
+
148
+ if is_one:
149
+ t = [t]
150
+
151
+ packed, packed_shape = pack(t, pattern)
152
+
153
+ def inverse(out, inv_pattern = None):
154
+ inv_pattern = default(inv_pattern, pattern)
155
+ out = unpack(out, packed_shape, inv_pattern)
156
+
157
+ if is_one:
158
+ out = first(out)
159
+
160
+ return out
161
+
162
+ return packed, inverse