PoPE-pytorch 0.0.1__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,21 @@
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: Set up Python 3.10
12
+ uses: actions/setup-python@v5
13
+ with:
14
+ python-version: "3.10"
15
+ - name: Install dependencies
16
+ run: |
17
+ python -m pip install --upgrade pip
18
+ python -m pip install -e .[test]
19
+ - name: Test with pytest
20
+ run: |
21
+ python -m 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,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: PoPE-pytorch
3
+ Version: 0.0.1
4
+ Summary: PoPE
5
+ Project-URL: Homepage, https://pypi.org/project/PoPE-pytorch/
6
+ Project-URL: Repository, https://github.com/lucidrains/PoPE-pytorch
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: artificial intelligence,deep learning,positional embedding
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Programming Language :: Python :: 3.10
35
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
36
+ Requires-Python: >=3.10
37
+ Requires-Dist: einops>=0.8.1
38
+ Requires-Dist: torch-einops-utils>=0.0.14
39
+ Requires-Dist: torch>=2.5
40
+ Provides-Extra: examples
41
+ Provides-Extra: test
42
+ Requires-Dist: pytest; extra == 'test'
43
+ Description-Content-Type: text/markdown
44
+
45
+ <img src="./pope.png" width="400px"></img>
46
+
47
+ ## PoPE-pytorch
48
+
49
+ Efficient implementation (and explorations) into [polar coordinate positional embedding (PoPE)](https://arxiv.org/abs/2509.10534) - from [Gopalakrishnan](https://agopal42.github.io/) et al. under Schmidhuber
50
+
51
+ ## Install
52
+
53
+ ```shell
54
+ $ pip install PoPE-pytorch
55
+ ```
56
+
57
+ ## Usage
58
+
59
+ ```python
60
+ import torch
61
+ from PoPE_pytorch import PoPE
62
+
63
+ # define pope
64
+
65
+ pope = PoPE(64, heads = 8)
66
+
67
+ # pass in sequence length
68
+
69
+ pos_embed = pope(1024)
70
+
71
+ # queries and keys in attention
72
+
73
+ q = torch.randn(1, 8, 1024, 64)
74
+ k = torch.randn(1, 8, 1024, 64)
75
+
76
+ # training
77
+
78
+ rotated_q, rotated_k = pope.apply_pope_to_qk(pos_embed, q, k)
79
+
80
+ # inference
81
+
82
+ rotated_q, rotated_k = pope.apply_pope_to_qk(pos_embed, q[..., -1:, :], k)
83
+ ```
84
+
85
+ ## Citations
86
+
87
+ ```bibtex
88
+ @misc{gopalakrishnan2025decouplingwhatwherepolar,
89
+ title = {Decoupling the "What" and "Where" With Polar Coordinate Positional Embeddings},
90
+ author = {Anand Gopalakrishnan and Robert Csordás and Jürgen Schmidhuber and Michael C. Mozer},
91
+ year = {2025},
92
+ eprint = {2509.10534},
93
+ archivePrefix = {arXiv},
94
+ primaryClass = {cs.LG},
95
+ url = {https://arxiv.org/abs/2509.10534},
96
+ }
97
+ ```
@@ -0,0 +1,121 @@
1
+ from __future__ import annotations
2
+ from collections import namedtuple
3
+ from math import pi
4
+
5
+ import torch
6
+ from torch import arange, stack, is_tensor, Tensor
7
+ from torch.nn import Module, Parameter
8
+ from torch.amp import autocast
9
+
10
+ import torch.nn.functional as F
11
+
12
+ from einops import einsum, rearrange
13
+
14
+ from torch_einops_utils import slice_right_at_dim
15
+
16
+ # constants
17
+
18
+ PolarEmbedReturn = namedtuple('PolarEmbedReturn', ('freqs', 'bias'))
19
+
20
+ # helper functions
21
+
22
+ def exists(v):
23
+ return v is not None
24
+
25
+ def default(v, d):
26
+ return v if exists(v) else d
27
+
28
+ # applying pope to qk
29
+
30
+ @autocast('cuda', enabled = False)
31
+ def apply_pope_to_qk(
32
+ pope: PolarEmbedReturn,
33
+ q, k,
34
+ to_magnitude = F.softplus
35
+ ):
36
+ q_len, k_len = q.shape[-2], k.shape[-2]
37
+ assert q_len <= k_len
38
+
39
+ freqs, bias = pope
40
+
41
+ if freqs.ndim == 3:
42
+ freqs = rearrange(freqs, 'b n d -> b 1 n d')
43
+
44
+ freq_with_bias = freqs + rearrange(bias, 'h d -> h 1 d')
45
+
46
+ # convert q and k to polar magnitudes with activation
47
+
48
+ q, k = to_magnitude(q), to_magnitude(k)
49
+
50
+ # apply rotations
51
+
52
+ freqs = slice_right_at_dim(freqs, q_len, dim = -2)
53
+
54
+ qcos, qsin = freqs.cos(), freqs.sin()
55
+
56
+ q = rearrange([q * qcos, q * qsin], 'two ... d -> ... (d two)')
57
+
58
+ # handle inference
59
+
60
+ kcos, ksin = freq_with_bias.cos(), freq_with_bias.sin()
61
+
62
+ k = rearrange([k * kcos, k * ksin], 'two ... d -> ... (d two)')
63
+
64
+ return q, k
65
+
66
+ # main class
67
+
68
+ class PoPE(Module):
69
+ def __init__(
70
+ self,
71
+ dim,
72
+ *,
73
+ heads,
74
+ theta = 10000,
75
+ bias_uniform_init = False
76
+ ):
77
+ super().__init__()
78
+
79
+ # freqs
80
+
81
+ inv_freqs = theta ** -(arange(dim).float() / dim)
82
+ self.register_buffer('inv_freqs', inv_freqs)
83
+
84
+ # the learned bias on the keys
85
+
86
+ self.bias = Parameter(torch.zeros(heads, dim))
87
+
88
+ if bias_uniform_init:
89
+ self.bias.uniform_(-2. * pi, 0.)
90
+
91
+ # convenience
92
+
93
+ self.apply_pope_to_qk = staticmethod(apply_pope_to_qk)
94
+
95
+ @property
96
+ def device(self):
97
+ return self.inv_freqs.device
98
+
99
+ @autocast('cuda', enabled = False)
100
+ def forward(
101
+ self,
102
+ pos_or_seq_len: Tensor | int
103
+ ):
104
+
105
+ # get positions depending on input
106
+
107
+ if is_tensor(pos_or_seq_len):
108
+ pos = pos_or_seq_len
109
+ else:
110
+ seq_len = pos_or_seq_len
111
+ pos = arange(seq_len, device = self.device, dtype = self.inv_freqs.dtype)
112
+
113
+ # freqs
114
+
115
+ freqs = einsum(pos, self.inv_freqs, '... i, j -> ... i j')
116
+
117
+ # the bias, with clamping
118
+
119
+ bias = self.bias.clamp(-2. * pi, 0.)
120
+
121
+ return PolarEmbedReturn(freqs, bias)
@@ -0,0 +1 @@
1
+ from PoPE_pytorch.PoPE import PoPE
@@ -0,0 +1,53 @@
1
+ <img src="./pope.png" width="400px"></img>
2
+
3
+ ## PoPE-pytorch
4
+
5
+ Efficient implementation (and explorations) into [polar coordinate positional embedding (PoPE)](https://arxiv.org/abs/2509.10534) - from [Gopalakrishnan](https://agopal42.github.io/) et al. under Schmidhuber
6
+
7
+ ## Install
8
+
9
+ ```shell
10
+ $ pip install PoPE-pytorch
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```python
16
+ import torch
17
+ from PoPE_pytorch import PoPE
18
+
19
+ # define pope
20
+
21
+ pope = PoPE(64, heads = 8)
22
+
23
+ # pass in sequence length
24
+
25
+ pos_embed = pope(1024)
26
+
27
+ # queries and keys in attention
28
+
29
+ q = torch.randn(1, 8, 1024, 64)
30
+ k = torch.randn(1, 8, 1024, 64)
31
+
32
+ # training
33
+
34
+ rotated_q, rotated_k = pope.apply_pope_to_qk(pos_embed, q, k)
35
+
36
+ # inference
37
+
38
+ rotated_q, rotated_k = pope.apply_pope_to_qk(pos_embed, q[..., -1:, :], k)
39
+ ```
40
+
41
+ ## Citations
42
+
43
+ ```bibtex
44
+ @misc{gopalakrishnan2025decouplingwhatwherepolar,
45
+ title = {Decoupling the "What" and "Where" With Polar Coordinate Positional Embeddings},
46
+ author = {Anand Gopalakrishnan and Robert Csordás and Jürgen Schmidhuber and Michael C. Mozer},
47
+ year = {2025},
48
+ eprint = {2509.10534},
49
+ archivePrefix = {arXiv},
50
+ primaryClass = {cs.LG},
51
+ url = {https://arxiv.org/abs/2509.10534},
52
+ }
53
+ ```
Binary file
@@ -0,0 +1,58 @@
1
+ [project]
2
+ name = "PoPE-pytorch"
3
+ version = "0.0.1"
4
+ description = "PoPE"
5
+ authors = [
6
+ { name = "Phil Wang", email = "lucidrains@gmail.com" }
7
+ ]
8
+ readme = "README.md"
9
+ requires-python = ">= 3.10"
10
+ license = { file = "LICENSE" }
11
+ keywords = [
12
+ 'artificial intelligence',
13
+ 'deep learning',
14
+ 'positional embedding',
15
+ ]
16
+
17
+ classifiers=[
18
+ 'Development Status :: 4 - Beta',
19
+ 'Intended Audience :: Developers',
20
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
21
+ 'License :: OSI Approved :: MIT License',
22
+ 'Programming Language :: Python :: 3.10',
23
+ ]
24
+
25
+ dependencies = [
26
+ "einops>=0.8.1",
27
+ "torch>=2.5",
28
+ "torch-einops-utils>=0.0.14"
29
+ ]
30
+
31
+ [project.urls]
32
+ Homepage = "https://pypi.org/project/PoPE-pytorch/"
33
+ Repository = "https://github.com/lucidrains/PoPE-pytorch"
34
+
35
+ [project.optional-dependencies]
36
+ examples = []
37
+ test = [
38
+ "pytest"
39
+ ]
40
+
41
+ [tool.pytest.ini_options]
42
+ pythonpath = [
43
+ "."
44
+ ]
45
+
46
+ [build-system]
47
+ requires = ["hatchling"]
48
+ build-backend = "hatchling.build"
49
+
50
+ [tool.rye]
51
+ managed = true
52
+ dev-dependencies = []
53
+
54
+ [tool.hatch.metadata]
55
+ allow-direct-references = true
56
+
57
+ [tool.hatch.build.targets.wheel]
58
+ packages = ["PoPE_pytorch"]
@@ -0,0 +1,22 @@
1
+ import pytest
2
+ import torch
3
+
4
+ def test_pope():
5
+ from PoPE_pytorch.PoPE import PoPE
6
+
7
+ pope = PoPE(64, heads = 8)
8
+
9
+ pos_embed = pope(1024)
10
+
11
+ q = torch.randn(1, 8, 1024, 64)
12
+ k = torch.randn(1, 8, 1024, 64)
13
+
14
+ rotated_q, rotated_k = pope.apply_pope_to_qk(pos_embed, q, k)
15
+
16
+ assert rotated_q.shape == (1, 8, 1024, 128)
17
+ assert rotated_k.shape == (1, 8, 1024, 128)
18
+
19
+ rotated_q, rotated_k = pope.apply_pope_to_qk(pos_embed, q[..., -1:, :], k)
20
+
21
+ assert rotated_q.shape == (1, 8, 1, 128)
22
+ assert rotated_k.shape == (1, 8, 1024, 128)