superlinear 0.1.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 (67) hide show
  1. superlinear-0.1.0/LICENSE +202 -0
  2. superlinear-0.1.0/PKG-INFO +469 -0
  3. superlinear-0.1.0/README.md +418 -0
  4. superlinear-0.1.0/apps/__init__.py +4 -0
  5. superlinear-0.1.0/apps/cli/__init__.py +8 -0
  6. superlinear-0.1.0/apps/cli/bm25_rag.py +471 -0
  7. superlinear-0.1.0/apps/cli/chat_repl.py +1497 -0
  8. superlinear-0.1.0/apps/cli/client.py +195 -0
  9. superlinear-0.1.0/apps/cli/docs_repl.py +2275 -0
  10. superlinear-0.1.0/apps/cli/light_rag.py +729 -0
  11. superlinear-0.1.0/apps/cli/local_snapshots.py +139 -0
  12. superlinear-0.1.0/apps/cli/locks.py +214 -0
  13. superlinear-0.1.0/apps/cli/main.py +457 -0
  14. superlinear-0.1.0/apps/cli/output.py +32 -0
  15. superlinear-0.1.0/apps/cli/server_cmds.py +516 -0
  16. superlinear-0.1.0/apps/cli/session_cmds.py +491 -0
  17. superlinear-0.1.0/apps/cli/snapshot_cmds.py +303 -0
  18. superlinear-0.1.0/apps/cli/state.py +265 -0
  19. superlinear-0.1.0/apps/server/__init__.py +4 -0
  20. superlinear-0.1.0/apps/server/app.py +1363 -0
  21. superlinear-0.1.0/apps/server/main.py +313 -0
  22. superlinear-0.1.0/pyproject.toml +122 -0
  23. superlinear-0.1.0/setup.cfg +4 -0
  24. superlinear-0.1.0/superlinear/__init__.py +114 -0
  25. superlinear-0.1.0/superlinear/_version.py +3 -0
  26. superlinear-0.1.0/superlinear/engine/__init__.py +10 -0
  27. superlinear-0.1.0/superlinear/engine/adapters/__init__.py +12 -0
  28. superlinear-0.1.0/superlinear/engine/adapters/base.py +91 -0
  29. superlinear-0.1.0/superlinear/engine/adapters/superlinear.py +1233 -0
  30. superlinear-0.1.0/superlinear/engine/chat_engine.py +1173 -0
  31. superlinear-0.1.0/superlinear/engine/chat_types.py +130 -0
  32. superlinear-0.1.0/superlinear/engine/registry.py +51 -0
  33. superlinear-0.1.0/superlinear/engine/repetition.py +203 -0
  34. superlinear-0.1.0/superlinear/engine/session_snapshots.py +451 -0
  35. superlinear-0.1.0/superlinear/engine/tool_parser.py +83 -0
  36. superlinear-0.1.0/superlinear/engine/types.py +42 -0
  37. superlinear-0.1.0/superlinear/kernels/__init__.py +2 -0
  38. superlinear-0.1.0/superlinear/kernels/common/__init__.py +21 -0
  39. superlinear-0.1.0/superlinear/kernels/common/adjustment.py +106 -0
  40. superlinear-0.1.0/superlinear/kernels/common/power.py +154 -0
  41. superlinear-0.1.0/superlinear/kernels/superlinear/__init__.py +10 -0
  42. superlinear-0.1.0/superlinear/kernels/superlinear/attention/__init__.py +78 -0
  43. superlinear-0.1.0/superlinear/kernels/superlinear/attention/_prefill.py +940 -0
  44. superlinear-0.1.0/superlinear/kernels/superlinear/attention/_sliding_window.py +1167 -0
  45. superlinear-0.1.0/superlinear/kernels/superlinear/attention/api.py +433 -0
  46. superlinear-0.1.0/superlinear/kernels/superlinear/search/__init__.py +33 -0
  47. superlinear-0.1.0/superlinear/kernels/superlinear/search/_reference.py +204 -0
  48. superlinear-0.1.0/superlinear/kernels/superlinear/search/_triton.py +488 -0
  49. superlinear-0.1.0/superlinear/kernels/superlinear/search/_triton_gqa.py +534 -0
  50. superlinear-0.1.0/superlinear/kernels/superlinear/search/api.py +200 -0
  51. superlinear-0.1.0/superlinear/kernels/superlinear/span/__init__.py +41 -0
  52. superlinear-0.1.0/superlinear/kernels/superlinear/span/_triton_bucketed_gqa.py +1461 -0
  53. superlinear-0.1.0/superlinear/kernels/superlinear/span/_triton_forward.py +22 -0
  54. superlinear-0.1.0/superlinear/kernels/superlinear/span/_triton_gqa.py +1226 -0
  55. superlinear-0.1.0/superlinear/kernels/superlinear/span/_triton_impl.py +928 -0
  56. superlinear-0.1.0/superlinear/kernels/superlinear/span/_triton_precomputed_sw.py +460 -0
  57. superlinear-0.1.0/superlinear/kernels/superlinear/span/_triton_precomputed_sw_gqa.py +598 -0
  58. superlinear-0.1.0/superlinear/kernels/superlinear/span/api.py +296 -0
  59. superlinear-0.1.0/superlinear/kernels/superlinear/span/masks.py +187 -0
  60. superlinear-0.1.0/superlinear/py.typed +0 -0
  61. superlinear-0.1.0/superlinear/runtime.py +71 -0
  62. superlinear-0.1.0/superlinear.egg-info/PKG-INFO +469 -0
  63. superlinear-0.1.0/superlinear.egg-info/SOURCES.txt +65 -0
  64. superlinear-0.1.0/superlinear.egg-info/dependency_links.txt +1 -0
  65. superlinear-0.1.0/superlinear.egg-info/entry_points.txt +2 -0
  66. superlinear-0.1.0/superlinear.egg-info/requires.txt +30 -0
  67. superlinear-0.1.0/superlinear.egg-info/top_level.txt +2 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,469 @@
1
+ Metadata-Version: 2.4
2
+ Name: superlinear
3
+ Version: 0.1.0
4
+ Summary: Efficient sparse attention kernels for long-context language models
5
+ Author: Superlinear Authors
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/concavity-ai/superlinear
8
+ Project-URL: Documentation, https://github.com/concavity-ai/superlinear#readme
9
+ Project-URL: Repository, https://github.com/concavity-ai/superlinear
10
+ Project-URL: Issues, https://github.com/concavity-ai/superlinear/issues
11
+ Keywords: attention,transformers,triton,sparse-attention,long-context,machine-learning,deep-learning
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: torch>=2.0.0
27
+ Requires-Dist: triton>=2.1.0
28
+ Provides-Extra: cli
29
+ Requires-Dist: rank-bm25>=0.2.2; extra == "cli"
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7.0; extra == "dev"
32
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
33
+ Requires-Dist: black>=23.0; extra == "dev"
34
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
35
+ Requires-Dist: mypy>=1.0; extra == "dev"
36
+ Provides-Extra: inference
37
+ Requires-Dist: transformers<5,>=4.38.0; extra == "inference"
38
+ Requires-Dist: accelerate>=0.26.0; extra == "inference"
39
+ Provides-Extra: model
40
+ Requires-Dist: transformers<5,>=4.38.0; extra == "model"
41
+ Requires-Dist: accelerate>=0.26.0; extra == "model"
42
+ Requires-Dist: vllm>=0.15.0; extra == "model"
43
+ Provides-Extra: server
44
+ Requires-Dist: fastapi>=0.110.0; extra == "server"
45
+ Requires-Dist: uvicorn>=0.23.0; extra == "server"
46
+ Provides-Extra: docs
47
+ Requires-Dist: sphinx>=6.0; extra == "docs"
48
+ Requires-Dist: sphinx-rtd-theme>=1.0; extra == "docs"
49
+ Requires-Dist: myst-parser>=1.0; extra == "docs"
50
+ Dynamic: license-file
51
+
52
+ # Superlinear
53
+
54
+ **Long-context inference with efficient sparse attention**
55
+
56
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
57
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
58
+ [![PyTorch 2.0+](https://img.shields.io/badge/pytorch-2.0+-ee4c2c.svg)](https://pytorch.org/)
59
+
60
+ Superlinear is an inference engine for long-context language models built on [Superlinear Multi-Step Attention](https://arxiv.org/abs/2601.18401) — a fully trainable multi-step attention architecture that achieves **subquadratic complexity** while preserving **random context access** (no eligible token position is structurally excluded from attention). It comes with an OpenAI-compatible server and a CLI that lets you chat, ingest documents, and manage sessions — with **explicit, stateful KV cache reuse across turns**. Unlike stateless “send the full prompt every turn” setups, Superlinear exposes sessions/snapshots so you can directly manage KV cache lifetime and GPU memory for performance.
61
+
62
+ > **⚠️ Research Preview — Not for Production Use**
63
+ >
64
+ > This software and its associated model weights are released as an **experimental research artifact** accompanying the [Superlinear Multi-Step Attention](https://arxiv.org/abs/2601.18401) paper. They are provided for research, experimentation, and exploration purposes only. The model has undergone **limited** training and evaluation (primarily NIAH retrieval); it has **not** been evaluated for safety, factual accuracy, or robustness across general tasks. **Do not use this system for any critical, production, or decision-making applications.** The authors and contributors assume no responsibility or liability for any outputs generated or consequences arising from the use of this software.
65
+
66
+ <p align="center">
67
+ <img src="assets/superlinear_architecture.png" alt="Superlinear attention architecture" width="900">
68
+ </p>
69
+
70
+ <p align="center"><em>
71
+ Superlinear attention reformulates causal self-attention as a multi-step search problem with N steps,
72
+ yielding O(L<sup>1+1/N</sup>) complexity. In the baseline N=2 instantiation (analogous to jump search):<br>
73
+ (1) <b>accumulate</b> prefix context via linear recurrence (Mamba-2),
74
+ (2) <b>span-search</b> over O(√L) anchors to route to relevant regions,
75
+ (3) <b>span-attention</b> over the top-k selected spans, and
76
+ (4) <b>combine</b> via softmax-weighted gating —
77
+ achieving O(L<sup>3/2</sup>) complexity while preserving random context access.
78
+ </em></p>
79
+
80
+ ## Installation
81
+
82
+ ### Install the repo (kernels + CLI/server)
83
+
84
+ ```bash
85
+ git clone https://github.com/concavity-ai/superlinear.git
86
+ cd superlinear
87
+
88
+ # Superlinear itself only depends on torch + triton.
89
+ pip install -e ".[server]"
90
+ ```
91
+
92
+ **Requirements:** Python ≥ 3.9, PyTorch ≥ 2.0, Triton ≥ 2.1, CUDA-capable GPU.
93
+
94
+ ### Run the released model (additional GPU deps)
95
+
96
+ To run **concavity-ai/superlinear-exp-v0.1**, you need additional model/runtime dependencies and CUDA-compiled extensions.
97
+
98
+ Copy/paste one-liner (recommended, from repo root):
99
+
100
+ ```bash
101
+ conda env create -f environment.yml \
102
+ && conda run -n superlinear pip install torch --index-url https://download.pytorch.org/whl/cu128 \
103
+ && conda run -n superlinear pip install -e ".[server,model]" \
104
+ && conda run -n superlinear bash -lc 'CUDA_HOME="$CONDA_PREFIX" pip install "mamba-ssm[causal-conv1d]" --no-build-isolation --no-cache-dir --no-binary :all:'
105
+ ```
106
+
107
+ See [docs/installation.md](docs/installation.md) for step-by-step instructions, tested versions, and a pip-only option (if you already have `mamba-ssm[causal-conv1d]` working).
108
+
109
+ ## Memory Management
110
+
111
+ Superlinear’s main differentiator is **stateful KV cache reuse**: you can keep long contexts “hot” across turns and actively control memory/performance via sessions, snapshots, and chunked prefill (`--chunk-size`).
112
+
113
+ - **GPU memory budgeting.** The model weights for **concavity-ai/superlinear-exp-v0.1** require ~60 GB VRAM at 16-bit precision. Additionally, the KV cache uses ~6 GB per million tokens of context. Budget extra headroom for chunked prefill working memory. A single 80 GB GPU can run up to ~2M context; 180 GB (e.g., B200) supports 10M+ context.
114
+
115
+ - **KV cache dominates at long context.** Rough rule of thumb: ~6 GB per 1M tokens *per active session*. If you keep multiple sessions open concurrently, KV cache usage scales roughly linearly with the number of sessions.
116
+ - **Chunked prefill trades throughput for peak VRAM.** Prefill runs in chunks to limit peak memory. The server default is `--chunk-size 8192`.
117
+ - Larger chunks typically improve throughput (fewer chunk boundaries / overhead).
118
+ - Smaller chunks reduce peak VRAM during prefill, which can help avoid OOM on smaller GPUs.
119
+ - If you hit OOM during prefill, try reducing chunk size first:
120
+ - `spl server start --model concavity-ai/superlinear-exp-v0.1 --chunk-size 4096`
121
+ - (or increase it on large-memory GPUs for better throughput, e.g. `--chunk-size 32768`, as used in the paper’s throughput measurements)
122
+ - **Use sessions to avoid re-prefill.** Stateful sessions persist the KV cache across turns, so follow-up turns don’t require re-sending/re-prefilling the entire history.
123
+ - **Use snapshots to checkpoint and free GPU memory.** Snapshots save session/workspace state to disk so you can close sessions (freeing VRAM) and later resume from a snapshot without re-ingesting documents.
124
+
125
+ ---
126
+
127
+ ## Quick Start
128
+
129
+ ### 1. Start the server
130
+
131
+ ```bash
132
+ spl server start --model concavity-ai/superlinear-exp-v0.1
133
+ ```
134
+
135
+ This downloads the model (if needed) and launches the inference server in the background (default: `http://127.0.0.1:8787`). Check status with `spl server status`.
136
+
137
+ ### 2. Chat
138
+
139
+ ```bash
140
+ spl chat
141
+ ```
142
+
143
+ Opens an interactive REPL with persistent sessions and thinking mode. Type `/help` for all commands.
144
+
145
+ ```
146
+ spl(chat:chat_20260206_...)> What is the capital of France?
147
+ thinking: The user is asking a simple factual question...
148
+ assistant: The capital of France is Paris.
149
+ ```
150
+
151
+ ### 3. Document Q&A
152
+
153
+ Load documents into a workspace, then ask questions with automatic RAG retrieval:
154
+
155
+ ```bash
156
+ spl docs wiki
157
+ ```
158
+
159
+ ```
160
+ spl(docs:wiki:INGEST)> /add examples/docs/wiki -s
161
+ added files=8 bytes=... sources=8
162
+ saved base_snapshot_id=764cb17e...
163
+
164
+ spl(docs:wiki:INGEST)> How do RNNs and Transformers differ in handling sequences?
165
+ assistant: ...
166
+ ```
167
+
168
+ Save your workspace as a snapshot and resume later:
169
+
170
+ ```
171
+ # Later, resume from the snapshot:
172
+ $ spl docs wiki -l 764cb17e...
173
+ ```
174
+
175
+ ---
176
+
177
+ ## CLI Reference
178
+
179
+ The `spl` command is the primary interface. All commands talk to the server over HTTP.
180
+
181
+ ### Server Management
182
+
183
+ ```bash
184
+ spl server start --model concavity-ai/superlinear-exp-v0.1 # Start server (background)
185
+ spl server start --model concavity-ai/superlinear-exp-v0.1 --foreground # Start in foreground
186
+ spl server start --model concavity-ai/superlinear-exp-v0.1 --chunk-size 4096 # Reduce peak VRAM during prefill (default: 8192)
187
+ spl server status # Check if server is running
188
+ spl server stop # Stop server
189
+ spl server connect <url> # Connect to a remote server
190
+ ```
191
+
192
+ ### Chat & Docs REPLs
193
+
194
+ ```bash
195
+ spl chat # Interactive chat
196
+ spl chat --new # Start fresh session
197
+ spl docs <name> # Document Q&A workspace
198
+ spl docs <name> -l <snapshot_id> # Resume from snapshot
199
+ ```
200
+
201
+ Both REPLs support these commands (type `/help` inside):
202
+
203
+ | Command | Description |
204
+ |---------|-------------|
205
+ | `/help` | Show all commands |
206
+ | `/ls` | List sessions and snapshots |
207
+ | `/rm` | Delete current session, start fresh |
208
+ | `/rm <id...>` | Delete specific session(s) or snapshot(s) |
209
+ | `/save [title]` | Save session as snapshot |
210
+ | `/load <snap>` | Load snapshot |
211
+ | `/head [n]` / `/tail [n]` | Show first/last messages |
212
+ | `/history [n]` | Show input history |
213
+ | `/stats` | Show last turn metrics |
214
+ | `/info` | Show workspace info (docs only) |
215
+ | `/add <paths...>` | Add documents (docs only) |
216
+ | `/sources` | List loaded sources (docs only) |
217
+ | `/rag ...` | Configure RAG retrieval (docs only) |
218
+
219
+ ### Session & Snapshot Management
220
+
221
+ ```bash
222
+ spl ls # List all sessions and snapshots
223
+ spl rm <id...> # Remove session(s) or snapshot(s)
224
+ spl session ls # List sessions (detailed)
225
+ spl session info <id> # Show session info
226
+ spl snapshot ls # List snapshots (detailed)
227
+ spl snapshot save --session <id> # Save session as snapshot
228
+ spl snapshot load <snap_id> # Load snapshot into new session
229
+ spl snapshot rm --all # Delete all snapshots
230
+ ```
231
+
232
+ ---
233
+
234
+ ## Using the Server API Directly
235
+
236
+ The server exposes an OpenAI-compatible API. Any OpenAI SDK client works out of the box:
237
+
238
+ ```python
239
+ from openai import OpenAI
240
+
241
+ client = OpenAI(base_url="http://localhost:8787/v1", api_key="not-needed")
242
+
243
+ response = client.chat.completions.create(
244
+ model="superlinear-exp-v0.1",
245
+ messages=[{"role": "user", "content": "Hello!"}],
246
+ max_tokens=100,
247
+ )
248
+ print(response.choices[0].message.content)
249
+ ```
250
+
251
+ ### Stateful Sessions
252
+
253
+ The key differentiator is **stateful sessions**. Instead of resending the full conversation (and re-prefilling it) each turn, the server maintains the KV cache across turns to make long-context interaction feel closer to an interactive “running process” than a stateless API call.
254
+
255
+ ```python
256
+ import requests
257
+ from openai import OpenAI
258
+
259
+ BASE = "http://localhost:8787"
260
+ client = OpenAI(base_url=f"{BASE}/v1", api_key="not-needed")
261
+
262
+ # Create a session
263
+ requests.post(f"{BASE}/v1/sessions", json={"session_id": "my-chat"})
264
+
265
+ # Turn 1 — ingests and caches
266
+ client.chat.completions.create(
267
+ model="superlinear-exp-v0.1",
268
+ messages=[{"role": "user", "content": "My name is Alice."}],
269
+ extra_body={"session_id": "my-chat"},
270
+ )
271
+
272
+ # Turn 2 — only the new message is processed; prior turns are cached
273
+ response = client.chat.completions.create(
274
+ model="superlinear-exp-v0.1",
275
+ messages=[{"role": "user", "content": "What's my name?"}],
276
+ extra_body={"session_id": "my-chat"},
277
+ )
278
+ print(response.choices[0].message.content) # "Alice"
279
+
280
+ # Cleanup
281
+ requests.delete(f"{BASE}/v1/sessions/my-chat")
282
+ ```
283
+
284
+ ### Snapshots
285
+
286
+ Snapshots save the full session state (KV cache + history) to disk. This lets you **resume conversations instantly** or **fork** a session into multiple branches without re-processing the context.
287
+
288
+ ```python
289
+ # Save a snapshot
290
+ requests.post(f"{BASE}/v1/sessions/my-chat/save", json={"title": "checkpoint-1"})
291
+ # Returns: {"snapshot_id": "764cb17e..."}
292
+
293
+ # Load it back (into a new or existing session)
294
+ requests.post(f"{BASE}/v1/snapshots/764cb17e.../load", json={"session_id": "my-chat-v2"})
295
+ ```
296
+
297
+ **Use cases:**
298
+ - **Document ingestion caching** — Ingest a large corpus once, snapshot it, and load the snapshot each time you want to ask new questions.
299
+ - **Conversation branching** — Snapshot at a decision point, then explore multiple conversation paths.
300
+ - **Warm starts** — Pre-build a session with a system prompt + reference material, snapshot it, and load it for every new user.
301
+
302
+ ### Reasoning Mode
303
+
304
+ Enable chain-of-thought reasoning with a token budget:
305
+
306
+ ```python
307
+ response = client.chat.completions.create(
308
+ model="superlinear-exp-v0.1",
309
+ messages=[{"role": "user", "content": "Solve: 15 × 17"}],
310
+ extra_body={"reasoning_budget": 256},
311
+ )
312
+ ```
313
+
314
+ ### Repetition Detection
315
+
316
+ Automatically stop runaway generation loops:
317
+
318
+ ```python
319
+ response = client.chat.completions.create(
320
+ model="superlinear-exp-v0.1",
321
+ messages=[{"role": "user", "content": "List all primes"}],
322
+ max_tokens=50000,
323
+ extra_body={
324
+ "repetition_detection": {
325
+ "enabled": True,
326
+ "tail_len": 1024,
327
+ "min_repeats": 3,
328
+ "max_period": 512,
329
+ }
330
+ },
331
+ )
332
+ # finish_reason will be "repetition" if a loop was detected
333
+ ```
334
+
335
+ ### API Endpoints
336
+
337
+ | Endpoint | Method | Description |
338
+ |----------|--------|-------------|
339
+ | `/health` | GET | Health check |
340
+ | `/v1/models` | GET | List available models |
341
+ | `/v1/chat/completions` | POST | Chat completions (streaming supported) |
342
+ | `/v1/sessions` | POST | Create a stateful session |
343
+ | `/v1/sessions` | GET | List active sessions |
344
+ | `/v1/sessions/{id}` | GET | Get session info |
345
+ | `/v1/sessions/{id}` | DELETE | Close session |
346
+ | `/v1/sessions/{id}/history` | GET | Get conversation history |
347
+ | `/v1/sessions/{id}/resize` | POST | Resize session context length |
348
+ | `/v1/sessions/{id}/save` | POST | Save session as snapshot |
349
+ | `/v1/snapshots` | GET | List snapshots |
350
+ | `/v1/snapshots/{id}` | GET | Get snapshot info |
351
+ | `/v1/snapshots/{id}` | DELETE | Delete snapshot |
352
+ | `/v1/snapshots/{id}/load` | POST | Load snapshot into session |
353
+
354
+ ---
355
+
356
+ ## Sparse Attention Kernels
357
+
358
+ Under the hood, Superlinear uses custom Triton kernels implementing the [Superlinear Multi-Step Attention](https://arxiv.org/abs/2601.18401) architecture. The baseline N=2 mechanism works as follows:
359
+
360
+ 1. **Span-search** — For each query at position *i*, score O(√i) candidate anchors (placed at a power-law stride pattern) using a routing query Q_s against accumulated keys K_a, then select the top-k anchors.
361
+ 2. **Span-attention** — Attend to contiguous spans of O(√i) tokens centered at each selected anchor, plus a local sliding window for short-range context.
362
+ 3. **Combination** — Merge span outputs via softmax-weighted gating over the search scores, making routing end-to-end trainable.
363
+
364
+ This yields O(L^{3/2}) total complexity for prefill/training while preserving **random context access**: the union of all candidate spans covers every eligible key position.
365
+
366
+ A **bucketed kernel design** groups (query, span) pairs by key-block footprint for efficient GPU tiling without global sorting. See [Section 4.3 of the paper](https://arxiv.org/abs/2601.18401) for details.
367
+
368
+ ### Throughput
369
+
370
+ Measured on a single NVIDIA B200 GPU (180 GB VRAM), batch size 1, on a modified 30B hybrid MoE model ([nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16](https://huggingface.co/nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16)). Prefill uses 32K chunked prefilling.
371
+
372
+ | Context Length | Prefill (tok/s) | Decode (tok/s) | Decode Latency |
373
+ |----------------|-----------------|----------------|----------------|
374
+ | 1M tokens | ~20,000 | ~109 | ~9.2 ms/tok |
375
+ | 10M tokens | ~5,500 | ~76 | ~13.2 ms/tok |
376
+
377
+ FlashAttention-2 is faster at short contexts (<60K) but its throughput drops rapidly with length. Superlinear attention overtakes it near 60K tokens and scales into the multi-million-token regime where dense attention is impractical. See [Section 4.4 of the paper](https://arxiv.org/abs/2601.18401) for the full comparison.
378
+
379
+ ### Key Features
380
+
381
+ - **Content-dependent routing** — Spans are selected by learned search scores, not fixed sparsity patterns.
382
+ - **Sliding window** — Recent tokens are always attended to via a local window.
383
+ - **GQA support** — First-class support for Grouped Query Attention.
384
+ - **CUDA graph compatible** — Optimized for high-throughput inference with graph capture.
385
+
386
+ ### Parameters
387
+
388
+ | Parameter | Description |
389
+ |-----------|-------------|
390
+ | `sw_index` | Sliding window index. Window size = `(sw_index + 1)² - 1` |
391
+ | `num_spans` | Number of top-k spans to aggregate (typically 2–3) |
392
+ | `backward_factor` | Factor for backward span extension from anchor |
393
+ | `forward_factor` | Factor for forward span extension from anchor |
394
+ | `search_power` | Exponent *p* for anchor stride pattern; balanced at 0.5, upscaled to ~0.55 for robustness |
395
+ | `span_power` | Exponent for span length scaling; span length ∝ i^(1−span_power). Balanced at 0.5, can differ from `search_power` for redundancy |
396
+
397
+ ### Direct Usage
398
+
399
+ ```python
400
+ import torch
401
+ from superlinear.kernels.superlinear.attention import fused_prefill_with_swtriton_gqa
402
+ from superlinear.kernels.superlinear.span import decode_span_attention_staged_gqa
403
+
404
+ B, H_Q, H_KV, L, D = 1, 32, 8, 1024, 128
405
+
406
+ Q1 = torch.randn(B, H_Q, L, D, device="cuda", dtype=torch.bfloat16)
407
+ Q2 = torch.randn(B, H_Q, L, D, device="cuda", dtype=torch.bfloat16)
408
+ K = torch.randn(B, H_KV, L, D, device="cuda", dtype=torch.bfloat16)
409
+ V = torch.randn(B, H_KV, L, D, device="cuda", dtype=torch.bfloat16)
410
+ cache_position = torch.arange(L, device="cuda")
411
+
412
+ # Prefill
413
+ output = fused_prefill_with_swtriton_gqa(
414
+ Q1, Q2, K, V, cache_position,
415
+ sw_index=3, num_spans=3,
416
+ backward_factor=3.0, forward_factor=1.0,
417
+ )
418
+
419
+ # Decode
420
+ output_decode = decode_span_attention_staged_gqa(
421
+ Q1[:, :, -1:], Q2[:, :, -1:], K, V, cache_position[-1:],
422
+ sw_index=3, enable_gqa=True,
423
+ )
424
+ ```
425
+
426
+ ## Project Structure
427
+
428
+ ```
429
+ superlinear/
430
+ ├── kernels/ # Triton attention kernels
431
+ │ ├── common/ # Shared utilities
432
+ │ └── superlinear/ # Model-specific implementations
433
+ │ ├── attention/ # Prefill and decode
434
+ │ ├── search/ # Span search operations
435
+ │ └── span/ # Low-level span attention
436
+ └── engine/ # Inference engine
437
+ ├── adapters/ # Model adapters
438
+ ├── chat_engine.py # Async streaming engine
439
+ └── chat_types.py # Type definitions
440
+
441
+ apps/
442
+ ├── server/ # OpenAI-compatible HTTP server
443
+ └── cli/ # Command-line interface (spl)
444
+ ```
445
+
446
+ ## Environment Variables
447
+
448
+ | Variable | Description |
449
+ |----------|-------------|
450
+ | `SPAN_ATTENTION_ENABLE_ASSERTS` | Enable validation checks (default: off for CUDA graphs) |
451
+ | `SPAN_ATTENTION_FORCE_SPARSE_META` | Force sparse bucketing strategy |
452
+ | `SUPERLINEAR_SNAPSHOT_DIR` | Directory to store snapshots (default: `~/.cache/spl/snapshots` or `$XDG_CACHE_HOME/spl/snapshots`) |
453
+
454
+ ## License
455
+
456
+ [Apache 2.0](LICENSE)
457
+
458
+ ## Citation
459
+
460
+ If you use Superlinear in your research, please cite:
461
+
462
+ ```bibtex
463
+ @article{huang2026superlinear,
464
+ title={Superlinear Multi-Step Attention},
465
+ author={Huang, Yufeng},
466
+ journal={arXiv preprint arXiv:2601.18401},
467
+ year={2026}
468
+ }
469
+ ```