trainstream 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.
- trainstream-0.1.0/LICENSE +202 -0
- trainstream-0.1.0/MANIFEST.in +8 -0
- trainstream-0.1.0/NOTICE +4 -0
- trainstream-0.1.0/PKG-INFO +119 -0
- trainstream-0.1.0/README.md +81 -0
- trainstream-0.1.0/build.bat +23 -0
- trainstream-0.1.0/csrc/bindings.cpp +139 -0
- trainstream-0.1.0/csrc/kernels.h +49 -0
- trainstream-0.1.0/csrc/memory_pinner.cpp +680 -0
- trainstream-0.1.0/csrc/offload_adamw.cpp +712 -0
- trainstream-0.1.0/csrc/offload_adamw.h +154 -0
- trainstream-0.1.0/csrc/offload_adamw_kernel.cu +183 -0
- trainstream-0.1.0/csrc/trainstream.h +132 -0
- trainstream-0.1.0/pyproject.toml +6 -0
- trainstream-0.1.0/setup.cfg +4 -0
- trainstream-0.1.0/setup.py +106 -0
- trainstream-0.1.0/tests/test_huggingface.py +176 -0
- trainstream-0.1.0/tests/test_offload.py +313 -0
- trainstream-0.1.0/tests/test_optimizer.py +222 -0
- trainstream-0.1.0/trainstream/__init__.py +55 -0
- trainstream-0.1.0/trainstream/hooks.py +547 -0
- trainstream-0.1.0/trainstream/integrations/__init__.py +7 -0
- trainstream-0.1.0/trainstream/integrations/huggingface.py +211 -0
- trainstream-0.1.0/trainstream/optimizer.py +333 -0
- trainstream-0.1.0/trainstream/profiler.py +166 -0
- trainstream-0.1.0/trainstream/wrapper.py +191 -0
- trainstream-0.1.0/trainstream.egg-info/PKG-INFO +119 -0
- trainstream-0.1.0/trainstream.egg-info/SOURCES.txt +30 -0
- trainstream-0.1.0/trainstream.egg-info/dependency_links.txt +1 -0
- trainstream-0.1.0/trainstream.egg-info/not-zip-safe +1 -0
- trainstream-0.1.0/trainstream.egg-info/requires.txt +5 -0
- trainstream-0.1.0/trainstream.egg-info/top_level.txt +1 -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 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.
|
trainstream-0.1.0/NOTICE
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: trainstream
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-dependency PCIe offloading engine for PyTorch training (optimizer, gradients, activations).
|
|
5
|
+
Home-page: https://github.com/johnanishg/TrainStream
|
|
6
|
+
Author: John Anish G
|
|
7
|
+
License: Apache-2.0
|
|
8
|
+
Project-URL: Source, https://github.com/johnanishg/TrainStream
|
|
9
|
+
Project-URL: Issues, https://github.com/johnanishg/TrainStream/issues
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: C++
|
|
15
|
+
Classifier: Environment :: GPU :: NVIDIA CUDA
|
|
16
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
17
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
License-File: NOTICE
|
|
23
|
+
Provides-Extra: hf
|
|
24
|
+
Requires-Dist: transformers; extra == "hf"
|
|
25
|
+
Requires-Dist: accelerate; extra == "hf"
|
|
26
|
+
Requires-Dist: peft; extra == "hf"
|
|
27
|
+
Dynamic: author
|
|
28
|
+
Dynamic: classifier
|
|
29
|
+
Dynamic: description
|
|
30
|
+
Dynamic: description-content-type
|
|
31
|
+
Dynamic: home-page
|
|
32
|
+
Dynamic: license
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
Dynamic: project-url
|
|
35
|
+
Dynamic: provides-extra
|
|
36
|
+
Dynamic: requires-python
|
|
37
|
+
Dynamic: summary
|
|
38
|
+
|
|
39
|
+
# TrainStream
|
|
40
|
+
|
|
41
|
+
Train and fine-tune models larger than your GPU's memory by moving optimizer state, gradients and activations to system RAM over PCIe — with one line of code and no third-party dependencies.
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
import trainstream
|
|
45
|
+
model, optimizer = trainstream.wrap(model, optimizer)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
TrainStream is a C++/CUDA extension for PyTorch. It keeps only the weights in VRAM: gradients stream to pinned host memory as autograd produces them, AdamW runs on host threads while the backward pass continues, and a profiled share of activations is paged out and prefetched back block by block. Updates match `torch.optim.AdamW` (max parameter difference ≈3·10⁻⁷ after 20 steps); activation paging is bit-exact.
|
|
49
|
+
|
|
50
|
+
## Results (RTX 5090 Laptop GPU, 24 GB)
|
|
51
|
+
|
|
52
|
+
| Workload | Stock PyTorch AdamW | TrainStream |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| 1.8B-parameter GPT, fp32, batch 8×512 | 34.1 GiB peak — exceeds VRAM, driver spills to RAM, 13.7 s/step | 20.6 GiB, 1.1 s/step (13.5 GiB with all activations paged) |
|
|
55
|
+
| Qwen2.5-1.5B full fine-tune (Hugging Face Trainer) | 35.9 GiB peak (spill), 111.7 s / 10 steps | 18.7 GiB, 28.5 s / 10 steps, same losses |
|
|
56
|
+
| 85M GPT (fits either way) | 2.5 GiB, ~94k tokens/s | 1.8 GiB, ~64k tokens/s |
|
|
57
|
+
|
|
58
|
+
When a model already fits, TrainStream trades throughput for memory. Its value is training what does not fit, or freeing VRAM for larger batches. All numbers come from a single machine; see `research/research_dossier.html` for methodology and caveats.
|
|
59
|
+
|
|
60
|
+
## Requirements
|
|
61
|
+
|
|
62
|
+
- An NVIDIA GPU and a CUDA build of PyTorch
|
|
63
|
+
- The CUDA toolkit matching PyTorch's CUDA major version, and a C++ compiler (MSVC 2022+ on Windows, GCC 11+ on Linux)
|
|
64
|
+
- Tested on Windows 11, PyTorch 2.14.1+cu130, CUDA 13.4, Python 3.14. Linux builds use the same setup but are untested.
|
|
65
|
+
|
|
66
|
+
## Install
|
|
67
|
+
|
|
68
|
+
TrainStream compiles against the PyTorch you already have, so install PyTorch first and disable build isolation:
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
pip install torch --index-url https://download.pytorch.org/whl/cu130
|
|
72
|
+
pip install trainstream --no-build-isolation
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
From a checkout: `build.bat` (Windows) or `python setup.py build_ext --inplace`.
|
|
76
|
+
|
|
77
|
+
## Usage
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
import torch, trainstream
|
|
81
|
+
|
|
82
|
+
model = MyModel().cuda()
|
|
83
|
+
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
|
|
84
|
+
model, optimizer = trainstream.wrap(model, optimizer) # max_grad_norm=..., accumulation_steps=... if you use them
|
|
85
|
+
|
|
86
|
+
for x, y in loader:
|
|
87
|
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
|
88
|
+
loss = model(x.cuda(), y.cuda())
|
|
89
|
+
loss.backward()
|
|
90
|
+
optimizer.step()
|
|
91
|
+
optimizer.zero_grad()
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Hugging Face (`pip install transformers accelerate`):
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from trainstream.integrations.huggingface import TrainStreamTrainer
|
|
98
|
+
trainer = TrainStreamTrainer(model=model, args=TrainingArguments(..., bf16=True), train_dataset=ds)
|
|
99
|
+
trainer.train()
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Use `bf16=True` or fp32; fp16 with loss scaling is not supported.
|
|
103
|
+
|
|
104
|
+
## Tools in this repository
|
|
105
|
+
|
|
106
|
+
- `start_dashboard.bat` — live dashboard: one-click comparison reports (stock AdamW vs TrainStream), real-time VRAM / RAM / PCIe charts
|
|
107
|
+
- `examples/verify_ram_offload.py` — proves where training memory lives (VRAM vs system RAM) with a PASS/FAIL verdict
|
|
108
|
+
- `examples/hf_finetune.py` — fine-tune a Hugging Face model, optionally side by side with the stock Trainer
|
|
109
|
+
- `docs/index.html` — full documentation; `research/` — research dossier with all measurements
|
|
110
|
+
|
|
111
|
+
## Limitations
|
|
112
|
+
|
|
113
|
+
- Weights stay in VRAM (no parameter offloading); large-vocabulary output logits are not offloaded
|
|
114
|
+
- Single GPU per process
|
|
115
|
+
- Host AdamW speed is bounded by system RAM bandwidth
|
|
116
|
+
|
|
117
|
+
## License
|
|
118
|
+
|
|
119
|
+
Apache License 2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE). Copyright 2026 John Anish G.
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# TrainStream
|
|
2
|
+
|
|
3
|
+
Train and fine-tune models larger than your GPU's memory by moving optimizer state, gradients and activations to system RAM over PCIe — with one line of code and no third-party dependencies.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
import trainstream
|
|
7
|
+
model, optimizer = trainstream.wrap(model, optimizer)
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
TrainStream is a C++/CUDA extension for PyTorch. It keeps only the weights in VRAM: gradients stream to pinned host memory as autograd produces them, AdamW runs on host threads while the backward pass continues, and a profiled share of activations is paged out and prefetched back block by block. Updates match `torch.optim.AdamW` (max parameter difference ≈3·10⁻⁷ after 20 steps); activation paging is bit-exact.
|
|
11
|
+
|
|
12
|
+
## Results (RTX 5090 Laptop GPU, 24 GB)
|
|
13
|
+
|
|
14
|
+
| Workload | Stock PyTorch AdamW | TrainStream |
|
|
15
|
+
|---|---|---|
|
|
16
|
+
| 1.8B-parameter GPT, fp32, batch 8×512 | 34.1 GiB peak — exceeds VRAM, driver spills to RAM, 13.7 s/step | 20.6 GiB, 1.1 s/step (13.5 GiB with all activations paged) |
|
|
17
|
+
| Qwen2.5-1.5B full fine-tune (Hugging Face Trainer) | 35.9 GiB peak (spill), 111.7 s / 10 steps | 18.7 GiB, 28.5 s / 10 steps, same losses |
|
|
18
|
+
| 85M GPT (fits either way) | 2.5 GiB, ~94k tokens/s | 1.8 GiB, ~64k tokens/s |
|
|
19
|
+
|
|
20
|
+
When a model already fits, TrainStream trades throughput for memory. Its value is training what does not fit, or freeing VRAM for larger batches. All numbers come from a single machine; see `research/research_dossier.html` for methodology and caveats.
|
|
21
|
+
|
|
22
|
+
## Requirements
|
|
23
|
+
|
|
24
|
+
- An NVIDIA GPU and a CUDA build of PyTorch
|
|
25
|
+
- The CUDA toolkit matching PyTorch's CUDA major version, and a C++ compiler (MSVC 2022+ on Windows, GCC 11+ on Linux)
|
|
26
|
+
- Tested on Windows 11, PyTorch 2.14.1+cu130, CUDA 13.4, Python 3.14. Linux builds use the same setup but are untested.
|
|
27
|
+
|
|
28
|
+
## Install
|
|
29
|
+
|
|
30
|
+
TrainStream compiles against the PyTorch you already have, so install PyTorch first and disable build isolation:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install torch --index-url https://download.pytorch.org/whl/cu130
|
|
34
|
+
pip install trainstream --no-build-isolation
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
From a checkout: `build.bat` (Windows) or `python setup.py build_ext --inplace`.
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
import torch, trainstream
|
|
43
|
+
|
|
44
|
+
model = MyModel().cuda()
|
|
45
|
+
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
|
|
46
|
+
model, optimizer = trainstream.wrap(model, optimizer) # max_grad_norm=..., accumulation_steps=... if you use them
|
|
47
|
+
|
|
48
|
+
for x, y in loader:
|
|
49
|
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
|
50
|
+
loss = model(x.cuda(), y.cuda())
|
|
51
|
+
loss.backward()
|
|
52
|
+
optimizer.step()
|
|
53
|
+
optimizer.zero_grad()
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Hugging Face (`pip install transformers accelerate`):
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from trainstream.integrations.huggingface import TrainStreamTrainer
|
|
60
|
+
trainer = TrainStreamTrainer(model=model, args=TrainingArguments(..., bf16=True), train_dataset=ds)
|
|
61
|
+
trainer.train()
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Use `bf16=True` or fp32; fp16 with loss scaling is not supported.
|
|
65
|
+
|
|
66
|
+
## Tools in this repository
|
|
67
|
+
|
|
68
|
+
- `start_dashboard.bat` — live dashboard: one-click comparison reports (stock AdamW vs TrainStream), real-time VRAM / RAM / PCIe charts
|
|
69
|
+
- `examples/verify_ram_offload.py` — proves where training memory lives (VRAM vs system RAM) with a PASS/FAIL verdict
|
|
70
|
+
- `examples/hf_finetune.py` — fine-tune a Hugging Face model, optionally side by side with the stock Trainer
|
|
71
|
+
- `docs/index.html` — full documentation; `research/` — research dossier with all measurements
|
|
72
|
+
|
|
73
|
+
## Limitations
|
|
74
|
+
|
|
75
|
+
- Weights stay in VRAM (no parameter offloading); large-vocabulary output logits are not offloaded
|
|
76
|
+
- Single GPU per process
|
|
77
|
+
- Host AdamW speed is bounded by system RAM bandwidth
|
|
78
|
+
|
|
79
|
+
## License
|
|
80
|
+
|
|
81
|
+
Apache License 2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE). Copyright 2026 John Anish G.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
@echo off
|
|
2
|
+
REM Builds trainstream._C in place on Windows.
|
|
3
|
+
REM Loads the MSVC x64 toolchain and points the build at the CUDA toolkit.
|
|
4
|
+
setlocal
|
|
5
|
+
|
|
6
|
+
set "VCVARS=C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\VC\Auxiliary\Build\vcvars64.bat"
|
|
7
|
+
if not exist "%VCVARS%" (
|
|
8
|
+
for /f "usebackq delims=" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -property installationPath`) do set "VCVARS=%%i\VC\Auxiliary\Build\vcvars64.bat"
|
|
9
|
+
)
|
|
10
|
+
call "%VCVARS%" >nul || exit /b 1
|
|
11
|
+
|
|
12
|
+
if "%CUDA_HOME%"=="" (
|
|
13
|
+
for /d %%d in ("C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v*") do set "CUDA_HOME=%%d"
|
|
14
|
+
)
|
|
15
|
+
set "CUDA_PATH=%CUDA_HOME%"
|
|
16
|
+
set "PATH=%CUDA_HOME%\bin;%PATH%"
|
|
17
|
+
set DISTUTILS_USE_SDK=1
|
|
18
|
+
|
|
19
|
+
set "PY=%~dp0.venv\Scripts\python.exe"
|
|
20
|
+
if not exist "%PY%" set "PY=python"
|
|
21
|
+
|
|
22
|
+
cd /d "%~dp0"
|
|
23
|
+
"%PY%" setup.py build_ext --inplace %*
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// TrainStream — Python bindings (module: trainstream._C).
|
|
2
|
+
//
|
|
3
|
+
// Every call that can block on the GPU or on worker threads releases the GIL,
|
|
4
|
+
// so autograd's backward thread and the training thread never deadlock on it.
|
|
5
|
+
|
|
6
|
+
#include <torch/extension.h>
|
|
7
|
+
|
|
8
|
+
#include <cstdio>
|
|
9
|
+
#include <exception>
|
|
10
|
+
|
|
11
|
+
#include "offload_adamw.h"
|
|
12
|
+
#include "trainstream.h"
|
|
13
|
+
|
|
14
|
+
namespace py = pybind11;
|
|
15
|
+
using namespace trainstream;
|
|
16
|
+
|
|
17
|
+
namespace {
|
|
18
|
+
using nogil = py::call_guard<py::gil_scoped_release>;
|
|
19
|
+
|
|
20
|
+
// An exception escaping a destructor (e.g. a CUDA error surfacing inside the
|
|
21
|
+
// caching allocator's free path) calls std::terminate, and the default abort
|
|
22
|
+
// handler prints only a stack. Print the message first, then chain.
|
|
23
|
+
std::terminate_handler g_prev_terminate = nullptr;
|
|
24
|
+
void print_then_terminate() {
|
|
25
|
+
if (auto ex = std::current_exception()) {
|
|
26
|
+
try {
|
|
27
|
+
std::rethrow_exception(ex);
|
|
28
|
+
} catch (const std::exception& e) {
|
|
29
|
+
std::fprintf(stderr, "[trainstream] terminate: %s\n", e.what());
|
|
30
|
+
} catch (...) {
|
|
31
|
+
std::fprintf(stderr, "[trainstream] terminate: unknown exception\n");
|
|
32
|
+
}
|
|
33
|
+
std::fflush(stderr);
|
|
34
|
+
}
|
|
35
|
+
if (g_prev_terminate) g_prev_terminate();
|
|
36
|
+
std::abort();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
std::map<std::string, std::string> build_info() {
|
|
40
|
+
int runtime_version = 0, driver_version = 0;
|
|
41
|
+
cudaRuntimeGetVersion(&runtime_version);
|
|
42
|
+
cudaDriverGetVersion(&driver_version);
|
|
43
|
+
return {{"cuda_runtime", std::to_string(runtime_version)},
|
|
44
|
+
{"cuda_driver", std::to_string(driver_version)},
|
|
45
|
+
{"compiled_with_cuda", std::to_string(CUDART_VERSION)},
|
|
46
|
+
#ifdef _MSVC_LANG
|
|
47
|
+
{"cxx_standard", std::to_string(_MSVC_LANG)}}; // MSVC pins __cplusplus to 199711L
|
|
48
|
+
#else
|
|
49
|
+
{"cxx_standard", std::to_string(__cplusplus)}};
|
|
50
|
+
#endif
|
|
51
|
+
}
|
|
52
|
+
} // namespace
|
|
53
|
+
|
|
54
|
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
|
55
|
+
m.doc() = "TrainStream native runtime: pinned memory, DMA streams, offloaded AdamW";
|
|
56
|
+
g_prev_terminate = std::set_terminate(print_then_terminate);
|
|
57
|
+
|
|
58
|
+
m.def("build_info", &build_info);
|
|
59
|
+
m.def("now_ms", &now_ms);
|
|
60
|
+
m.def("init", [](int device) { runtime(device); }, py::arg("device") = -1);
|
|
61
|
+
m.def("is_dense", [](const at::Tensor& t) { return t.is_non_overlapping_and_dense(); },
|
|
62
|
+
"True if the tensor occupies exactly numel*itemsize contiguous bytes (any dimension order).");
|
|
63
|
+
|
|
64
|
+
// ---- events -------------------------------------------------------------
|
|
65
|
+
py::class_<Event, std::shared_ptr<Event>>(m, "Event")
|
|
66
|
+
.def(py::init([](int device, bool timing) { return make_event(resolve_device(device), timing); }),
|
|
67
|
+
py::arg("device") = -1, py::arg("timing") = false)
|
|
68
|
+
.def("record", [](Event& e) { e.record(compute_stream(e.device())); },
|
|
69
|
+
"Record on the current PyTorch compute stream.")
|
|
70
|
+
.def("query", &Event::query)
|
|
71
|
+
.def("synchronize", &Event::synchronize, nogil())
|
|
72
|
+
.def("wait", [](Event& e) { e.block(compute_stream(e.device())); },
|
|
73
|
+
"Make the current compute stream wait for this event (GPU-side, non-blocking for the host).")
|
|
74
|
+
.def("elapsed_ms", &Event::elapsed_ms, nogil())
|
|
75
|
+
.def_property_readonly("recorded", &Event::recorded)
|
|
76
|
+
.def_property_readonly("device", &Event::device);
|
|
77
|
+
m.def("record_event", &record_on_current, py::arg("device") = -1, py::arg("timing") = false);
|
|
78
|
+
|
|
79
|
+
// ---- pinned memory --------------------------------------------------------
|
|
80
|
+
m.def("pinned_empty", &pinned_empty, py::arg("sizes"), py::arg("dtype"), py::arg("tag") = "user",
|
|
81
|
+
py::arg("mapped") = false, py::arg("cached") = true);
|
|
82
|
+
m.def("pinned_stats", &pinned_stats);
|
|
83
|
+
m.def("pinned_tag_bytes", &pinned_tag_bytes);
|
|
84
|
+
m.def("pinned_log", &pinned_log, py::arg("limit") = 256);
|
|
85
|
+
m.def("pinned_empty_cache", &pinned_empty_cache, nogil());
|
|
86
|
+
m.def("pinned_set_cache_limit", &pinned_set_cache_limit);
|
|
87
|
+
|
|
88
|
+
// ---- transfers ------------------------------------------------------------
|
|
89
|
+
m.def("d2h_async", &d2h_async, py::arg("dst"), py::arg("src"));
|
|
90
|
+
m.def("h2d_async", &h2d_async, py::arg("dst"), py::arg("src"), py::arg("after") = EventPtr());
|
|
91
|
+
m.def("h2d_alloc_async", &h2d_alloc_async, py::arg("src"), py::arg("after") = EventPtr(),
|
|
92
|
+
py::arg("device") = -1, py::arg("sizes") = std::vector<int64_t>{},
|
|
93
|
+
py::arg("strides") = std::vector<int64_t>{});
|
|
94
|
+
m.def("transfer_stats", &transfer_stats, py::arg("device") = -1);
|
|
95
|
+
m.def("synchronize_streams", [](int device) {
|
|
96
|
+
Runtime& rt = runtime(device);
|
|
97
|
+
TS_CUDA_CHECK(cudaStreamSynchronize(rt.d2h));
|
|
98
|
+
TS_CUDA_CHECK(cudaStreamSynchronize(rt.h2d));
|
|
99
|
+
TS_CUDA_CHECK(cudaStreamSynchronize(rt.upd));
|
|
100
|
+
}, py::arg("device") = -1, nogil());
|
|
101
|
+
|
|
102
|
+
// ---- benchmarks -----------------------------------------------------------
|
|
103
|
+
m.def("benchmark_pcie", &benchmark_pcie, py::arg("device") = -1, py::arg("bytes") = 256LL << 20,
|
|
104
|
+
py::arg("iters") = 10, nogil());
|
|
105
|
+
m.def("benchmark_matmul", &benchmark_matmul, py::arg("device") = -1, py::arg("n") = 4096,
|
|
106
|
+
py::arg("dtype") = at::kBFloat16, py::arg("iters") = 20, nogil());
|
|
107
|
+
m.def("benchmark_cpu_adamw", &benchmark_cpu_adamw, py::arg("numel") = 1 << 24, py::arg("threads") = 0,
|
|
108
|
+
nogil());
|
|
109
|
+
m.def("benchmark_zero_copy_adamw", &benchmark_zero_copy_adamw, py::arg("device") = -1,
|
|
110
|
+
py::arg("numel") = 1 << 24, nogil());
|
|
111
|
+
|
|
112
|
+
// ---- optimizer engine -----------------------------------------------------
|
|
113
|
+
py::class_<OffloadAdamW>(m, "OffloadAdamWEngine")
|
|
114
|
+
.def(py::init<int, const std::string&, int, int64_t>(), py::arg("device"), py::arg("mode") = "cpu",
|
|
115
|
+
py::arg("threads") = 0, py::arg("chunk_elems") = 1 << 20)
|
|
116
|
+
.def("add_param", &OffloadAdamW::add_param, py::arg("param"), py::arg("pin_moments") = true)
|
|
117
|
+
.def("offload_grad", &OffloadAdamW::offload_grad, py::arg("id"), py::arg("grad"),
|
|
118
|
+
py::arg("apply_update") = false, py::arg("lr") = 0.0, py::arg("beta1") = 0.9, py::arg("beta2") = 0.999,
|
|
119
|
+
py::arg("eps") = 1e-8, py::arg("weight_decay") = 0.0, nogil())
|
|
120
|
+
.def("step", &OffloadAdamW::step, py::arg("ids"), py::arg("lrs"), py::arg("beta1s"), py::arg("beta2s"),
|
|
121
|
+
py::arg("epss"), py::arg("wds"), py::arg("grads"), py::arg("max_grad_norm") = 0.0,
|
|
122
|
+
py::arg("compute_norm") = false, nogil())
|
|
123
|
+
.def("wait_ready", &OffloadAdamW::wait_ready, nogil())
|
|
124
|
+
.def("synchronize", &OffloadAdamW::synchronize, nogil())
|
|
125
|
+
.def("last_grad_norm", &OffloadAdamW::last_grad_norm, nogil())
|
|
126
|
+
.def("state", &OffloadAdamW::state, nogil())
|
|
127
|
+
.def("load_state",
|
|
128
|
+
[](OffloadAdamW& e, int64_t id, const at::Tensor& m, const at::Tensor& v,
|
|
129
|
+
const std::optional<at::Tensor>& master, int64_t step) {
|
|
130
|
+
e.load_state(id, m, v, master.value_or(at::Tensor()), step);
|
|
131
|
+
},
|
|
132
|
+
py::arg("id"), py::arg("exp_avg"), py::arg("exp_avg_sq"), py::arg("master") = py::none(),
|
|
133
|
+
py::arg("step") = 0, nogil())
|
|
134
|
+
.def("get_step", &OffloadAdamW::get_step)
|
|
135
|
+
.def("stats", &OffloadAdamW::stats)
|
|
136
|
+
.def_property_readonly("mode", &OffloadAdamW::mode)
|
|
137
|
+
.def_property_readonly("num_params", &OffloadAdamW::num_params)
|
|
138
|
+
.def_property_readonly("threads", &OffloadAdamW::threads);
|
|
139
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// TrainStream — device kernel launch interface.
|
|
2
|
+
//
|
|
3
|
+
// This header is deliberately free of PyTorch includes so that nvcc only has to
|
|
4
|
+
// parse CUDA runtime headers when compiling offload_adamw_kernel.cu. The C++
|
|
5
|
+
// translation units translate at::ScalarType into kernels::DType before calling.
|
|
6
|
+
#pragma once
|
|
7
|
+
|
|
8
|
+
#include <cstdint>
|
|
9
|
+
#include <cuda_runtime.h>
|
|
10
|
+
|
|
11
|
+
namespace trainstream {
|
|
12
|
+
namespace kernels {
|
|
13
|
+
|
|
14
|
+
enum class DType : int { kFloat32 = 0, kFloat16 = 1, kBFloat16 = 2 };
|
|
15
|
+
|
|
16
|
+
// Hyper-parameters for one AdamW step on one tensor. Bias corrections are folded
|
|
17
|
+
// on the host so the kernel does no pow() per element:
|
|
18
|
+
// step_size = lr / (1 - beta1^t)
|
|
19
|
+
// bias_correction2_sqrt = sqrt(1 - beta2^t)
|
|
20
|
+
struct AdamWParams {
|
|
21
|
+
float lr;
|
|
22
|
+
float beta1;
|
|
23
|
+
float beta2;
|
|
24
|
+
float eps;
|
|
25
|
+
float weight_decay;
|
|
26
|
+
float step_size;
|
|
27
|
+
float bias_correction2_sqrt;
|
|
28
|
+
float max_grad_norm; // only read when a grad_sq_norm pointer is supplied
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// Fused AdamW where the optimizer state lives in *mapped pinned host memory*.
|
|
32
|
+
// `exp_avg`, `exp_avg_sq` and (optionally) `master` are device-visible aliases of
|
|
33
|
+
// cudaHostAlloc(cudaHostAllocMapped) buffers, so every state read/write is a PCIe
|
|
34
|
+
// transaction and the moments never occupy VRAM. `param` and `grad` live in VRAM.
|
|
35
|
+
// If `master` is non-null the fp32 master copy is updated and `param` receives a
|
|
36
|
+
// rounded copy (mixed-precision training with fp16/bf16 weights).
|
|
37
|
+
// If `grad_sq_norm` is non-null it points at a device float holding sum(g^2) over
|
|
38
|
+
// all gradients; the kernel derives the global-norm clip coefficient from it.
|
|
39
|
+
cudaError_t adamw_zero_copy(DType dtype, void* param, const void* grad, float* exp_avg,
|
|
40
|
+
float* exp_avg_sq, float* master, int64_t n,
|
|
41
|
+
const AdamWParams& hp, const float* grad_sq_norm, int sm_count,
|
|
42
|
+
cudaStream_t stream);
|
|
43
|
+
|
|
44
|
+
// out[0] += sum(grad[i]^2). Used for global gradient-norm clipping on the GPU path.
|
|
45
|
+
cudaError_t grad_sq_norm_accumulate(DType dtype, const void* grad, int64_t n, float* out,
|
|
46
|
+
int sm_count, cudaStream_t stream);
|
|
47
|
+
|
|
48
|
+
} // namespace kernels
|
|
49
|
+
} // namespace trainstream
|