locoformer 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) 2025 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,66 @@
1
+ Metadata-Version: 2.4
2
+ Name: locoformer
3
+ Version: 0.0.1
4
+ Summary: LocoFormer
5
+ Project-URL: Homepage, https://pypi.org/project/locoformer/
6
+ Project-URL: Repository, https://github.com/lucidrains/locoformer
7
+ Author-email: Phil Wang <lucidrains@gmail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2025 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,attention mechanism,cross-embodiment,deep learning,robotics,transformer
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: assoc-scan
38
+ Requires-Dist: einops>=0.8.0
39
+ Requires-Dist: einx>=0.3.0
40
+ Requires-Dist: rotary-embedding-torch
41
+ Requires-Dist: torch>=2.4
42
+ Provides-Extra: examples
43
+ Requires-Dist: accelerate; extra == 'examples'
44
+ Requires-Dist: tqdm; extra == 'examples'
45
+ Provides-Extra: test
46
+ Requires-Dist: pytest; extra == 'test'
47
+ Description-Content-Type: text/markdown
48
+
49
+ <img src="./fig3.png" width="400px"></img>
50
+
51
+ ## LocoFormer (wip)
52
+
53
+ [LocoFormer - Generalist Locomotion via Long-Context Adaptation](https://generalist-locomotion.github.io/)
54
+
55
+ The gist is they trained a simple Transformer-XL in simulation on robots with many different bodies (cross-embodiment). When transferring to the real-world, they noticed the robot now gains the ability to adapt to insults. The XL memories span across multiple trials, which allowed the robot to learn in-context adaptation.
56
+
57
+ ## Citations
58
+
59
+ ```bibtex
60
+ @article{liu2025locoformer,
61
+ title = {LocoFormer: Generalist Locomotion via Long-Context Adaptation},
62
+ author = {Liu, Min and Pathak, Deepak and Agarwal, Ananye},
63
+ journal = {Conference on Robot Learning ({CoRL})},
64
+ year = {2025}
65
+ }
66
+ ```
@@ -0,0 +1,18 @@
1
+ <img src="./fig3.png" width="400px"></img>
2
+
3
+ ## LocoFormer (wip)
4
+
5
+ [LocoFormer - Generalist Locomotion via Long-Context Adaptation](https://generalist-locomotion.github.io/)
6
+
7
+ The gist is they trained a simple Transformer-XL in simulation on robots with many different bodies (cross-embodiment). When transferring to the real-world, they noticed the robot now gains the ability to adapt to insults. The XL memories span across multiple trials, which allowed the robot to learn in-context adaptation.
8
+
9
+ ## Citations
10
+
11
+ ```bibtex
12
+ @article{liu2025locoformer,
13
+ title = {LocoFormer: Generalist Locomotion via Long-Context Adaptation},
14
+ author = {Liu, Min and Pathak, Deepak and Agarwal, Ananye},
15
+ journal = {Conference on Robot Learning ({CoRL})},
16
+ year = {2025}
17
+ }
18
+ ```
@@ -0,0 +1,3 @@
1
+ # Data source
2
+
3
+ The enwik8 data was downloaded from the Hutter prize page: http://prize.hutter1.net/
Binary file
Binary file
@@ -0,0 +1 @@
1
+ from locoformer.locoformer import Locoformer
@@ -0,0 +1,325 @@
1
+ from __future__ import annotations
2
+ from functools import partial
3
+
4
+ import torch
5
+ from torch import cat, stack, is_tensor
6
+ import torch.nn.functional as F
7
+ from torch.nn import Module, ModuleList, Linear, RMSNorm, Identity
8
+ from torch.utils._pytree import tree_map
9
+
10
+ from einops import einsum
11
+ from einops.layers.torch import Rearrange
12
+
13
+ from rotary_embedding_torch import RotaryEmbedding
14
+
15
+ from assoc_scan import AssocScan
16
+
17
+ LinearNoBias = partial(Linear, bias = False)
18
+
19
+ # helper functions
20
+
21
+ def exists(v):
22
+ return v is not None
23
+
24
+ def default(v, d):
25
+ return v if exists(v) else d
26
+
27
+ def tree_map_tensor(x, fn):
28
+ return tree_map(lambda t: t if not is_tensor(t) else fn(t), x)
29
+
30
+ def detach_all(x):
31
+ return tree_map_tensor(x, lambda t: t.detach())
32
+
33
+ def combine_kv_cache(cache1, cache2):
34
+ combined_cache = []
35
+
36
+ for layer_cache1, layer_cache2 in zip(cache1, cache2):
37
+ next_cache = cat((layer_cache1, layer_cache2), dim = -2)
38
+ combined_cache.append(next_cache)
39
+
40
+ return combined_cache
41
+
42
+ # generalized advantage estimate
43
+
44
+ @torch.no_grad()
45
+ def calc_gae(
46
+ rewards,
47
+ values,
48
+ masks,
49
+ gamma = 0.99,
50
+ lam = 0.95,
51
+ use_accelerated = None
52
+ ):
53
+ assert values.shape[-1] == rewards.shape[-1]
54
+ use_accelerated = default(use_accelerated, rewards.is_cuda)
55
+
56
+ values = F.pad(values, (0, 1), value = 0.)
57
+ values, values_next = values[..., :-1], values[..., 1:]
58
+
59
+ delta = rewards + gamma * values_next * masks - values
60
+ gates = gamma * lam * masks
61
+
62
+ scan = AssocScan(reverse = True, use_accelerated = use_accelerated)
63
+
64
+ gae = scan(gates, delta)
65
+
66
+ returns = gae + values
67
+
68
+ return returns
69
+
70
+ # transformer-xl mask w/ flex attn
71
+
72
+ flex_attention = None
73
+
74
+ try:
75
+ from torch.nn.attention.flex_attention import flex_attention, create_block_mask
76
+ if torch.cuda.is_available():
77
+ flex_attention = torch.compile(flex_attention)
78
+ except ImportError:
79
+ pass
80
+
81
+ def create_xl_mask(
82
+ seq_len,
83
+ kv_seq_len,
84
+ window_size,
85
+ episode_ids = None, # (b n) - in the case that within the same batch there are multiple episodes
86
+ lookback_blocks = 1, # in transformer-xl, lookback is one window size block, but can be multiple for longer context
87
+ device = None
88
+ ):
89
+ assert kv_seq_len >= seq_len
90
+ assert window_size <= seq_len
91
+
92
+ offset = kv_seq_len - seq_len
93
+
94
+ def create_block_mask_fn(b, __, q, k):
95
+ offset_q = q + offset
96
+ block_q = offset_q // window_size
97
+ block_k = k // window_size
98
+
99
+ causal_mask = offset_q >= k
100
+
101
+ # in transformer-xl, the previous segment is fully attended to - may just double the segments and make this sliding for ease of inference logic
102
+
103
+ block_mask = (block_q >= block_k) & (block_q <= (block_k + lookback_blocks))
104
+
105
+ mask = causal_mask & block_mask
106
+
107
+ # handle intra-episodic attention if needed
108
+
109
+ if exists(episode_ids):
110
+ q_episode = episodes[b, q + offset]
111
+ k_episode = episodes[b, k]
112
+
113
+ intra_episode_mask = q_episode == k_episode
114
+ mask = mask & intra_episode_mask
115
+
116
+ return mask
117
+
118
+ create_kwargs = dict(device = device) if exists(device) else dict()
119
+ return create_block_mask(create_block_mask_fn, B = None, H = None, Q_LEN = seq_len, KV_LEN = kv_seq_len, _compile = True, **create_kwargs)
120
+
121
+ def create_sliding_mask(
122
+ seq_len,
123
+ kv_seq_len,
124
+ window_size,
125
+ device = None
126
+ ):
127
+ assert kv_seq_len >= seq_len
128
+ offset = kv_seq_len - seq_len
129
+
130
+ def sliding_mask(_, __, q, k):
131
+ offset_q = q + offset
132
+ distance = offset_q - k
133
+
134
+ backward_sliding_mask = distance <= window_size
135
+ forward_sliding_mask = distance >= 0
136
+
137
+ return backward_sliding_mask & forward_sliding_mask
138
+
139
+ create_kwargs = dict(device = device) if exists(device) else dict()
140
+ return create_block_mask(sliding_mask, B = None, H = None, Q_LEN = seq_len, KV_LEN = kv_seq_len, _compile = True, **create_kwargs)
141
+
142
+ # transformer-xl with ppo
143
+
144
+ class Attention(Module):
145
+ def __init__(
146
+ self,
147
+ dim,
148
+ dim_head = 64,
149
+ heads = 8,
150
+ pre_rmsnorm = True
151
+ ):
152
+ super().__init__()
153
+ self.scale = dim_head ** -0.5
154
+
155
+ self.norm = RMSNorm(dim) if pre_rmsnorm else Identity()
156
+
157
+ self.split_heads = Rearrange('b n (h d) -> b h n d', h = heads)
158
+ self.merge_heads = Rearrange('b h n d -> b n (h d)')
159
+
160
+ self.rotary_embed = RotaryEmbedding(dim_head)
161
+
162
+ dim_inner = dim_head * heads
163
+ self.to_q = LinearNoBias(dim, dim_inner)
164
+ self.to_kv = LinearNoBias(dim, dim_inner * 2)
165
+ self.to_out = LinearNoBias(dim_inner, dim)
166
+
167
+ def forward(
168
+ self,
169
+ tokens,
170
+ kv_cache = None,
171
+ return_kv_cache = False
172
+ ):
173
+ tokens = self.norm(tokens)
174
+
175
+ q, k, v = (self.to_q(tokens), *self.to_kv(tokens).chunk(2, dim = -1))
176
+
177
+ q, k, v = map(self.split_heads, (q, k, v))
178
+
179
+ q = q * self.scale
180
+
181
+ if return_kv_cache:
182
+ next_kv_cache = stack((k, v))
183
+
184
+ if exists(kv_cache):
185
+ ck, cv = kv_cache
186
+ k = cat((ck, k), dim = -2)
187
+ v = cat((cv, v), dim = -2)
188
+
189
+ q, k = self.rotary_embed.rotate_queries_with_cached_keys(q, k)
190
+
191
+ sim = einsum(q, k, 'b h i d, b h j d -> b h i j')
192
+
193
+ i, j = sim.shape[-2:]
194
+
195
+ causal_mask = torch.ones((i, j), dtype = torch.bool, device = sim.device).triu(j - i + 1)
196
+
197
+ sim = sim.masked_fill(causal_mask, -torch.finfo(sim.dtype).max)
198
+
199
+ attn = sim.softmax(dim = -1)
200
+
201
+ out = einsum(attn, v, 'b h i j, b h j d -> b h i d')
202
+
203
+ out = self.merge_heads(out)
204
+
205
+ out = self.to_out(out)
206
+
207
+ if not return_kv_cache:
208
+ return out
209
+
210
+ return out, next_kv_cache
211
+
212
+ class FeedForward(Module):
213
+ def __init__(
214
+ self,
215
+ dim,
216
+ expansion_factor = 4.,
217
+ pre_rmsnorm = True
218
+ ):
219
+ super().__init__()
220
+ self.norm = RMSNorm(dim) if pre_rmsnorm else Identity()
221
+
222
+ dim_inner = int(dim * expansion_factor * 2 / 3)
223
+
224
+ self.proj_in = Linear(dim, dim_inner * 2)
225
+ self.proj_out = Linear(dim_inner, dim)
226
+
227
+ def forward(
228
+ self,
229
+ x
230
+ ):
231
+ x = self.norm(x)
232
+
233
+ x, gates = self.proj_in(x).chunk(2, dim = -1)
234
+
235
+ x = x * F.gelu(gates)
236
+
237
+ return self.proj_out(x)
238
+
239
+ class TransformerXL(Module):
240
+ def __init__(
241
+ self,
242
+ dim,
243
+ depth,
244
+ dim_head = 64,
245
+ heads = 8,
246
+ expansion_factor = 4.,
247
+ final_norm = True
248
+ ):
249
+ super().__init__()
250
+
251
+ layers = ModuleList([])
252
+
253
+ for _ in range(depth):
254
+ attn = Attention(dim = dim, dim_head = dim_head, heads = heads)
255
+
256
+ ff = FeedForward(dim = dim, expansion_factor = expansion_factor)
257
+
258
+ layers.append(ModuleList([
259
+ attn, ff
260
+ ]))
261
+
262
+ self.layers = layers
263
+ self.norm = RMSNorm(dim) if final_norm else Identity()
264
+
265
+ def forward(
266
+ self,
267
+ x,
268
+ cache = None,
269
+ return_kv_cache = False
270
+ ):
271
+
272
+ cache = default(cache, (None,) * len(self.layers))
273
+
274
+ next_kv_caches = []
275
+
276
+ for (attn, ff), kv_cache in zip(self.layers, cache):
277
+
278
+ attn_out, next_kv_cache = attn(x, kv_cache = kv_cache, return_kv_cache = True)
279
+
280
+ next_kv_caches.append(next_kv_cache)
281
+
282
+ x = attn_out + x
283
+ x = ff(x) + x
284
+
285
+ embed = self.norm(x)
286
+
287
+ if not return_kv_cache:
288
+ return embed
289
+
290
+ return embed, stack(next_kv_caches)
291
+
292
+ # class
293
+
294
+ class Locoformer(Module):
295
+ def __init__(
296
+ self,
297
+ embedder: Module,
298
+ unembedder: Module,
299
+ transformer: dict | TransformerXL
300
+ ):
301
+ super().__init__()
302
+
303
+ if isinstance(transformer, dict):
304
+ transformer = TransformerXL(**transformer)
305
+
306
+ self.transformer = transformer
307
+ self.embedder = embedder
308
+ self.unembedder = unembedder
309
+
310
+ def forward(
311
+ self,
312
+ seq,
313
+ cache: Tensor | None = None,
314
+ detach_cache = False
315
+ ):
316
+ tokens = self.embedder(seq)
317
+
318
+ embed, kv_cache = self.transformer(tokens, cache = cache, return_kv_cache = True)
319
+
320
+ logits = self.unembedder(embed)
321
+
322
+ if detach_cache:
323
+ kv_cache = detach_all(kv_cache)
324
+
325
+ return logits, kv_cache
@@ -0,0 +1,68 @@
1
+ [project]
2
+ name = "locoformer"
3
+ version = "0.0.1"
4
+ description = "LocoFormer"
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
+ 'artificial intelligence',
13
+ 'deep learning',
14
+ 'transformer',
15
+ 'attention mechanism',
16
+ 'robotics',
17
+ 'cross-embodiment',
18
+ ]
19
+
20
+ classifiers=[
21
+ 'Development Status :: 4 - Beta',
22
+ 'Intended Audience :: Developers',
23
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
24
+ 'License :: OSI Approved :: MIT License',
25
+ 'Programming Language :: Python :: 3.9',
26
+ ]
27
+
28
+ dependencies = [
29
+ "assoc-scan",
30
+ "einx>=0.3.0",
31
+ "einops>=0.8.0",
32
+ "rotary-embedding-torch",
33
+ "torch>=2.4"
34
+ ]
35
+
36
+ [project.urls]
37
+ Homepage = "https://pypi.org/project/locoformer/"
38
+ Repository = "https://github.com/lucidrains/locoformer"
39
+
40
+ [project.optional-dependencies]
41
+
42
+ examples = [
43
+ "accelerate",
44
+ "tqdm"
45
+ ]
46
+
47
+ test = [
48
+ "pytest"
49
+ ]
50
+
51
+ [tool.pytest.ini_options]
52
+ pythonpath = [
53
+ "."
54
+ ]
55
+
56
+ [build-system]
57
+ requires = ["hatchling"]
58
+ build-backend = "hatchling.build"
59
+
60
+ [tool.rye]
61
+ managed = true
62
+ dev-dependencies = []
63
+
64
+ [tool.hatch.metadata]
65
+ allow-direct-references = true
66
+
67
+ [tool.hatch.build.targets.wheel]
68
+ packages = ["locoformer"]
@@ -0,0 +1,25 @@
1
+ import pytest
2
+ param = pytest.mark.parametrize
3
+
4
+ import torch
5
+
6
+ def test_locoformer():
7
+ from locoformer.locoformer import Locoformer
8
+ from torch import nn
9
+
10
+ model = Locoformer(
11
+ embedder = nn.Embedding(256, 128),
12
+ unembedder = nn.Linear(128, 256, bias = False),
13
+ transformer = dict(
14
+ dim = 128,
15
+ depth = 1
16
+ )
17
+ )
18
+
19
+ seq = torch.randint(0, 256, (2, 512))
20
+
21
+ logits, cache = model(seq)
22
+ logits, cache = model(seq, cache = cache)
23
+ logits, cache = model(seq, cache = cache)
24
+
25
+ assert logits.shape == (2, 512, 256)
@@ -0,0 +1,132 @@
1
+ # /// script
2
+ # dependencies = [
3
+ # 'accelerate',
4
+ # 'locoformer',
5
+ # 'tqdm'
6
+ # ]
7
+ # ///
8
+
9
+ import random
10
+ import tqdm
11
+ import gzip
12
+ import numpy as np
13
+
14
+ import torch
15
+ from torch import nn
16
+ from torch import from_numpy
17
+ from torch.optim import Adam
18
+ from torch.nn import functional as F
19
+ from torch.utils.data import DataLoader, Dataset
20
+
21
+ from einops import rearrange
22
+ from accelerate import Accelerator
23
+
24
+ from locoformer.locoformer import Locoformer
25
+
26
+ # constants
27
+
28
+ NUM_BATCHES = int(1e5)
29
+ BATCH_SIZE = 16
30
+ LEARNING_RATE = 1e-4
31
+ VALIDATE_EVERY = 100
32
+
33
+ GENERATE_EVERY = 500
34
+ PRIME_LENGTH = 512
35
+ GENERATE_LENGTH = 1024
36
+
37
+ SEQ_LEN = 512
38
+ NUM_SEGMENTS = 4
39
+
40
+ # helpers
41
+
42
+ def cycle(loader):
43
+ while True:
44
+ for data in loader:
45
+ yield data
46
+
47
+ def decode_token(token):
48
+ return str(chr(max(32, token)))
49
+
50
+ def decode_tokens(tokens):
51
+ return ''.join(list(map(decode_token, tokens)))
52
+
53
+ # instantiate model
54
+
55
+ dim_model = 512
56
+
57
+ model = Locoformer(
58
+ embedder = nn.Embedding(256, dim_model),
59
+ unembedder = nn.Linear(dim_model, 256, bias = False),
60
+ transformer = dict(
61
+ dim = dim_model,
62
+ depth = 6
63
+ )
64
+ )
65
+
66
+ # prepare enwik8 data
67
+
68
+ with gzip.open('./data/enwik8.gz') as file:
69
+ data = np.fromstring(file.read(int(95e6)), dtype = np.uint8)
70
+ train_data, valid_data = np.split(data, [int(90e6)])
71
+ data_train, data_val = from_numpy(train_data), from_numpy(valid_data)
72
+
73
+ class TextSamplerDataset(Dataset):
74
+ def __init__(self, data, seq_len, segments):
75
+ super().__init__()
76
+ self.data = data
77
+ self.seq_len = seq_len
78
+ self.segments = segments
79
+ self.total_len = seq_len * segments
80
+
81
+ def __getitem__(self, index):
82
+ rand_start = torch.randint(0, self.data.size(0) - self.total_len - 1, (1,))
83
+ full_seq = self.data[rand_start: rand_start + self.total_len + 1].long()
84
+ return full_seq
85
+
86
+ def __len__(self):
87
+ return self.data.size(0) // self.total_len
88
+
89
+ train_dataset = TextSamplerDataset(data_train, SEQ_LEN, NUM_SEGMENTS)
90
+ val_dataset = TextSamplerDataset(data_val, SEQ_LEN, NUM_SEGMENTS)
91
+ train_loader = DataLoader(train_dataset, batch_size = BATCH_SIZE)
92
+ val_loader = DataLoader(val_dataset, batch_size = BATCH_SIZE)
93
+
94
+ # optimizer
95
+
96
+ optim = Adam(model.parameters(), lr = LEARNING_RATE)
97
+
98
+ # prepare accelerate
99
+
100
+ accelerate = Accelerator()
101
+
102
+ model, optim, train_loader = accelerate.prepare(model, optim, train_loader)
103
+
104
+ # training loop
105
+
106
+ train_loader_iter = cycle(train_loader)
107
+
108
+ for _ in range(NUM_BATCHES):
109
+
110
+ seq = next(train_loader_iter)
111
+ seq, labels = seq[:, :-1], seq[:, 1:]
112
+
113
+ cache = None
114
+
115
+ for segment_seq, segment_labels in zip(seq.chunk(NUM_SEGMENTS, dim = -1), labels.chunk(NUM_SEGMENTS, dim = -1)):
116
+
117
+ logits, cache = model(
118
+ segment_seq,
119
+ cache = cache,
120
+ detach_cache = True
121
+ )
122
+
123
+ loss = F.cross_entropy(
124
+ rearrange(logits, 'b n l -> b l n'),
125
+ segment_labels
126
+ )
127
+
128
+ accelerate.backward(loss / NUM_SEGMENTS)
129
+ accelerate.print(f'loss: {loss.item():.3f}')
130
+
131
+ optim.step()
132
+ optim.zero_grad()