adambridge 0.1.2__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,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 2026 John Anish G
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,441 @@
1
+ Metadata-Version: 2.4
2
+ Name: adambridge
3
+ Version: 0.1.2
4
+ Summary: AdamW with host-offloaded state, fused SIMD CPU kernels, and layer-wise overlap with the GPU backward pass
5
+ Author: John Anish G
6
+ License-Expression: Apache-2.0
7
+ Keywords: pytorch,optimizer,adamw,offload,simd,avx512
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: C
10
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: torch>=2.1
15
+ Provides-Extra: compiler
16
+ Requires-Dist: ziglang; extra == "compiler"
17
+ Provides-Extra: test
18
+ Requires-Dist: pytest>=7; extra == "test"
19
+ Dynamic: license-file
20
+
21
+ # adambridge
22
+
23
+ AdamW for PyTorch with the optimizer state offloaded to host RAM and updated by
24
+ fused SIMD kernels on the CPU. It overlaps those updates with the GPU backward
25
+ pass, layer by layer. It implements the *OptiCompute-Bridge* design: the GPU
26
+ keeps only the parameters, while FP32 master weights and both Adam moments
27
+ live on the (NUMA-local) host.
28
+
29
+ ```python
30
+ import adambridge
31
+
32
+ opt = adambridge.AdamBridge(model.parameters(), lr=1e-4, weight_decay=0.01,
33
+ precision="bf16_moments") # 'fp32' | 'bf16' | 'fp8'
34
+ opt.attach_hooks(model) # layer-wise async updates
35
+
36
+ for x, y in loader:
37
+ loss = loss_fn(model(x), y)
38
+ loss.backward() # each layer is offloaded + updated as soon as its grad is ready
39
+ opt.step_sync() # wait; the next forward pass sees the new weights
40
+ ```
41
+
42
+ Without `attach_hooks`, `AdamBridge` is a drop-in optimizer (`backward(); step(); zero_grad()`),
43
+ and works with LR schedulers and `clip_grad_norm_`. `adambridge.OptiComputeAdamW` is an alias.
44
+
45
+ ## Measured results
46
+
47
+ All numbers in this section come from two `adambridge-lab` reports generated on 2026-10-28
48
+ (`adambridge-lab/reports/20261028-224442-*`). Test machine: a laptop with an NVIDIA GeForce
49
+ RTX 5090 Laptop GPU (24 GiB VRAM), Intel Core Ultra 9 290HX Plus (24 threads, AVX2), 64 GiB RAM,
50
+ Windows 11, Python 3.14.7, PyTorch 2.14.1 + CUDA 13.2, adambridge 0.1.0 (native/avx2 backend).
51
+ Compared libraries: bitsandbytes 0.50.2, torchao 0.18.0; DeepSpeed 0.19.8 (CPU kernel only,
52
+ under WSL, because it is not installed on Windows).
53
+
54
+ ### Fine-tuning a real LLM
55
+
56
+ Qwen2.5-0.5B (494M parameters) fine-tuned on WikiText-2: 200 steps of 8 × 512 tokens,
57
+ peak learning rate 2e-5 with warm-up and cosine decay. Every configuration starts from
58
+ the same weights, sees the same batches in the same order, and runs in a fresh process
59
+ (the *LLM fine-tuning* experiment in `adambridge-lab`). Validation loss is measured on the
60
+ whole WikiText-2 validation split (start: 2.868).
61
+
62
+ | configuration | final val. loss | Δ vs reference | step | peak GPU | host RAM† |
63
+ |---|---:|---:|---:|---:|---:|
64
+ | PyTorch AdamW, FP32 weights + autocast (**reference**) | 2.6402 | | 292 ms | 19.6 GiB | |
65
+ | PyTorch AdamW, BF16 weights + FP32 master, all on GPU | 2.6404 | +0.0002 | 281 ms | 18.8 GiB | <0.1 GiB |
66
+ | **adambridge, FP32 moments** | 2.6409 | +0.0008 | 395 ms | 13.2 GiB | +7.4 GiB |
67
+ | **adambridge, BF16 moments** | 2.6405 | +0.0003 | 317 ms | 13.2 GiB | +5.6 GiB |
68
+ | **adambridge, FP8 moments** | 2.6409 | +0.0007 | 305 ms | 13.2 GiB | +4.7 GiB |
69
+ | bitsandbytes AdamW8bit, FP32 weights | 2.6433 | +0.0031 | 312 ms | 16.8 GiB | <0.1 GiB |
70
+ | bitsandbytes AdamW8bit, BF16 weights | 2.6557 | +0.0156 | 298 ms | 14.2 GiB | <0.1 GiB |
71
+ | bitsandbytes PagedAdamW8bit, BF16 weights | 2.6549 | +0.0147 | 306 ms | 13.3 GiB | <0.1 GiB |
72
+ | torchao CPUOffloadOptimizer, FP32 weights | 2.6401 | −0.0001 | 525 ms | 15.9 GiB | +10.6 GiB |
73
+ | torchao CPUOffloadOptimizer, BF16 weights | 2.6526 | +0.0124 | 341 ms | 13.2 GiB | +5.3 GiB |
74
+ | PyTorch AdamW, BF16 weights only | 2.6526 | +0.0124 | 266 ms | 15.1 GiB | <0.1 GiB |
75
+
76
+ † growth of the process's resident memory beyond the all-GPU reference's.
77
+
78
+ * **Noise.** Re-running the reference with two other data orders moved its final loss by
79
+ up to 0.0017, so differences below 0.002 are noise. All three adambridge precisions are
80
+ inside that band, and so is the same algorithm run entirely on the GPU: offloading the
81
+ optimizer costs no quality.
82
+ * **Why the BF16-only configurations fall behind.** An AdamW update at this learning rate is
83
+ smaller than half the BF16 spacing of most weights, so without an FP32 copy it is rounded
84
+ away: only 18% of their weights changed (at BF16 resolution) vs 84% for the reference.
85
+ adambridge keeps BF16 weights on the GPU but the FP32 master on the host.
86
+ * **Memory.** adambridge needs 32% less GPU memory than the reference, the least of any
87
+ configuration at reference quality, and 2.7 GiB less than torchao's offload at the same quality.
88
+ * **Speed.** With BF16 or FP8 moments adambridge is 5–9% slower than the all-GPU reference
89
+ (35% with FP32 moments) and needs 40% less time per step than torchao's offload at the
90
+ same quality (25% less with FP32 moments). The GPU waits once per step for the update of
91
+ the last gradient of the backward pass. This laptop's GPU also drops its clocks whenever it
92
+ idles: a forward+backward pass that takes 251 ms back to back takes 22% longer after a 20 ms
93
+ pause and 33% longer after a 50 ms one, which every CPU-offload optimizer pays.
94
+ * **Host memory.** adambridge's host footprint is its FP32 master, the moments and one gradient and
95
+ one write-back buffer per parameter: with FP8 moments, less than torchao's BF16 offload,
96
+ which keeps no FP32 master.
97
+
98
+ ### Fine-tuning a small LLM (quick preset)
99
+
100
+ SmolLM2-135M fine-tuned on WikiText-2: 60 steps of 8 × 256 tokens, same protocol as above
101
+ (start: 3.306). The report labels these quick-preset numbers as indicative only.
102
+
103
+ | configuration | final val. loss | Δ vs reference | step | peak GPU | host RAM† |
104
+ |---|---:|---:|---:|---:|---:|
105
+ | PyTorch AdamW, FP32 weights + autocast (**reference**) | 3.1245 | | 94 ms | 4.74 GiB | |
106
+ | PyTorch AdamW, BF16 weights + FP32 master, all on GPU | 3.1260 | +0.0015 | 89 ms | 4.38 GiB | <0.1 GiB |
107
+ | **adambridge, FP32 moments** | 3.1259 | +0.0014 | 115 ms | 2.86 GiB | +2.1 GiB |
108
+ | **adambridge, BF16 moments** | 3.1258 | +0.0013 | 106 ms | 2.86 GiB | +1.6 GiB |
109
+ | **adambridge, FP8 moments** | 3.1232 | −0.0013 | 105 ms | 2.86 GiB | +1.4 GiB |
110
+ | bitsandbytes AdamW8bit, FP32 weights | 3.1246 | +0.0001 | 109 ms | 3.98 GiB | <0.1 GiB |
111
+ | bitsandbytes AdamW8bit, BF16 weights | 3.2867 | +0.1622 | 99 ms | 3.12 GiB | <0.1 GiB |
112
+ | bitsandbytes PagedAdamW8bit, BF16 weights | 3.2867 | +0.1622 | 102 ms | 2.87 GiB | <0.1 GiB |
113
+ | torchao CPUOffloadOptimizer, FP32 weights | 3.1246 | +0.0001 | 157 ms | 3.71 GiB | +1.9 GiB |
114
+ | torchao CPUOffloadOptimizer, BF16 weights | 3.2867 | +0.1622 | 132 ms | 2.86 GiB | +1.1 GiB |
115
+ | PyTorch AdamW, BF16 weights only | 3.2866 | +0.1621 | 83 ms | 3.37 GiB | <0.1 GiB |
116
+
117
+ The reference's own spread across data orders was 0.0014, so ties are called within 0.002.
118
+ adambridge uses 40% less GPU memory than the reference at the same quality. The BF16-only
119
+ configurations kept only 10–11% of the reference's loss reduction: 2% of their weights
120
+ changed at BF16 resolution, vs 27% for the reference. This model showed no measurable GPU
121
+ pause penalty (±0% after 20 ms, +2% after 50 ms).
122
+
123
+ ### Training step, speed and GPU memory
124
+
125
+ A 67M-parameter model (8 blocks, width 1024), 4,096 tokens per step, median of the timed
126
+ steps. Except the all-GPU baseline, every configuration keeps BF16 weights on the GPU.
127
+
128
+ | configuration | step | peak GPU | optimizer state |
129
+ |---|---:|---:|---|
130
+ | forward + backward only (no optimizer) | 30.2 ms | 0.891 GiB | none |
131
+ | `torch.optim.AdamW` fused, on GPU (FP32 + autocast) | 35.0 ms | 1.71 GiB | FP32 weights + FP32 m, v on GPU |
132
+ | bitsandbytes AdamW8bit | 36.5 ms | 1.02 GiB | 8-bit m, v on GPU, no FP32 master |
133
+ | bitsandbytes PagedAdamW8bit | 37.1 ms | 0.893 GiB | 8-bit m, v in unified memory, no FP32 master |
134
+ | torchao CPUOffloadOptimizer | 36.1 ms | 0.891 GiB | BF16 copy + BF16 m, v on CPU, no FP32 master |
135
+ | **adambridge async, FP32 moments** | 40.6 ms | 0.891 GiB | FP32 master + FP32 m, v on CPU |
136
+ | **adambridge async, BF16 moments** | 36.6 ms | 0.891 GiB | FP32 master + BF16 m, v on CPU |
137
+ | **adambridge async, FP8 moments** | 36.1 ms | 0.891 GiB | FP32 master + FP8 m, v on CPU |
138
+ | adambridge sync (`step()`), FP32 / BF16 / FP8 moments | 60.8 / 54.0 / 51.0 ms | 0.891 GiB | as above |
139
+
140
+ With FP8 moments adambridge is 3% slower than the all-GPU AdamW and uses 52% of its GPU memory.
141
+ The asynchronous mode (`attach_hooks`) takes 29–33% less time per step than synchronous
142
+ `step()` here.
143
+
144
+ ### Host kernel
145
+
146
+ 8M parameters, 24 threads (`benchmarks/bench_kernels.py --numel 8M`). At this size part of
147
+ the data stays in the CPU caches, so these times are optimistic.
148
+
149
+ | implementation | Windows ms/step | Windows GB/s | WSL ms/step | WSL GB/s |
150
+ |---|---:|---:|---:|---:|
151
+ | `torch.optim.AdamW` (foreach, CPU) | 5.83 | 38 | 7.99 | 28 |
152
+ | `torch.optim.AdamW(fused=True)` (CPU) | 2.31 | 97 | 1.98 | 113 |
153
+ | DeepSpeed CPUAdam | – | – | 2.22 | 101 |
154
+ | adambridge native, FP32 moments | 1.83 | 123 | 2.13 | 105 |
155
+ | adambridge native, FP32 moments, BF16 gradient in + BF16 weights out | 1.92 | 116 | 2.43 | 92 |
156
+ | adambridge native, BF16 moments (same I/O) | 1.13 | 141 | 1.68 | 95 |
157
+ | adambridge native, FP8 moments (same I/O) | 1.80 | 72 | 3.19 | 40 |
158
+ | adambridge PyTorch fallback, FP32 / BF16 / FP8 moments | 4.48 / 7.20 / 10.55 | | 94.57 / 13.38 / 16.77 | |
159
+
160
+ GB/s counts the minimum bytes each variant must move. The fastest adambridge variant (BF16
161
+ moments) is 2.0× faster than PyTorch's fused CPU AdamW on Windows and 1.18× under WSL.
162
+ With FP32 moments adambridge is 1.26× faster on Windows and slightly slower under WSL
163
+ (2.13 vs 1.98 ms). FP8 moments trade kernel speed for host memory; under WSL they are the slowest
164
+ native variant.
165
+
166
+ ## Install
167
+
168
+ ```bash
169
+ pip install . # or: uv pip install . / uv add ./adambridge
170
+ pip install ".[compiler]" # also installs ziglang, a C compiler for machines without one
171
+ python -m adambridge build # optional: compile the native kernels now
172
+ python -m adambridge info # shows the ISA, NUMA nodes and L2 size
173
+ ```
174
+
175
+ adambridge is a pure-Python wheel (`py3-none-any`) that carries its C source, so the same
176
+ artifact installs everywhere.
177
+
178
+ **CUDA torch:** adambridge only declares `torch>=2.1`. On Windows, and for specific CUDA
179
+ versions, PyPI's `torch` is CPU-only, so a clean `pip`/`uv` install pulls the CPU build.
180
+ Install torch from the PyTorch index first (`pip install torch --index-url
181
+ https://download.pytorch.org/whl/cu130`). With uv, pin it in your project instead:
182
+
183
+ ```toml
184
+ [tool.uv.sources]
185
+ torch = { index = "pytorch-cuda" }
186
+
187
+ [[tool.uv.index]]
188
+ name = "pytorch-cuda"
189
+ url = "https://download.pytorch.org/whl/cu130" # pick your CUDA version
190
+ explicit = true
191
+ ```
192
+
193
+ The native kernel is plain C, loaded through `ctypes`, and compiled on first use into
194
+ `~/.cache/adambridge` (override with `ADAMBRIDGE_CACHE_DIR`). The build tries `$ADAMBRIDGE_CC`, then
195
+ `cc`, `gcc`, `clang`, then `python -m ziglang cc` (`pip install ziglang` gives Windows
196
+ a compiler), then MSVC `cl`. If none works, adambridge falls back to the PyTorch kernels,
197
+ which support everything but are slower. Set `ADAMBRIDGE_DISABLE_NATIVE=1` to force the fallback.
198
+
199
+ ## How it works
200
+
201
+ ```
202
+ autograd thread D2H stream worker thread (per GPU) H2D stream
203
+ grad of layer L ready
204
+ record event ──────► wait, copy grad
205
+ to pinned host ───► wait copy, fused AdamW on
206
+ NUMA-pinned thread pool ─────► copy weights
207
+ backward continues for layer L-1 ... back to GPU
208
+ ```
209
+
210
+ `step_sync()` waits for the host work. It then makes the current CUDA stream wait on the
211
+ H2D stream, so no device-wide synchronization is needed.
212
+
213
+ * **Scheduling.** Autograd's CPU side runs ahead of the GPU, so a parameter's hook fires
214
+ long before the GPU has produced its gradient. The worker updates, in one native call,
215
+ every gradient whose copy has already landed (copies complete in order on one stream),
216
+ so the host update stays right behind the GPU's backward pass. Under load the batches
217
+ grow on their own.
218
+ * **Large gradients are chunked.** Gradients above 16.8M elements are copied, updated and
219
+ copied back in chunks, so the three overlap. This matters most for the last gradient of
220
+ the backward pass. In a language model that is the embedding, which the next forward pass
221
+ needs first, so the GPU waits on exactly this tail. Chunks draw the same rounding bits as a
222
+ whole-tensor update.
223
+ * **Small parameters are grouped.** Parameters below `small_param_threshold` (65,536 elements:
224
+ norms, biases) get no per-tensor hook; at `step_sync()` they move as one buffer each way.
225
+ * **Exact-size pinned buffers.** PyTorch's pinned allocator rounds every buffer up to a power
226
+ of two, so a 272 MB gradient buffer locks 512 MB. adambridge registers ordinary allocations of 1 MiB
227
+ or more with CUDA instead, which locks exactly their size.
228
+ * **Fused kernel** (`adambridge/csrc/adambridge_kernels.c`): one pass reads p, g, m and v and writes
229
+ p, m, v and the low-precision copy for the GPU. ISA is chosen at runtime: AVX-512F,
230
+ AVX2+FMA, NEON or scalar. The arithmetic is exactly `torch.optim.AdamW`'s.
231
+ * **Moment storage** (`precision=`):
232
+
233
+ | precision | m | v | host bytes/param | kernel |
234
+ |---|---|---|---:|---|
235
+ | `fp32` | FP32 | FP32 | 12 | native |
236
+ | `bf16` | BF16 | BF16 | 8 | native |
237
+ | `fp8` | E4M3, per-128 scale | E5M2 of `sqrt(v)`, per-128 scale | 6.06 | native |
238
+
239
+ Plus the transfer buffers: one gradient and one write-back buffer per parameter, in its dtype.
240
+ * **NUMA**: each GPU's state is allocated by, and updated on, threads pinned to the CPUs
241
+ of the NUMA node that the GPU's PCIe slot hangs off (read from Linux sysfs). This uses
242
+ first-touch placement, so no libnuma is needed. On other platforms pinning is a no-op.
243
+ * **Auto-tuning** (`autotune=True` or `AutoTuneConfig(...)`):
244
+ * It benchmarks thread counts for the native kernel.
245
+ * When host update time exceeds GPU backward time, it steps moment precision down a level.
246
+ * It keeps a downgrade only if host time actually falls. Floor: `min_precision="bf16"` by default.
247
+
248
+ ### Where this deviates from the design document, and why
249
+
250
+ 1. **Stochastic rounding for BF16/FP8 moments.** With round-to-nearest and β₂ = 0.999, the
251
+ per-step change in `v` is smaller than half a BF16 ulp, so `v` freezes.
252
+ `test_ema_stalls_without_stochastic_rounding` shows it sticking at its initial value.
253
+ adambridge rounds stochastically using a counter-based hash. The native and PyTorch kernels
254
+ use the same hash, so they make the same rounding decisions, and results do not depend
255
+ on the thread split or on chunking.
256
+ 2. **FP8 stores `sqrt(v)`, not `v`.** Block-scaled E5M2 `v` flushes to zero for any element
257
+ whose gradient is about 2¹⁶× below its block's maximum, while `m` stays non-zero. The
258
+ step then becomes `m/eps` and explodes. Storing the square root doubles the usable range,
259
+ at the cost of a ~1–2% upward bias in `v`.
260
+ 3. **BF16 write-back rounds to nearest-even** instead of truncating the top 16 bits.
261
+ Truncation biases every weight toward zero.
262
+ 4. **The kernel handles tails.** The spec kernel reads and writes past the end when
263
+ `n % 16 != 0`.
264
+ 5. **Master weights are created lazily** on the first update, not at construction. Loading
265
+ pretrained weights after building the optimizer would otherwise be silently reverted.
266
+ 6. **SPSC queues are Python `SimpleQueue`s.** There is one producer side (autograd hooks) and
267
+ one consumer thread per device. Lock contention isn't the bottleneck: kernels run with the
268
+ GIL released.
269
+
270
+ ## Parameters
271
+
272
+ ```python
273
+ adambridge.AdamBridge(
274
+ params,
275
+ lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=1e-2,
276
+ *, # everything below is keyword-only
277
+ precision="fp32", stochastic_rounding=True, backend="auto",
278
+ numa_aware=True, num_threads=None, chunk_size=None,
279
+ release_grads=True, overlap_writeback=True,
280
+ autotune=False, seed=0, small_param_threshold=65536,
281
+ )
282
+ ```
283
+
284
+ ### AdamW hyperparameters
285
+
286
+ These behave exactly as in `torch.optim.AdamW`. They can differ between parameter groups
287
+ (pass a list of dicts as `params`) and can be changed by LR schedulers.
288
+
289
+ | parameter | default | accepted values | meaning and use |
290
+ |---|---|---|---|
291
+ | `params` | required | iterable of tensors, or of dicts (parameter groups) | The parameters to optimize. Use groups to give, say, biases and norms `weight_decay=0`. Sparse parameters are rejected. |
292
+ | `lr` | `1e-3` | float `>= 0` | Learning rate: the size of each update. Fine-tuning typically uses `1e-5`–`1e-4`. |
293
+ | `betas` | `(0.9, 0.999)` | two floats, each in `[0, 1)` | Decay rates of the running averages of the gradient (`m`) and of its square (`v`). Higher values average over more steps. |
294
+ | `eps` | `1e-8` | float `>= 0` | Added to `sqrt(v)` in the denominator so the update never divides by zero. |
295
+ | `weight_decay` | `1e-2` | float `>= 0` | Decoupled weight decay: each step every weight is shrunk by `lr * weight_decay * w`. `0` disables it. |
296
+
297
+ ### Memory and precision
298
+
299
+ | parameter | default | accepted values | meaning and use |
300
+ |---|---|---|---|
301
+ | `precision` | `"fp32"` | `"fp32"` (alias `"float32"`), `"bf16"` (aliases `"bf16_moments"`, `"bfloat16"`), `"fp8"` (alias `"fp8_moments"`); case-insensitive | How the two Adam moments are stored in host RAM: 12, 8 or ~6.06 host bytes per parameter including the FP32 master (see the table in *How it works*). Lower precision uses less RAM and is faster; in the measurements above all three reached reference quality. The FP32 master weights are kept in every mode. Can be changed later with `set_precision()`. |
302
+ | `stochastic_rounding` | `True` | `True`, `False` | Rounds BF16/FP8 moments up or down at random, in proportion to the remainder, so tiny per-step changes accumulate on average. Has no effect with `precision="fp32"`. Keep it on: without it `v` stops changing once `beta2` is close to 1 (see *Where this deviates…*, item 1). |
303
+ | `seed` | `0` | int | Base seed for stochastic rounding. The same seed gives bit-identical results regardless of thread count or chunking. |
304
+
305
+ ### Hardware and threading
306
+
307
+ | parameter | default | accepted values | meaning and use |
308
+ |---|---|---|---|
309
+ | `backend` | `"auto"` | `"auto"`, `"native"`, `"torch"` | Which update kernel runs on the CPU. `"auto"` uses the compiled SIMD kernel when it can be built and otherwise the PyTorch fallback. `"native"` raises an error if the kernel isn't available. `"torch"` always uses the slower PyTorch kernels, which is useful for debugging. Check the result with `opt.backend`. |
310
+ | `numa_aware` | `True` | `True`, `False` | On multi-socket Linux machines, keeps each GPU's optimizer state in the RAM attached to the CPU closest to that GPU and runs its updates on that CPU's cores. No effect on Windows, macOS, or single-socket machines. |
311
+ | `num_threads` | `None` | `None` or int `>= 1` | CPU threads per NUMA node for the update. `None` uses all CPUs of the node minus two (left for the training loop), capped at 32. The update is limited by memory bandwidth, so more threads stop helping well before all cores are busy; `tune_threads()` or `autotune` finds the best count. |
312
+ | `chunk_size` | `None` | `None` or a positive multiple of 128 | Elements processed per pass by the **PyTorch fallback** kernel. `None` derives it from the CPU's L2 cache size (between 262,144 and 4,194,304). Ignored by the native kernel. |
313
+
314
+ ### Asynchronous mode (`attach_hooks`)
315
+
316
+ | parameter | default | accepted values | meaning and use |
317
+ |---|---|---|---|
318
+ | `release_grads` | `True` | `True`, `False` | Frees each gradient from GPU memory as soon as it has been copied to the host, so `p.grad` is `None` after `backward()`. Set `False` if your code reads `p.grad` after backward (for logging, say), at the cost of keeping all gradients on the GPU. |
319
+ | `overlap_writeback` | `True` | `True`, `False` | Copies each updated weight back to the GPU as soon as it is ready, overlapping with the rest of backward. `False` defers all copies to `step_sync()`. Only needed if something reads a parameter during backward after that parameter's gradient is complete (only possible with `.detach()` tricks). |
320
+ | `small_param_threshold` | `65536` | int `>= 0` | CUDA parameters with fewer elements than this (norms, biases) get no per-tensor hook and are updated together at `step_sync()`, with one transfer each way. Their update takes microseconds, while a hook costs tens of microseconds of Python. `0` hooks every parameter. |
321
+ | `autotune` | `False` | `False`, `True`, or an `AutoTuneConfig` | Tunes the thread count and moment precision while training (see below). `True` uses `AutoTuneConfig()` defaults. Decisions are made from `step_sync()` timings and recorded in `opt.autotune_log`. |
322
+
323
+ ### Auto-tuning (`adambridge.autotune.AutoTuneConfig`)
324
+
325
+ The tuner first benchmarks thread counts once. Then, if the CPU update takes longer than the
326
+ GPU's backward pass, it steps the moment precision down one level (`fp32` → `bf16` → `fp8`).
327
+ It keeps the change only if the update actually got faster, and stops at the first decision.
328
+
329
+ ```python
330
+ from adambridge.autotune import AutoTuneConfig
331
+ opt = adambridge.AdamBridge(model.parameters(), autotune=AutoTuneConfig(min_precision="fp8"))
332
+ ```
333
+
334
+ | field | default | accepted values | meaning and use |
335
+ |---|---|---|---|
336
+ | `warmup_steps` | `3` | int `>= 0` | Steps ignored at start-up and after each precision change, while caches and allocations settle. |
337
+ | `window` | `5` | int `>= 1` | Steps measured (median) before each decision. |
338
+ | `threshold` | `1.0` | float `> 0` | The host counts as the bottleneck when `cpu_update > threshold * gpu_backward`. Lower it to downgrade sooner. |
339
+ | `min_precision` | `"bf16"` | any `precision` value | Lowest precision the tuner may pick. The default never selects FP8; set `"fp8"` to allow it, or `"fp32"` to disable precision tuning. |
340
+ | `min_gain` | `0.05` | float in `[0, 1)` | A downgrade is kept only if host update time drops by at least this fraction (5%); otherwise it is reverted. |
341
+ | `tune_threads` | `True` | `True`, `False` | Benchmark thread counts on the first tuned step and keep the fastest; within 3% of the best, the fewest threads win. Only applies to the native kernel. |
342
+
343
+ ### Methods
344
+
345
+ | method | use |
346
+ |---|---|
347
+ | `step(closure=None)` | Synchronous update, as with any PyTorch optimizer: copy gradients to the host, update, copy weights back. Works with gradient clipping and LR schedulers. |
348
+ | `zero_grad()` | As in PyTorch. |
349
+ | `attach_hooks(model=None)` | Switches to asynchronous mode: each parameter is updated as soon as its gradient is ready during `backward()`. With `model`, only that model's parameters are hooked. Returns the optimizer. |
350
+ | `detach_hooks()` | Back to synchronous mode. |
351
+ | `step_sync()` | In asynchronous mode, call after `backward()` instead of `step()`. Updates the small parameters, waits for every queued update, and makes the next GPU work wait for the new weights. Returns `StepStats`. |
352
+ | `no_sync()` | Context manager for gradient accumulation: run all but the last micro-batch inside `with opt.no_sync():`. Without it, a second gradient before `step_sync()` raises an error. |
353
+ | `set_precision(precision)` | Re-encodes all moments in another precision between steps. |
354
+ | `tune_threads(numel=4194304)` | Benchmarks the native kernel and sets the fastest thread count per device. Returns `{device: {threads: seconds}}`. |
355
+ | `state_dict()` / `load_state_dict(sd)` | Checkpointing. Moments are saved in their stored precision. Loading also accepts `torch.optim.AdamW` checkpoints and converts precision when needed. |
356
+ | `memory_report()` | Host bytes held, by category: `master`, `moments`, `staging` (transfer buffers) and `total`. |
357
+ | `expected_bytes_per_param()` | Host bytes per parameter for master + moments at the current precision (12, 8 or ~6.06). |
358
+ | `master_params()` | The FP32 master copies (`None` for a parameter until its first update). |
359
+ | `close()` | Stops the worker threads and releases pinned memory. Runs automatically when the optimizer is garbage-collected. |
360
+
361
+ Read-only attributes: `opt.backend` (`"native/avx2"`, `"native/avx512"`, `"native/neon"`,
362
+ `"native/scalar"` or `"torch"`), `opt.precision`, `opt.autotune_log` (list of the tuner's
363
+ decisions) and `opt.last_step_stats`.
364
+
365
+ `step_sync()` and `opt.last_step_stats` return a `StepStats` with these fields (seconds):
366
+
367
+ | field | meaning |
368
+ |---|---|
369
+ | `num_updates` | Parameters updated this step (a chunked update counts once). |
370
+ | `gpu_backward` | GPU time from the first to the last gradient being ready; `None` without CUDA hooks. |
371
+ | `cpu_update` | CPU kernel time of the busiest device worker. |
372
+ | `stall` | How long `step_sync()` blocked the training loop, including waiting for the GPU to finish backward. |
373
+ | `per_device_cpu` | `cpu_update` broken down by device. |
374
+
375
+ ### Environment variables
376
+
377
+ | variable | default | meaning and use |
378
+ |---|---|---|
379
+ | `ADAMBRIDGE_CACHE_DIR` | `~/.cache/adambridge` | Where the compiled native kernel is stored. |
380
+ | `ADAMBRIDGE_CC` | unset | Compiler command to try first, e.g. `gcc`, `clang -march=native` or `cl`. |
381
+ | `ADAMBRIDGE_DISABLE_NATIVE` | unset | Any value except `0` forces the PyTorch fallback kernels. |
382
+ | `ADAMBRIDGE_SPIN` | `4000` | How long the update threads busy-wait (in CPU pause instructions) for the next job before sleeping. Higher reacts faster between updates but burns CPU; `0` sleeps immediately. |
383
+
384
+ ### Command line
385
+
386
+ | command | use |
387
+ |---|---|
388
+ | `python -m adambridge build [--force] [--verbose]` | Compile the native kernel now instead of on first use. `--force` rebuilds; `--verbose` prints the compiler output. |
389
+ | `python -m adambridge info` | Shows the kernel library path, SIMD level, NUMA nodes and L2 cache size. |
390
+
391
+ ### Things to know
392
+
393
+ * Global gradient clipping (`clip_grad_norm_`) is impossible in asynchronous mode, because
394
+ the first layers update before the last gradients exist. Use synchronous `step()` if you
395
+ need it.
396
+ * LR schedulers work in both modes: they change `lr` in the parameter groups, which is read
397
+ at each update.
398
+ * Master weights are created on a parameter's first update, so loading pretrained weights
399
+ after building the optimizer is safe.
400
+
401
+ ## Testing
402
+
403
+ ```bash
404
+ pytest # 83 tests; CUDA tests run when a GPU is present
405
+ cc -O2 -pthread -o selftest tests/native/selftest.c -lm && ./selftest # includes the kernel source
406
+ ```
407
+
408
+ Results from the 2026-10-28 report:
409
+
410
+ | runtime | passed | failed | skipped | native C self-test |
411
+ |---|---:|---:|---:|---|
412
+ | Windows, CUDA (kernel built with `python -m ziglang cc`) | 82 | 0 | 1 | passed, 216 cases, avx2 |
413
+ | WSL Linux, CPU only (kernel built with `/usr/bin/cc`) | 61 | 0 | 0 | passed, 216 cases, avx2 |
414
+
415
+ What the tests check:
416
+
417
+ * adambridge's updates against `torch.optim.AdamW` on CPU and GPU (FP32 tolerance: rtol 1e-6,
418
+ atol 1e-7), in sync and async modes.
419
+ * Parameter groups, schedulers, weight tying, gradient accumulation, gradient clipping, BF16
420
+ params, checkpoint resume, chunked updates, exact-size pinned buffers, and the auto-tuner.
421
+ * The C self-test compares the SIMD paths against scalar code and checks the FP8 codec and
422
+ thread-count and chunking invariance.
423
+ * `adambridge-lab` runs all of this plus the benchmarks and the LLM fine-tuning comparison from
424
+ one page, and writes the reports.
425
+
426
+ ## Limitations / not yet verified
427
+
428
+ * The **AVX-512 and NEON paths compile but were not executed**: the test machine is AVX2.
429
+ Run `selftest` on such hardware before relying on them.
430
+ * **Multi-socket NUMA placement** is covered by unit tests on a simulated sysfs, not
431
+ measured on a real two-socket server.
432
+ * The GPU waits once per step for the update of the last gradient of the backward pass (for
433
+ language models, the embedding). Its cost grows with that tensor's size and the bytes per
434
+ parameter of the moments, and on GPUs that drop their clocks when idle, the next passes
435
+ run slower too.
436
+ * Not covered yet: FP16 gradients with `GradScaler`, and integration with DDP or FSDP
437
+ sharding (single-process, one or more GPUs).
438
+
439
+ ## License
440
+
441
+ Copyright 2026 John Anish G. Licensed under the [Apache License, Version 2.0](LICENSE).