stackformers 3.8.0__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 (79) hide show
  1. stackformers-3.8.0/.claude/settings.json +7 -0
  2. stackformers-3.8.0/.claudeignore +17 -0
  3. stackformers-3.8.0/.gitignore +219 -0
  4. stackformers-3.8.0/.python-version +1 -0
  5. stackformers-3.8.0/.vscode/settings.json +3 -0
  6. stackformers-3.8.0/CLAUDE.md +89 -0
  7. stackformers-3.8.0/Justfile +68 -0
  8. stackformers-3.8.0/LICENSE +21 -0
  9. stackformers-3.8.0/PKG-INFO +204 -0
  10. stackformers-3.8.0/PLAN.md +109 -0
  11. stackformers-3.8.0/README.md +156 -0
  12. stackformers-3.8.0/pyproject.toml +72 -0
  13. stackformers-3.8.0/stackformers/__init__.py +136 -0
  14. stackformers-3.8.0/stackformers/attention/README.md +21 -0
  15. stackformers-3.8.0/stackformers/attention/__init__.py +16 -0
  16. stackformers-3.8.0/stackformers/attention/bias.py +12 -0
  17. stackformers-3.8.0/stackformers/attention/config.py +145 -0
  18. stackformers-3.8.0/stackformers/attention/cross_attn.py +77 -0
  19. stackformers-3.8.0/stackformers/attention/ops.py +167 -0
  20. stackformers-3.8.0/stackformers/attention/protocols.py +44 -0
  21. stackformers-3.8.0/stackformers/attention/self_attn.py +88 -0
  22. stackformers-3.8.0/stackformers/config.py +26 -0
  23. stackformers-3.8.0/stackformers/cross_attender.py +46 -0
  24. stackformers-3.8.0/stackformers/decoder.py +57 -0
  25. stackformers-3.8.0/stackformers/encoder.py +26 -0
  26. stackformers-3.8.0/stackformers/feedforward/README.md +11 -0
  27. stackformers-3.8.0/stackformers/feedforward/__init__.py +5 -0
  28. stackformers-3.8.0/stackformers/feedforward/config.py +68 -0
  29. stackformers-3.8.0/stackformers/feedforward/factory.py +24 -0
  30. stackformers-3.8.0/stackformers/feedforward/geglu.py +35 -0
  31. stackformers-3.8.0/stackformers/feedforward/protocols.py +16 -0
  32. stackformers-3.8.0/stackformers/feedforward/relu_squared.py +28 -0
  33. stackformers-3.8.0/stackformers/feedforward/swiglu.py +34 -0
  34. stackformers-3.8.0/stackformers/layers.py +31 -0
  35. stackformers-3.8.0/stackformers/norm/README.md +11 -0
  36. stackformers-3.8.0/stackformers/norm/__init__.py +3 -0
  37. stackformers-3.8.0/stackformers/norm/config.py +20 -0
  38. stackformers-3.8.0/stackformers/norm/factory.py +18 -0
  39. stackformers-3.8.0/stackformers/norm/protocols.py +16 -0
  40. stackformers-3.8.0/stackformers/positional/README.md +13 -0
  41. stackformers-3.8.0/stackformers/positional/__init__.py +23 -0
  42. stackformers-3.8.0/stackformers/positional/config.py +65 -0
  43. stackformers-3.8.0/stackformers/positional/factory.py +28 -0
  44. stackformers-3.8.0/stackformers/positional/learned.py +49 -0
  45. stackformers-3.8.0/stackformers/positional/none.py +32 -0
  46. stackformers-3.8.0/stackformers/positional/protocols.py +32 -0
  47. stackformers-3.8.0/stackformers/positional/rope1d.py +111 -0
  48. stackformers-3.8.0/stackformers/positional/rope2d.py +59 -0
  49. stackformers-3.8.0/stackformers/presets/README.md +63 -0
  50. stackformers-3.8.0/stackformers/presets/__init__.py +39 -0
  51. stackformers-3.8.0/stackformers/presets/cross_attender.py +108 -0
  52. stackformers-3.8.0/stackformers/presets/decoder.py +126 -0
  53. stackformers-3.8.0/stackformers/presets/encoder.py +150 -0
  54. stackformers-3.8.0/stackformers/sequence.py +158 -0
  55. stackformers-3.8.0/tests/__init__.py +0 -0
  56. stackformers-3.8.0/tests/attention/__init__.py +0 -0
  57. stackformers-3.8.0/tests/attention/test_cross_attn.py +120 -0
  58. stackformers-3.8.0/tests/attention/test_kernels.py +172 -0
  59. stackformers-3.8.0/tests/attention/test_ops.py +137 -0
  60. stackformers-3.8.0/tests/attention/test_self_attn.py +191 -0
  61. stackformers-3.8.0/tests/conftest.py +40 -0
  62. stackformers-3.8.0/tests/feedforward/__init__.py +0 -0
  63. stackformers-3.8.0/tests/feedforward/test_geglu.py +61 -0
  64. stackformers-3.8.0/tests/feedforward/test_relu_squared.py +49 -0
  65. stackformers-3.8.0/tests/feedforward/test_swiglu.py +49 -0
  66. stackformers-3.8.0/tests/positional/__init__.py +0 -0
  67. stackformers-3.8.0/tests/positional/test_learned_pos.py +103 -0
  68. stackformers-3.8.0/tests/positional/test_rope.py +276 -0
  69. stackformers-3.8.0/tests/presets/__init__.py +0 -0
  70. stackformers-3.8.0/tests/presets/test_cross_attender.py +36 -0
  71. stackformers-3.8.0/tests/presets/test_decoder.py +36 -0
  72. stackformers-3.8.0/tests/presets/test_encoder.py +102 -0
  73. stackformers-3.8.0/tests/test_cross_attender.py +118 -0
  74. stackformers-3.8.0/tests/test_decoder.py +141 -0
  75. stackformers-3.8.0/tests/test_encoder.py +90 -0
  76. stackformers-3.8.0/tests/test_layers.py +71 -0
  77. stackformers-3.8.0/tests/test_norm.py +36 -0
  78. stackformers-3.8.0/tests/test_sequence.py +170 -0
  79. stackformers-3.8.0/uv.lock +1011 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(python -c \"import torch; print\\(torch.__version__\\)\")"
5
+ ]
6
+ }
7
+ }
@@ -0,0 +1,17 @@
1
+ # Lock files - never useful to read
2
+ uv.lock
3
+ poetry.lock
4
+ package-lock.json
5
+ yarn.lock
6
+ Cargo.lock
7
+ *.lock
8
+
9
+ # Other noise
10
+ __pycache__/
11
+ *.pyc
12
+ .venv/
13
+ dist/
14
+ build/
15
+ *.egg-info/
16
+ .mypy_cache/
17
+ .ruff_cache/
@@ -0,0 +1,219 @@
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
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
219
+ x-transformers
@@ -0,0 +1 @@
1
+ 3.11
@@ -0,0 +1,3 @@
1
+ {
2
+ "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python"
3
+ }
@@ -0,0 +1,89 @@
1
+ # CLAUDE.md — stackformers
2
+
3
+ ## What this project is
4
+ Typed, composable, SOLID transformer library for PyTorch.
5
+ Behavior comes from injected dependencies, not constructor flags.
6
+
7
+ ## Key rules — never violate these
8
+
9
+ - No optional fields on dataclasses to encode different modes — use sealed unions instead
10
+ - No `if self.x is not None` inside `forward()` — use null objects (e.g. `NoPosEncoding`)
11
+ - No flags in `__init__` that change `forward()` behavior — new behavior = new class
12
+ - `forward()` must be traceable by torch.compile and torch.export — no Python control flow on tensors
13
+ - One concept per file — if you can't describe it in one sentence, split it
14
+ - All tensor args annotated with jaxtyping shape strings using project dim vocabulary
15
+ - Every collaborator accepted by `__init__` must be typed as a protocol, never as a concrete class
16
+
17
+ ## Dim naming convention (use everywhere)
18
+ | Symbol | Meaning |
19
+ |--------|---------|
20
+ | b | batch size |
21
+ | n | query sequence length |
22
+ | s | key/value sequence length (= n for self-attn) |
23
+ | d | model dim |
24
+ | h | number of heads |
25
+ | dh | dim per head |
26
+ | w | window size |
27
+ | nt | total tokens in packed sequence |
28
+
29
+ ## File organisation
30
+
31
+ - All code lives directly under `stackformers/`. Breaking changes go in a new top-level package.
32
+ - Configs live next to the class they configure: `attention/config.py`, `feedforward/config.py`.
33
+ - Cross-cutting configs (`LayerConfig`, `EncoderConfig`, `DecoderConfig`) live at `config.py`.
34
+ - Each module has a `factory.py` with a `build_*` function that dispatches on config type via `match`.
35
+ - Opinionated presets live in `presets/` — one file per preset class.
36
+ - Protocols are defined in the module they belong to (`attention/protocols.py`, etc.), not a central file.
37
+ - Implementations satisfy protocols structurally — they never import the protocol they implement.
38
+
39
+ ## Config and factory conventions
40
+
41
+ Every union config type uses a `kind: Literal[...]` discriminator field so configs round-trip through JSON unambiguously. The union itself is an `Annotated[..., Field(discriminator="kind")]` alias defined in the same `config.py`.
42
+
43
+ Each module owns its builder in a co-located `factory.py`. The function signature is `build_*(config: *Config, ...) -> Protocol`. Presets call these factories — they never instantiate concrete classes directly.
44
+
45
+ ## Module-level READMEs
46
+
47
+ Each subdirectory has a `README.md`. When you change a module's design — add a variant, remove a concept, change a dispatch strategy — update its `README.md` in the same commit. The README covers: purpose in one or two sentences, key design decisions, and how to extend with a new variant. It must not restate what reading the source already gives you (no file tables, no copied signatures).
48
+
49
+ ## Testing rules
50
+ - One test file per source file, mirroring directory structure
51
+ - Use pytest fixtures for module construction, inputs, and sequence objects — no plain helper functions
52
+ - Parametrise over `device_dtype` (all device×dtype combos) for compute tests; use `device` alone (float32) for gradient tests
53
+ - Test shape contracts, not numeric values
54
+ - Numerical assertions use `atol(dtype)` from `tests/conftest.py`
55
+
56
+ ## Dependencies
57
+ - PyTorch native first: `F.scaled_dot_product_attention`, `torch.nn.attention.varlen.varlen_attn`
58
+ - No optional third-party kernel dependencies — all kernels are pure PyTorch
59
+ - Pydantic for configs; use `Field(gt=0)` / `Field(ge=0)` constraints, not `@field_validator`, for simple bounds
60
+ - Prefer `nn.Module` activations (`nn.SiLU()`, `nn.GELU()`) over `torch.nn.functional` calls
61
+
62
+ ## x-transformers reference
63
+ Cloned at `./x-transformers/` — read for math and implementation details only.
64
+ Do not copy its architecture.
65
+
66
+ ## Versioning
67
+
68
+ Version is maintained in `pyproject.toml` under `[project].version` and exposed at runtime via `stackformers.__version__`.
69
+
70
+ Use [Semantic Versioning](https://semver.org/):
71
+ - **MAJOR** — breaking public API change
72
+ - **MINOR** — new backwards-compatible feature
73
+ - **PATCH** — bug fix or internal change with no API impact
74
+
75
+ Bump the version in `pyproject.toml` on every commit that changes behaviour. Commits that only touch docs, tests, or CI do not require a bump.
76
+
77
+ ## Commands
78
+ ```bash
79
+ just fmt # ruff format
80
+ just lint # ruff check
81
+ just types # pyrefly
82
+ just test # pytest
83
+ just check # full CI gate: fmt-check + lint + types + test
84
+ ```
85
+
86
+ ## PyTorch
87
+ - Before writing any torch code, run: `python -c "import torch; print(torch.__version__)"`
88
+ - Always prefer built-in torch implementations over custom ones
89
+ - Check `.venv/lib/python3.*/site-packages/torch/nn/modules/` for what's available
@@ -0,0 +1,68 @@
1
+ set dotenv-load := false
2
+
3
+ # List available recipes
4
+ default:
5
+ @just --list
6
+
7
+ # ── Dependencies ────────────────────────────────────────────────────────────
8
+
9
+ # Install all dependencies (including dev)
10
+ sync:
11
+ uv sync --group dev
12
+
13
+ # ── Formatting ──────────────────────────────────────────────────────────────
14
+
15
+ # Format source and tests
16
+ fmt:
17
+ uv run ruff format stackformers/ tests/
18
+
19
+ # Check formatting without modifying files
20
+ fmt-check:
21
+ uv run ruff format --check stackformers/ tests/
22
+
23
+ # ── Linting ─────────────────────────────────────────────────────────────────
24
+
25
+ # Lint source and tests
26
+ lint:
27
+ uv run ruff check stackformers/ tests/
28
+
29
+ # Lint and auto-fix what's safe
30
+ lint-fix:
31
+ uv run ruff check --fix stackformers/ tests/
32
+
33
+ # ── Type checking ────────────────────────────────────────────────────────────
34
+
35
+ # Type-check with pyrefly
36
+ types:
37
+ uv run pyrefly check stackformers/ tests/
38
+
39
+ # ── Testing ─────────────────────────────────────────────────────────────────
40
+
41
+ # Run tests
42
+ test:
43
+ uv run pytest tests/ -q
44
+
45
+ # Run tests with coverage report
46
+ test-cov:
47
+ uv run pytest tests/ --cov=stackformers --cov-report=term-missing -q
48
+
49
+ # Run a single test file or pattern, e.g.: just test-only tests/v1/test_encoder.py
50
+ test-only target:
51
+ uv run pytest {{ target }} -v
52
+
53
+ # ── Combined checks ──────────────────────────────────────────────────────────
54
+
55
+ # Run fmt-check + lint + types + test (CI gate)
56
+ check: fmt-check lint types test
57
+
58
+ # Format, lint-fix, then run all checks
59
+ fix: fmt lint-fix
60
+ just check
61
+
62
+ # ── Housekeeping ─────────────────────────────────────────────────────────────
63
+
64
+ # Remove build artifacts and caches
65
+ clean:
66
+ rm -rf dist/ .venv/ .ruff_cache/ .pytest_cache/ __pycache__
67
+ find . -type d -name "__pycache__" -exec rm -rf {} +
68
+ find . -type d -name "*.egg-info" -exec rm -rf {} +
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vadym Stupakov
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,204 @@
1
+ Metadata-Version: 2.4
2
+ Name: stackformers
3
+ Version: 3.8.0
4
+ Summary: Typed, composable, SOLID transformer library for PyTorch
5
+ Project-URL: Homepage, https://github.com/Red-Eyed/stackformers
6
+ Project-URL: Repository, https://github.com/Red-Eyed/stackformers
7
+ Project-URL: Bug Tracker, https://github.com/Red-Eyed/stackformers/issues
8
+ Author-email: Vadym Stupakov <vadim.stupakov@gmail.com>
9
+ License: MIT License
10
+
11
+ Copyright (c) 2026 Vadym Stupakov
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
30
+ License-File: LICENSE
31
+ Keywords: attention,deep-learning,pytorch,transformer
32
+ Classifier: Development Status :: 4 - Beta
33
+ Classifier: Intended Audience :: Science/Research
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Programming Language :: Python :: 3.11
37
+ Classifier: Programming Language :: Python :: 3.12
38
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
39
+ Classifier: Typing :: Typed
40
+ Requires-Python: >=3.11
41
+ Requires-Dist: beartype>=0.18
42
+ Requires-Dist: einops>=0.7
43
+ Requires-Dist: jaxtyping>=0.2
44
+ Requires-Dist: numpy>=2.4.4
45
+ Requires-Dist: pydantic>=2.0
46
+ Requires-Dist: torch>=2.2
47
+ Description-Content-Type: text/markdown
48
+
49
+ # stackformers
50
+
51
+ Typed, composable transformer library for PyTorch.
52
+ Every architectural choice — positional encoding, normalization, feedforward variant — is an injected dependency, not a constructor flag.
53
+
54
+ ```bash
55
+ uv add stackformers
56
+ ```
57
+
58
+ ---
59
+
60
+ ## Why
61
+
62
+ Most transformer libraries grow into a tangle of `if self.use_rope`, `if self.window_size is not None`, and god-config objects with thirty nullable fields. Adding a new variant means touching existing code.
63
+
64
+ stackformers takes a different approach:
65
+
66
+ - **Swap any component without touching anything else** — `SelfAttention(config, pos_encoding=RoPE)` vs `SelfAttention(config, pos_encoding=ALiBi)` — same call site, different object
67
+ - **No `None` checks in `forward()`** — `NoPosEncoding` is a real object that passes q/k unchanged; the branch never exists
68
+ - **Sealed sequence unions** — `PaddedInput | PackedInput` instead of optional `cu_seqlens` and `mask` arguments that conflict with each other
69
+ - **`torch.compile` / `torch.export` safe** — no Python control flow on tensors inside any `forward()`
70
+ - **Structural protocols** — bring your own implementation; no ABC inheritance required
71
+
72
+ ---
73
+
74
+ ## Quick start
75
+
76
+ ### Zero boilerplate
77
+
78
+ ```python
79
+ import torch
80
+ from stackformers import TransformerEncoder, plain_encoder_config, make_padded_input
81
+
82
+ model = TransformerEncoder(plain_encoder_config(dim=512, heads=8, num_layers=6))
83
+
84
+ x = torch.randn(2, 128, 512)
85
+ mask = torch.ones(2, 128, dtype=torch.bool)
86
+ out = model(make_padded_input(x, mask)) # (2, 128, 512)
87
+ ```
88
+
89
+ Switch to packed (variable-length, no padding waste) — same weights:
90
+
91
+ ```python
92
+ from stackformers import make_packed_input
93
+
94
+ cu = torch.tensor([0, 64, 128], dtype=torch.int32)
95
+ out = model(make_packed_input(x_flat, cu, max_seqlen=64)) # (128, 512)
96
+ ```
97
+
98
+ Causal LM backbone:
99
+
100
+ ```python
101
+ plain_encoder_config(dim=768, heads=12, num_layers=12, causal=True)
102
+ ```
103
+
104
+ Sliding-window local attention (O(n · w)):
105
+
106
+ ```python
107
+ from stackformers import windowed_encoder_config
108
+ windowed_encoder_config(dim=512, heads=8, num_layers=6, window_size=128)
109
+ ```
110
+
111
+ Encoder–decoder:
112
+
113
+ ```python
114
+ from stackformers import TransformerDecoder, plain_decoder_config
115
+
116
+ model = TransformerDecoder(plain_decoder_config(dim=512, heads=8, num_layers=6))
117
+ out = model(make_padded_input(x, mask), make_padded_input(context, ctx_mask))
118
+ ```
119
+
120
+ ### Explicit config
121
+
122
+ Full control with JSON round-trip via `kind` discriminators:
123
+
124
+ ```python
125
+ from stackformers import (
126
+ TransformerEncoderConfig, TransformerEncoder,
127
+ SelfAttentionConfig, SwiGLUConfig, RMSNormConfig, RoPE1DConfig,
128
+ make_padded_input,
129
+ )
130
+
131
+ cfg = TransformerEncoderConfig(
132
+ attn=SelfAttentionConfig(dim=512, heads=8, dim_head=64, causal=False),
133
+ ff=SwiGLUConfig(dim=512, mult=4.0),
134
+ norm=RMSNormConfig(dim=512),
135
+ pos_encoding=RoPE1DConfig(dim_head=64),
136
+ num_layers=6,
137
+ )
138
+ model = TransformerEncoder(cfg)
139
+
140
+ # Serialise / restore
141
+ cfg2 = TransformerEncoderConfig.model_validate(cfg.model_dump())
142
+ ```
143
+
144
+ ### Custom wiring
145
+
146
+ Wire layers yourself when presets aren't enough:
147
+
148
+ ```python
149
+ from stackformers import (
150
+ SelfAttention, SwiGLU, TransformerLayer, Encoder, RMSNorm,
151
+ RotaryEmbedding1D,
152
+ SelfAttentionConfig, SwiGLUConfig, RMSNormConfig, RoPE1DConfig,
153
+ )
154
+
155
+ pos = RotaryEmbedding1D(RoPE1DConfig(dim_head=64))
156
+ attn = SelfAttention(SelfAttentionConfig(dim=512, heads=8, dim_head=64), pos_encoding=pos)
157
+
158
+ layers = [
159
+ TransformerLayer(
160
+ self_attn=attn,
161
+ ff=SwiGLU(SwiGLUConfig(dim=512)),
162
+ norm_attn=RMSNorm(RMSNormConfig(dim=512)),
163
+ norm_ff=RMSNorm(RMSNormConfig(dim=512)),
164
+ )
165
+ for _ in range(6)
166
+ ]
167
+ encoder = Encoder(layers=layers, final_norm=RMSNorm(RMSNormConfig(dim=512)))
168
+ ```
169
+
170
+ ---
171
+
172
+ ## What's included
173
+
174
+ | Area | Variants |
175
+ |------|----------|
176
+ | Self-attention | Global, sliding-window (local); padded and packed backends; GQA / MQA |
177
+ | Cross-attention | Global; padded and packed backends |
178
+ | Positional encoding | RoPE-1D, RoPE-2D, none (null object) |
179
+ | Feedforward | SwiGLU, GEGLU |
180
+ | Normalization | RMSNorm, LayerNorm |
181
+ | Presets | Encoder, Decoder, CrossAttender |
182
+
183
+ On CUDA with fp16/bf16 the packed path uses `torch.nn.attention.varlen.varlen_attn`. CPU and fp32 fall back to a scatter-to-padded SDPA — correct everywhere, fast where it matters.
184
+
185
+ ---
186
+
187
+ ## Development
188
+
189
+ ```bash
190
+ git clone <repo> && cd stackformers
191
+ uv sync --group dev
192
+
193
+ just fmt # format
194
+ just lint # lint
195
+ just types # type-check
196
+ just test # test
197
+ just check # full CI gate
198
+ ```
199
+
200
+ ---
201
+
202
+ ## License
203
+
204
+ See [LICENSE](LICENSE).