streamft 0.2.0__tar.gz → 0.2.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.
Files changed (25) hide show
  1. streamft-0.2.2/LICENSE +202 -0
  2. {streamft-0.2.0/streamft.egg-info → streamft-0.2.2}/PKG-INFO +67 -18
  3. {streamft-0.2.0 → streamft-0.2.2}/README.md +66 -17
  4. {streamft-0.2.0 → streamft-0.2.2}/pyproject.toml +1 -1
  5. {streamft-0.2.0 → streamft-0.2.2}/streamft/__main__.py +7 -0
  6. {streamft-0.2.0 → streamft-0.2.2}/streamft/autotune.py +14 -2
  7. {streamft-0.2.0 → streamft-0.2.2}/streamft/cli.py +23 -8
  8. {streamft-0.2.0 → streamft-0.2.2}/streamft/data.py +19 -0
  9. {streamft-0.2.0 → streamft-0.2.2}/streamft/disk_quant_store.py +18 -2
  10. {streamft-0.2.0 → streamft-0.2.2}/streamft/fit.py +3 -1
  11. {streamft-0.2.0 → streamft-0.2.2}/streamft/stream_quant_lora.py +22 -10
  12. {streamft-0.2.0 → streamft-0.2.2/streamft.egg-info}/PKG-INFO +67 -18
  13. {streamft-0.2.0 → streamft-0.2.2}/tests/test_streamft_smoke.py +179 -114
  14. streamft-0.2.0/LICENSE +0 -21
  15. {streamft-0.2.0 → streamft-0.2.2}/setup.cfg +0 -0
  16. {streamft-0.2.0 → streamft-0.2.2}/streamft/__init__.py +0 -0
  17. {streamft-0.2.0 → streamft-0.2.2}/streamft/doctor.py +0 -0
  18. {streamft-0.2.0 → streamft-0.2.2}/streamft/lora.py +0 -0
  19. {streamft-0.2.0 → streamft-0.2.2}/streamft/metrics.py +0 -0
  20. {streamft-0.2.0 → streamft-0.2.2}/streamft/stream_train.py +0 -0
  21. {streamft-0.2.0 → streamft-0.2.2}/streamft.egg-info/SOURCES.txt +0 -0
  22. {streamft-0.2.0 → streamft-0.2.2}/streamft.egg-info/dependency_links.txt +0 -0
  23. {streamft-0.2.0 → streamft-0.2.2}/streamft.egg-info/entry_points.txt +0 -0
  24. {streamft-0.2.0 → streamft-0.2.2}/streamft.egg-info/requires.txt +0 -0
  25. {streamft-0.2.0 → streamft-0.2.2}/streamft.egg-info/top_level.txt +0 -0
streamft-0.2.2/LICENSE ADDED
@@ -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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: streamft
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Fine-tune models that do not fit: stream NF4 weights from disk, one transformer block at a time.
5
5
  Author-email: Gokhan Cava <byjameson@users.noreply.github.com>
6
6
  License: Apache-2.0
@@ -30,6 +30,8 @@ Dynamic: license-file
30
30
 
31
31
  # stream-finetune — fine-tune a 32B model on a 6 GB laptop GPU
32
32
 
33
+ [![PyPI](https://img.shields.io/pypi/v/streamft)](https://pypi.org/project/streamft/) [![try it](https://img.shields.io/badge/try-will%20it%20fit%3F-6ee7b7)](https://huggingface.co/spaces/byjameson/will-it-fit)
34
+
33
35
  A small training engine that fine-tunes models that **do not fit in VRAM**. The NF4
34
36
  weights are mmap'd from disk, one transformer block is materialised on the GPU at a
35
37
  time, and the backward recomputes through it. The base stays frozen; a LoRA adapter is
@@ -53,7 +55,8 @@ The 32B weights are **19.2 GB**. They never fully live in VRAM. At 1024 tokens/s
53
55
  throughput is **3.1×** the 128-token rate, because the per-step I/O is amortised over
54
56
  more tokens. 50 steps of Dolly-15k SFT moved eval loss **1.8755 → 0.9661**.
55
57
 
56
- **Start with [`GUIDE_6GB_32B.md`](GUIDE_6GB_32B.md)** — the practical write-up: presets,
58
+ **Installed from PyPI? Start with [`QUICKSTART.md`](QUICKSTART.md)** — it uses only the
59
+ published CLI (no repo scripts). Deeper dive: [`GUIDE_6GB_32B.md`](GUIDE_6GB_32B.md) — the practical write-up: presets,
57
60
  the six traps, and which numbers are real. The measurement protocol, the discarded rows
58
61
  and the correction of an earlier wrong claim ("8.6× / 100 tok/s") are in
59
62
  [`LONGCTX_FINDINGS.md`](LONGCTX_FINDINGS.md).
@@ -61,7 +64,7 @@ and the correction of an earlier wrong claim ("8.6× / 100 tok/s") are in
61
64
  ## Quick start
62
65
 
63
66
  ```powershell
64
- pip install -e . # or: pip install streamft (once it is on PyPI)
67
+ pip install streamft
65
68
 
66
69
  # 0) will it fit? memory arithmetic + the measured reference, no weights downloaded
67
70
  streamft fit --model Qwen/Qwen2.5-14B-Instruct --gpu 6 --seq 512
@@ -142,30 +145,33 @@ Raw output: `results/gradcheck.json` (git-ignored; the numbers above are copied
142
145
 
143
146
  ## Compared with PEFT (matched runs)
144
147
 
145
- Same data, same LoRA (r=8, α=16, q/k/v/o), same AdamW lr 1e-4, batch 1, same prompt
148
+ Same data, same LoRA (r=8, alpha=16, q/k/v/o), same AdamW lr 1e-4, batch 1, same prompt
146
149
  masking, same token-weighted masked eval on 8 held-out rows. PEFT uses
147
150
  `prepare_model_for_kbit_training` with gradient checkpointing (the standard QLoRA setup).
151
+ Step times move by up to ~30% between runs on this laptop; quality is the stable number.
148
152
 
149
153
  **3B (fits entirely):**
150
154
 
151
155
  | | streamft (36 blocks resident) | PEFT / transformers |
152
156
  |---|---:|---:|
153
- | step time, median of 30 @ seq 512 | 0.938 s | **0.579 s** |
157
+ | step time, median of 30 @ seq 512 | 0.94–1.24 s | **0.58–0.88 s** |
154
158
  | peak VRAM | **3.85 GB** | 4.90 GB |
155
159
  | eval before | 1.42087 | 1.42087 |
156
- | eval after | **1.30154** (−0.1193) | 1.32722 (−0.0936) |
160
+ | eval after | **1.30720** (−0.1137) | 1.33002 (−0.0909) |
157
161
 
158
- **7B and 14B (do not fit comfortably):**
162
+ **7B / 14B / 32B (do not fit comfortably), after the masked-gradient fix:**
159
163
 
160
- | model | step time, median @ seq 512 | peak VRAM | eval (start → after) |
164
+ | model | step time, median @ seq 512 | peak VRAM | eval (start → after, 30 steps) |
161
165
  |---|---:|---:|---:|
162
- | 7B, streamft (28 blocks) | **1.70 s** | **5.51 GB** | 2.1928 → 1.1094 |
166
+ | 7B, streamft (28 blocks) | **1.55 s** | **5.51 GB** | 2.1928 → **1.1055** |
163
167
  | 7B, PEFT | 8.96 s | 10.05 GB | 2.1914 → 1.1491 |
164
- | 14B, streamft (6 blocks) | **6.73 s** | **3.86 GB** | 2.3748 → 1.5312 (10 steps) |
165
- | 14B, PEFT | 18.56 s | 16.48 GB | 2.3748 (3 steps only) |
168
+ | 14B, streamft (6 blocks) | **5.86 s** | **3.86 GB** | 2.3748 → **0.9742** |
169
+ | 14B, PEFT | 18.56 s | 16.48 GB | 3 steps only |
170
+ | 32B, streamft (2 blocks, seq 1024) | **12.48 s** | **3.90 GB** | 1.8755 → **1.0008** |
171
+ | 32B, PEFT | fails before step 1 | — | — |
166
172
 
167
173
  At 7B the crossover has already happened: PEFT's 4.4 GB of weights plus activations no
168
- longer fit, so it spills (10.05 GB reserved) and pays 5.3× the step time. Note that
174
+ longer fit, so it spills (10.05 GB reserved) and pays ~5.8× the step time. Note that
169
175
  streamft's 7B peak (5.51 GB) is *higher* than its 14B peak (3.86 GB) because the 7B run
170
176
  kept all 28 blocks resident while the 14B run kept 6 — the window is a choice, and the
171
177
  14B number is the one to copy for a 6 GB card.
@@ -174,16 +180,58 @@ kept all 28 blocks resident while the 14B run kept 6 — the window is a choice,
174
180
  into shared memory (19.45 GB reserved on a 6 GiB card), and `prepare_model_for_kbit_training`
175
181
  then dies allocating the fp32 norm copy: *CUDA out of memory. Tried to allocate 2.90 GiB;
176
182
  18.00 GiB is already allocated.* The streaming engine runs the same checkpoint at
177
- **12.5 s/step and 3.90 GB** (64/64 layers, held-out 1.8755 to 0.9959).
183
+ **12.5 s/step and 3.90 GB** (64/64 layers).
178
184
 
179
185
  The 3B row is the honest answer to "is this faster?": **no** — on a model that fits, PEFT
180
- is 1.6× faster and uses 1.05 GB more. The 14B row is the design point: PEFT does not
181
- OOM on Windows, it **spills into shared system memory** (16.48 GB reserved on a 6.4 GB
182
- card) and pays 2.8× the step time; streamft stays at 3.86 GB. Over 30 steps and one seed
183
- the 3B quality difference is not meaningful.
186
+ is faster and uses 1.05 GB more. The 14B/32B rows are the design point: PEFT does not
187
+ OOM on Windows, it **spills into shared system memory** and pays 2.8–5.8× the step time.
188
+
189
+ ### Correction: masked gradient (25 Oct, after an external review)
190
+
191
+ `chunked_lm_loss_and_backward_masked` divided every chunk by **that chunk's** valid-token
192
+ count. The reported loss was still the correct mean, so the curves looked right, but the
193
+ accumulated gradient over-weighted chunks with few unmasked tokens — i.e. the prompt-heavy
194
+ start of an SFT row. Measured on a toy model with an uneven mask: **112–427% relative
195
+ gradient error** at seq 512/1024 with 60% of the row masked (chunk 128), while balanced
196
+ masks were unaffected.
197
+
198
+ The fix divides every chunk by the **global** valid count (computed once, no-grad), so the
199
+ gradient is exactly d(mean CE over valid tokens)/dh. Two tests pin it:
200
+ `test_masked_chunked_gradient_matches_full_with_uneven_masks` and
201
+ `test_masked_chunked_handles_fully_masked_chunks`.
202
+
203
+ All SFT runs above were re-run with the fix. Quality held: 3B −0.114 (was −0.119),
204
+ 7B −1.087 (was −1.083), 32B −0.875 (was −0.880); 14B is now 30 steps (−1.40) instead of
205
+ 10. The numbers in the tables are the post-fix ones.
184
206
 
185
207
  Reproduce: `python scripts/compare_peft.py --model checkpoints/qwen3b_bnb4bit --steps 30`
186
- and `... --model checkpoints/qwen14b_nf4 --steps 3`.
208
+ and `... --model checkpoints/qwen14b_nf4 --steps 30`.
209
+
210
+ ### Reproducibility probe
211
+
212
+ Run this and compare the row; it is deterministic (seed 1234) apart from GPU-kernel
213
+ non-determinism:
214
+
215
+ ```bash
216
+ streamft train --model-dir checkpoints/qwen3b_bnb4bit --steps 3 --seq 128 \
217
+ --eval_chunks 1 --tag repro
218
+ ```
219
+
220
+ Reference on the only machine tested so far (RTX 3050 Laptop 6 GB, torch 2.13.0+cu126,
221
+ bitsandbytes 0.50.2, Windows 11):
222
+
223
+ ```text
224
+ losses 3.347981 3.647039 3.049560
225
+ ce_before 2.44565
226
+ ce_after 2.44568
227
+ peak_gb_max 3.068
228
+ adapter_sha_after 422424c59ef004c5
229
+ ```
230
+
231
+ Different hardware will differ in the last digits (kernels, bf16 rounding). What must
232
+ match is the shape: the same three losses to ~1e-3, `grad_layers == n_layers`, and a
233
+ changed adapter hash. If it does not, that is a bug report worth posting with the
234
+ `streamft doctor` output.
187
235
 
188
236
  ## What this does not do
189
237
 
@@ -233,6 +281,7 @@ URLs. The engine lived at `experiments/exp54_disk_qlora.py` + `lcsa/` until the
233
281
  - [Running a 4B model in 6 GB and training 3B parameters on a laptop](https://dev.to/mycute_97b39c4e34027570f9/running-a-4b-model-in-6-gb-and-training-3b-parameters-on-a-laptop-4al)
234
282
  - [The same 32B post on Medium](https://medium.com/@myredditacc9393/fine-tuning-a-32b-model-on-a-6-gb-laptop-gpu-e749df447229)
235
283
  - [Will it fit? A free planner for fine-tuning models that do not fit](https://dev.to/mycute_97b39c4e34027570f9/will-it-fit-a-free-planner-for-fine-tuning-models-that-do-not-fit-on-your-gpu-o50)
284
+ - [Will it fit? on Medium](https://medium.com/@myredditacc9393/will-it-fit-a-free-check-before-you-download-19-gb-of-weights-9097e1fcf93f)
236
285
 
237
286
  ## License
238
287
 
@@ -1,5 +1,7 @@
1
1
  # stream-finetune — fine-tune a 32B model on a 6 GB laptop GPU
2
2
 
3
+ [![PyPI](https://img.shields.io/pypi/v/streamft)](https://pypi.org/project/streamft/) [![try it](https://img.shields.io/badge/try-will%20it%20fit%3F-6ee7b7)](https://huggingface.co/spaces/byjameson/will-it-fit)
4
+
3
5
  A small training engine that fine-tunes models that **do not fit in VRAM**. The NF4
4
6
  weights are mmap'd from disk, one transformer block is materialised on the GPU at a
5
7
  time, and the backward recomputes through it. The base stays frozen; a LoRA adapter is
@@ -23,7 +25,8 @@ The 32B weights are **19.2 GB**. They never fully live in VRAM. At 1024 tokens/s
23
25
  throughput is **3.1×** the 128-token rate, because the per-step I/O is amortised over
24
26
  more tokens. 50 steps of Dolly-15k SFT moved eval loss **1.8755 → 0.9661**.
25
27
 
26
- **Start with [`GUIDE_6GB_32B.md`](GUIDE_6GB_32B.md)** — the practical write-up: presets,
28
+ **Installed from PyPI? Start with [`QUICKSTART.md`](QUICKSTART.md)** — it uses only the
29
+ published CLI (no repo scripts). Deeper dive: [`GUIDE_6GB_32B.md`](GUIDE_6GB_32B.md) — the practical write-up: presets,
27
30
  the six traps, and which numbers are real. The measurement protocol, the discarded rows
28
31
  and the correction of an earlier wrong claim ("8.6× / 100 tok/s") are in
29
32
  [`LONGCTX_FINDINGS.md`](LONGCTX_FINDINGS.md).
@@ -31,7 +34,7 @@ and the correction of an earlier wrong claim ("8.6× / 100 tok/s") are in
31
34
  ## Quick start
32
35
 
33
36
  ```powershell
34
- pip install -e . # or: pip install streamft (once it is on PyPI)
37
+ pip install streamft
35
38
 
36
39
  # 0) will it fit? memory arithmetic + the measured reference, no weights downloaded
37
40
  streamft fit --model Qwen/Qwen2.5-14B-Instruct --gpu 6 --seq 512
@@ -112,30 +115,33 @@ Raw output: `results/gradcheck.json` (git-ignored; the numbers above are copied
112
115
 
113
116
  ## Compared with PEFT (matched runs)
114
117
 
115
- Same data, same LoRA (r=8, α=16, q/k/v/o), same AdamW lr 1e-4, batch 1, same prompt
118
+ Same data, same LoRA (r=8, alpha=16, q/k/v/o), same AdamW lr 1e-4, batch 1, same prompt
116
119
  masking, same token-weighted masked eval on 8 held-out rows. PEFT uses
117
120
  `prepare_model_for_kbit_training` with gradient checkpointing (the standard QLoRA setup).
121
+ Step times move by up to ~30% between runs on this laptop; quality is the stable number.
118
122
 
119
123
  **3B (fits entirely):**
120
124
 
121
125
  | | streamft (36 blocks resident) | PEFT / transformers |
122
126
  |---|---:|---:|
123
- | step time, median of 30 @ seq 512 | 0.938 s | **0.579 s** |
127
+ | step time, median of 30 @ seq 512 | 0.94–1.24 s | **0.58–0.88 s** |
124
128
  | peak VRAM | **3.85 GB** | 4.90 GB |
125
129
  | eval before | 1.42087 | 1.42087 |
126
- | eval after | **1.30154** (−0.1193) | 1.32722 (−0.0936) |
130
+ | eval after | **1.30720** (−0.1137) | 1.33002 (−0.0909) |
127
131
 
128
- **7B and 14B (do not fit comfortably):**
132
+ **7B / 14B / 32B (do not fit comfortably), after the masked-gradient fix:**
129
133
 
130
- | model | step time, median @ seq 512 | peak VRAM | eval (start → after) |
134
+ | model | step time, median @ seq 512 | peak VRAM | eval (start → after, 30 steps) |
131
135
  |---|---:|---:|---:|
132
- | 7B, streamft (28 blocks) | **1.70 s** | **5.51 GB** | 2.1928 → 1.1094 |
136
+ | 7B, streamft (28 blocks) | **1.55 s** | **5.51 GB** | 2.1928 → **1.1055** |
133
137
  | 7B, PEFT | 8.96 s | 10.05 GB | 2.1914 → 1.1491 |
134
- | 14B, streamft (6 blocks) | **6.73 s** | **3.86 GB** | 2.3748 → 1.5312 (10 steps) |
135
- | 14B, PEFT | 18.56 s | 16.48 GB | 2.3748 (3 steps only) |
138
+ | 14B, streamft (6 blocks) | **5.86 s** | **3.86 GB** | 2.3748 → **0.9742** |
139
+ | 14B, PEFT | 18.56 s | 16.48 GB | 3 steps only |
140
+ | 32B, streamft (2 blocks, seq 1024) | **12.48 s** | **3.90 GB** | 1.8755 → **1.0008** |
141
+ | 32B, PEFT | fails before step 1 | — | — |
136
142
 
137
143
  At 7B the crossover has already happened: PEFT's 4.4 GB of weights plus activations no
138
- longer fit, so it spills (10.05 GB reserved) and pays 5.3× the step time. Note that
144
+ longer fit, so it spills (10.05 GB reserved) and pays ~5.8× the step time. Note that
139
145
  streamft's 7B peak (5.51 GB) is *higher* than its 14B peak (3.86 GB) because the 7B run
140
146
  kept all 28 blocks resident while the 14B run kept 6 — the window is a choice, and the
141
147
  14B number is the one to copy for a 6 GB card.
@@ -144,16 +150,58 @@ kept all 28 blocks resident while the 14B run kept 6 — the window is a choice,
144
150
  into shared memory (19.45 GB reserved on a 6 GiB card), and `prepare_model_for_kbit_training`
145
151
  then dies allocating the fp32 norm copy: *CUDA out of memory. Tried to allocate 2.90 GiB;
146
152
  18.00 GiB is already allocated.* The streaming engine runs the same checkpoint at
147
- **12.5 s/step and 3.90 GB** (64/64 layers, held-out 1.8755 to 0.9959).
153
+ **12.5 s/step and 3.90 GB** (64/64 layers).
148
154
 
149
155
  The 3B row is the honest answer to "is this faster?": **no** — on a model that fits, PEFT
150
- is 1.6× faster and uses 1.05 GB more. The 14B row is the design point: PEFT does not
151
- OOM on Windows, it **spills into shared system memory** (16.48 GB reserved on a 6.4 GB
152
- card) and pays 2.8× the step time; streamft stays at 3.86 GB. Over 30 steps and one seed
153
- the 3B quality difference is not meaningful.
156
+ is faster and uses 1.05 GB more. The 14B/32B rows are the design point: PEFT does not
157
+ OOM on Windows, it **spills into shared system memory** and pays 2.8–5.8× the step time.
158
+
159
+ ### Correction: masked gradient (25 Oct, after an external review)
160
+
161
+ `chunked_lm_loss_and_backward_masked` divided every chunk by **that chunk's** valid-token
162
+ count. The reported loss was still the correct mean, so the curves looked right, but the
163
+ accumulated gradient over-weighted chunks with few unmasked tokens — i.e. the prompt-heavy
164
+ start of an SFT row. Measured on a toy model with an uneven mask: **112–427% relative
165
+ gradient error** at seq 512/1024 with 60% of the row masked (chunk 128), while balanced
166
+ masks were unaffected.
167
+
168
+ The fix divides every chunk by the **global** valid count (computed once, no-grad), so the
169
+ gradient is exactly d(mean CE over valid tokens)/dh. Two tests pin it:
170
+ `test_masked_chunked_gradient_matches_full_with_uneven_masks` and
171
+ `test_masked_chunked_handles_fully_masked_chunks`.
172
+
173
+ All SFT runs above were re-run with the fix. Quality held: 3B −0.114 (was −0.119),
174
+ 7B −1.087 (was −1.083), 32B −0.875 (was −0.880); 14B is now 30 steps (−1.40) instead of
175
+ 10. The numbers in the tables are the post-fix ones.
154
176
 
155
177
  Reproduce: `python scripts/compare_peft.py --model checkpoints/qwen3b_bnb4bit --steps 30`
156
- and `... --model checkpoints/qwen14b_nf4 --steps 3`.
178
+ and `... --model checkpoints/qwen14b_nf4 --steps 30`.
179
+
180
+ ### Reproducibility probe
181
+
182
+ Run this and compare the row; it is deterministic (seed 1234) apart from GPU-kernel
183
+ non-determinism:
184
+
185
+ ```bash
186
+ streamft train --model-dir checkpoints/qwen3b_bnb4bit --steps 3 --seq 128 \
187
+ --eval_chunks 1 --tag repro
188
+ ```
189
+
190
+ Reference on the only machine tested so far (RTX 3050 Laptop 6 GB, torch 2.13.0+cu126,
191
+ bitsandbytes 0.50.2, Windows 11):
192
+
193
+ ```text
194
+ losses 3.347981 3.647039 3.049560
195
+ ce_before 2.44565
196
+ ce_after 2.44568
197
+ peak_gb_max 3.068
198
+ adapter_sha_after 422424c59ef004c5
199
+ ```
200
+
201
+ Different hardware will differ in the last digits (kernels, bf16 rounding). What must
202
+ match is the shape: the same three losses to ~1e-3, `grad_layers == n_layers`, and a
203
+ changed adapter hash. If it does not, that is a bug report worth posting with the
204
+ `streamft doctor` output.
157
205
 
158
206
  ## What this does not do
159
207
 
@@ -203,6 +251,7 @@ URLs. The engine lived at `experiments/exp54_disk_qlora.py` + `lcsa/` until the
203
251
  - [Running a 4B model in 6 GB and training 3B parameters on a laptop](https://dev.to/mycute_97b39c4e34027570f9/running-a-4b-model-in-6-gb-and-training-3b-parameters-on-a-laptop-4al)
204
252
  - [The same 32B post on Medium](https://medium.com/@myredditacc9393/fine-tuning-a-32b-model-on-a-6-gb-laptop-gpu-e749df447229)
205
253
  - [Will it fit? A free planner for fine-tuning models that do not fit](https://dev.to/mycute_97b39c4e34027570f9/will-it-fit-a-free-planner-for-fine-tuning-models-that-do-not-fit-on-your-gpu-o50)
254
+ - [Will it fit? on Medium](https://medium.com/@myredditacc9393/will-it-fit-a-free-check-before-you-download-19-gb-of-weights-9097e1fcf93f)
206
255
 
207
256
  ## License
208
257
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "streamft"
7
- version = "0.2.0"
7
+ version = "0.2.2"
8
8
  description = "Fine-tune models that do not fit: stream NF4 weights from disk, one transformer block at a time."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -3,6 +3,7 @@
3
3
  streamft fit will this model fit? (memory arithmetic + measured speed when known)
4
4
  streamft prepare turn a bf16 model into a pre-quantized NF4 checkpoint
5
5
  streamft train the streaming trainer (all exp54 flags)
6
+ streamft data build the token shards (LM path only; SFT needs none)
6
7
  streamft doctor environment report (torch, CUDA, bitsandbytes, VRAM)
7
8
  """
8
9
  from __future__ import annotations
@@ -14,6 +15,7 @@ USAGE = """streamft - fine-tune models that do not fit
14
15
  streamft fit --model <dir|hf-id> [--gpu 6] [--seq 512]
15
16
  streamft prepare --model <dir> --save-quant checkpoints/<name>
16
17
  streamft train --model-dir checkpoints/<name> --sft --steps 30 [--seq 1024]
18
+ streamft data --model <dir|hf-id> --out data
17
19
  streamft doctor
18
20
 
19
21
  Docs: https://github.com/byjameson/stream-finetune
@@ -33,6 +35,11 @@ def main() -> int:
33
35
 
34
36
  return fit_main(rest)
35
37
 
38
+ if cmd == "data":
39
+ from streamft.data import main as data_main
40
+
41
+ return data_main(rest)
42
+
36
43
  if cmd == "doctor":
37
44
  from streamft.doctor import main as doctor_main
38
45
 
@@ -89,8 +89,20 @@ def checkpoint_stats(model_dir) -> dict:
89
89
  from safetensors import safe_open
90
90
 
91
91
  root = Path(model_dir)
92
- index = json.loads((root / "model.safetensors.index.json").read_text())
93
- weight_map: dict[str, str] = dict(index["weight_map"])
92
+ idx_path = root / "model.safetensors.index.json"
93
+ if idx_path.exists():
94
+ index = json.loads(idx_path.read_text())
95
+ weight_map: dict[str, str] = dict(index["weight_map"])
96
+ else:
97
+ # single-file checkpoint (small NF4 models): every key lives in one file
98
+ files = sorted(root.glob("*.safetensors"))
99
+ if len(files) != 1:
100
+ raise FileNotFoundError(
101
+ f"{root}: expected model.safetensors.index.json or exactly one "
102
+ f"*.safetensors file, found {len(files)}"
103
+ )
104
+ with safe_open(str(files[0]), framework="pt", device="cpu") as f:
105
+ weight_map = {k: files[0].name for k in f.keys()}
94
106
 
95
107
  handles: dict[str, object] = {}
96
108
  per_layer: dict[int, int] = {}
@@ -76,12 +76,22 @@ def adapter_sha(model) -> str:
76
76
  return h.hexdigest()[:16]
77
77
 
78
78
 
79
+ def user_path(value) -> Path:
80
+ """Resolve a CLI argument against the current directory (absolute paths unchanged).
81
+
82
+ The package root (`ROOT`) is where *this file* lives; for a pip-installed wheel that
83
+ is site-packages, which must never be used to resolve user paths.
84
+ """
85
+ q = Path(value).expanduser()
86
+ return q if q.is_absolute() else Path.cwd() / q
87
+
88
+
79
89
  def prepare(model: str, save_quant: str) -> int:
80
90
  """Quantize a local bf16 model into a bnb-4bit checkpoint (uint8 + qstate)."""
81
91
  from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
82
92
 
83
- src = str(ROOT / model)
84
- dst = ROOT / save_quant
93
+ src = str(user_path(model))
94
+ dst = user_path(save_quant)
85
95
  print(f"[prepare] {model} -> {save_quant}", flush=True)
86
96
  bnb = BitsAndBytesConfig(
87
97
  load_in_4bit=True,
@@ -212,7 +222,7 @@ def main() -> int:
212
222
  if args.prepare:
213
223
  return prepare(args.model, args.save_quant)
214
224
 
215
- model_dir = str(ROOT / args.model_dir)
225
+ model_dir = str(user_path(args.model_dir))
216
226
  print(f"[exp54] model_dir={Path(model_dir).name} steps={args.steps} seq={args.seq} "
217
227
  f"lora_r={args.lora_r} targets={args.targets} head={args.head}", flush=True)
218
228
 
@@ -361,12 +371,12 @@ def main() -> int:
361
371
  print(f"[eval] after loss={ce1:.4f} (delta {ce1-ce0:+.4f})", flush=True)
362
372
  wall = time.time() - t_all
363
373
  else:
364
- tokens = load_tokens(str(ROOT / args.data))
374
+ tokens = load_tokens(str(user_path(args.data)))
365
375
  sampler = TrainSampler(tokens, args.seq, generator=torch.Generator().manual_seed(1234))
366
376
  batches = [sampler.batch(1) for _ in range(args.steps)]
367
377
 
368
378
  if args.eval_chunks > 0:
369
- ev = chunks_from_tokens(load_tokens(str(ROOT / args.eval_data)), args.eval_seq,
379
+ ev = chunks_from_tokens(load_tokens(str(user_path(args.eval_data))), args.eval_seq,
370
380
  args.eval_chunks)
371
381
  ce0 = sum(stream_eval_ce(tr, ev[i].unsqueeze(0), args.chunk)
372
382
  for i in range(len(ev))) / len(ev)
@@ -392,7 +402,7 @@ def main() -> int:
392
402
 
393
403
  saved = None
394
404
  if args.save:
395
- save_path = ROOT / args.save
405
+ save_path = user_path(args.save)
396
406
  save_path.mkdir(parents=True, exist_ok=True)
397
407
  torch.save(lora_state_dict(model), str(save_path / "adapter.pt"))
398
408
  (save_path / "adapter_config.json").write_text(json.dumps({
@@ -437,11 +447,16 @@ def main() -> int:
437
447
  "ce_after": round(ce1, 5) if ce1 is not None else None,
438
448
  "ce_delta": round(ce1 - ce0, 6) if (ce0 is not None and ce1 is not None) else None,
439
449
  "saved": saved,
450
+ "license": "Apache-2.0",
451
+ "gpu": torch.cuda.get_device_name(0),
452
+ "torch": torch.__version__,
453
+ "cuda": torch.version.cuda,
440
454
  "ts": now(),
441
455
  }
442
456
  print(json.dumps(row, ensure_ascii=True), flush=True)
443
- append_jsonl(str(ROOT / "results" / "results.jsonl"), row)
444
- with open(ROOT / "results" / "exp54_disk_qlora.log", "a", encoding="utf-8") as f:
457
+ results_dir = user_path("results")
458
+ append_jsonl(str(results_dir / "results.jsonl"), row)
459
+ with open(results_dir / "exp54_disk_qlora.log", "a", encoding="utf-8") as f:
445
460
  f.write(json.dumps(row, ensure_ascii=False) + "\n")
446
461
  return 0
447
462
 
@@ -79,3 +79,22 @@ class TrainSampler:
79
79
  xs = torch.stack([self.tokens[s: s + self.seq_len].long() for s in starts])
80
80
  ys = torch.stack([self.tokens[s + 1: s + self.seq_len + 1].long() for s in starts])
81
81
  return xs, ys
82
+
83
+
84
+ def main(argv=None) -> int:
85
+ """`streamft data` -- build the token shards that --data/--eval_data expect."""
86
+ import argparse
87
+
88
+ from transformers import AutoTokenizer
89
+
90
+ ap = argparse.ArgumentParser(prog="streamft data")
91
+ ap.add_argument("--model", default="models/Qwen2.5-0.5B",
92
+ help="tokenizer source (local dir or HF id)")
93
+ ap.add_argument("--out", default="data")
94
+ ap.add_argument("--force", action="store_true", help="rebuild existing shards")
95
+ args = ap.parse_args(argv)
96
+ tok = AutoTokenizer.from_pretrained(args.model)
97
+ out = build_all(tok, args.out, force=args.force)
98
+ for name, path in out.items():
99
+ print(f"{name:20s} {path}")
100
+ return 0
@@ -43,8 +43,24 @@ class DiskQuantStore:
43
43
 
44
44
  def __init__(self, model_dir, device: str = "cuda"):
45
45
  self.dir = Path(model_dir)
46
- index = json.loads((self.dir / "model.safetensors.index.json").read_text())
47
- self.weight_map: dict[str, str] = dict(index["weight_map"])
46
+ idx_path = self.dir / "model.safetensors.index.json"
47
+ if idx_path.exists():
48
+ index = json.loads(idx_path.read_text())
49
+ self.weight_map: dict[str, str] = dict(index["weight_map"])
50
+ else:
51
+ # Single-file checkpoint (what `save_pretrained` writes for models whose
52
+ # quantized weights fit in one shard, e.g. 0.5B/1.5B NF4). The index is
53
+ # optional; every key lives in that one file.
54
+ files = sorted(self.dir.glob("*.safetensors"))
55
+ if len(files) != 1:
56
+ raise FileNotFoundError(
57
+ f"{self.dir}: expected model.safetensors.index.json or exactly one "
58
+ f"*.safetensors file, found {len(files)}"
59
+ )
60
+ from safetensors import safe_open
61
+
62
+ with safe_open(str(files[0]), framework="pt", device="cpu") as f:
63
+ self.weight_map = {k: files[0].name for k in f.keys()}
48
64
  self.device = device
49
65
  self._handles: dict[str, object] = {}
50
66
 
@@ -109,7 +109,9 @@ def main(argv: list[str] | None = None) -> int:
109
109
  f"+ reserve {RESERVE_GB} GB (embedding stays on CPU)")
110
110
  print(f" -> whole model needs ~{out['needed_whole_gb']} GB on {args.gpu:g} GB")
111
111
  if fits_whole:
112
- print(" verdict: fits whole at this seq (no streaming needed; >1k can still spill)")
112
+ print(" verdict: budget says the whole model fits at this seq")
113
+ print(" caution: activations and allocator headroom are not fully modelled;")
114
+ print(" treat this as a budget check, not a guarantee. >1k can still spill.")
113
115
  else:
114
116
  print(" verdict: needs streaming (one or more blocks on the GPU at a time)")
115
117
  if measured:
@@ -22,27 +22,39 @@ from .stream_train import _layer_out, chunked_lm_loss_and_backward
22
22
 
23
23
 
24
24
  def chunked_lm_loss_and_backward_masked(head, h, ys, chunk=128, ignore_index=-100):
25
- """Chunked CE with an ignore_index (for SFT prompt masking)."""
25
+ """Chunked CE with an ignore_index (for SFT prompt masking).
26
+
27
+ Every chunk contributes `loss_sum / valid_total` where valid_total is the number of
28
+ unmasked targets in the **whole sequence**, so the accumulated gradient is exactly
29
+ d(mean CE over valid tokens)/dh.
30
+
31
+ FIX (25.10.2026, reported by an external reviewer): the first version divided each
32
+ chunk by that chunk's own valid count. Losses were unaffected (the returned value
33
+ summed to the right mean) but the gradient over-weighted chunks with few valid
34
+ tokens, i.e. the prompt-heavy start of an SFT row. tests/test_streamft_smoke.py
35
+ pins the corrected behaviour with an uneven mask.
36
+ """
26
37
  B, T, _ = h.shape
38
+ tgt_all = ys.to(h.device)
39
+ valid_total = int((tgt_all != ignore_index).sum())
40
+ if valid_total == 0:
41
+ zero = torch.zeros((), device=h.device)
42
+ return zero, zero
27
43
  total = torch.zeros((), device=h.device, dtype=torch.float32)
28
- valid_total = 0
29
44
  for a in range(0, T, chunk):
30
45
  b = min(a + chunk, T)
31
- logits = head(h[:, a:b])
32
- tgt = ys[:, a:b].reshape(-1).to(h.device)
33
- valid = int((tgt != ignore_index).sum())
34
- if valid == 0:
46
+ tgt = tgt_all[:, a:b].reshape(-1)
47
+ if int((tgt != ignore_index).sum()) == 0:
35
48
  continue
49
+ logits = head(h[:, a:b])
36
50
  loss_sum = torch.nn.functional.cross_entropy(
37
51
  logits.reshape(-1, logits.shape[-1]).float(), tgt,
38
52
  reduction="sum", ignore_index=ignore_index,
39
53
  )
40
- (loss_sum / valid).backward()
54
+ (loss_sum / valid_total).backward()
41
55
  with torch.no_grad():
42
56
  total = total + loss_sum.detach()
43
- valid_total += valid
44
- denom = max(valid_total, 1)
45
- return total / denom, total / denom
57
+ return total / valid_total, total / valid_total
46
58
 
47
59
 
48
60
  def base_model_of(model):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: streamft
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Fine-tune models that do not fit: stream NF4 weights from disk, one transformer block at a time.
5
5
  Author-email: Gokhan Cava <byjameson@users.noreply.github.com>
6
6
  License: Apache-2.0
@@ -30,6 +30,8 @@ Dynamic: license-file
30
30
 
31
31
  # stream-finetune — fine-tune a 32B model on a 6 GB laptop GPU
32
32
 
33
+ [![PyPI](https://img.shields.io/pypi/v/streamft)](https://pypi.org/project/streamft/) [![try it](https://img.shields.io/badge/try-will%20it%20fit%3F-6ee7b7)](https://huggingface.co/spaces/byjameson/will-it-fit)
34
+
33
35
  A small training engine that fine-tunes models that **do not fit in VRAM**. The NF4
34
36
  weights are mmap'd from disk, one transformer block is materialised on the GPU at a
35
37
  time, and the backward recomputes through it. The base stays frozen; a LoRA adapter is
@@ -53,7 +55,8 @@ The 32B weights are **19.2 GB**. They never fully live in VRAM. At 1024 tokens/s
53
55
  throughput is **3.1×** the 128-token rate, because the per-step I/O is amortised over
54
56
  more tokens. 50 steps of Dolly-15k SFT moved eval loss **1.8755 → 0.9661**.
55
57
 
56
- **Start with [`GUIDE_6GB_32B.md`](GUIDE_6GB_32B.md)** — the practical write-up: presets,
58
+ **Installed from PyPI? Start with [`QUICKSTART.md`](QUICKSTART.md)** — it uses only the
59
+ published CLI (no repo scripts). Deeper dive: [`GUIDE_6GB_32B.md`](GUIDE_6GB_32B.md) — the practical write-up: presets,
57
60
  the six traps, and which numbers are real. The measurement protocol, the discarded rows
58
61
  and the correction of an earlier wrong claim ("8.6× / 100 tok/s") are in
59
62
  [`LONGCTX_FINDINGS.md`](LONGCTX_FINDINGS.md).
@@ -61,7 +64,7 @@ and the correction of an earlier wrong claim ("8.6× / 100 tok/s") are in
61
64
  ## Quick start
62
65
 
63
66
  ```powershell
64
- pip install -e . # or: pip install streamft (once it is on PyPI)
67
+ pip install streamft
65
68
 
66
69
  # 0) will it fit? memory arithmetic + the measured reference, no weights downloaded
67
70
  streamft fit --model Qwen/Qwen2.5-14B-Instruct --gpu 6 --seq 512
@@ -142,30 +145,33 @@ Raw output: `results/gradcheck.json` (git-ignored; the numbers above are copied
142
145
 
143
146
  ## Compared with PEFT (matched runs)
144
147
 
145
- Same data, same LoRA (r=8, α=16, q/k/v/o), same AdamW lr 1e-4, batch 1, same prompt
148
+ Same data, same LoRA (r=8, alpha=16, q/k/v/o), same AdamW lr 1e-4, batch 1, same prompt
146
149
  masking, same token-weighted masked eval on 8 held-out rows. PEFT uses
147
150
  `prepare_model_for_kbit_training` with gradient checkpointing (the standard QLoRA setup).
151
+ Step times move by up to ~30% between runs on this laptop; quality is the stable number.
148
152
 
149
153
  **3B (fits entirely):**
150
154
 
151
155
  | | streamft (36 blocks resident) | PEFT / transformers |
152
156
  |---|---:|---:|
153
- | step time, median of 30 @ seq 512 | 0.938 s | **0.579 s** |
157
+ | step time, median of 30 @ seq 512 | 0.94–1.24 s | **0.58–0.88 s** |
154
158
  | peak VRAM | **3.85 GB** | 4.90 GB |
155
159
  | eval before | 1.42087 | 1.42087 |
156
- | eval after | **1.30154** (−0.1193) | 1.32722 (−0.0936) |
160
+ | eval after | **1.30720** (−0.1137) | 1.33002 (−0.0909) |
157
161
 
158
- **7B and 14B (do not fit comfortably):**
162
+ **7B / 14B / 32B (do not fit comfortably), after the masked-gradient fix:**
159
163
 
160
- | model | step time, median @ seq 512 | peak VRAM | eval (start → after) |
164
+ | model | step time, median @ seq 512 | peak VRAM | eval (start → after, 30 steps) |
161
165
  |---|---:|---:|---:|
162
- | 7B, streamft (28 blocks) | **1.70 s** | **5.51 GB** | 2.1928 → 1.1094 |
166
+ | 7B, streamft (28 blocks) | **1.55 s** | **5.51 GB** | 2.1928 → **1.1055** |
163
167
  | 7B, PEFT | 8.96 s | 10.05 GB | 2.1914 → 1.1491 |
164
- | 14B, streamft (6 blocks) | **6.73 s** | **3.86 GB** | 2.3748 → 1.5312 (10 steps) |
165
- | 14B, PEFT | 18.56 s | 16.48 GB | 2.3748 (3 steps only) |
168
+ | 14B, streamft (6 blocks) | **5.86 s** | **3.86 GB** | 2.3748 → **0.9742** |
169
+ | 14B, PEFT | 18.56 s | 16.48 GB | 3 steps only |
170
+ | 32B, streamft (2 blocks, seq 1024) | **12.48 s** | **3.90 GB** | 1.8755 → **1.0008** |
171
+ | 32B, PEFT | fails before step 1 | — | — |
166
172
 
167
173
  At 7B the crossover has already happened: PEFT's 4.4 GB of weights plus activations no
168
- longer fit, so it spills (10.05 GB reserved) and pays 5.3× the step time. Note that
174
+ longer fit, so it spills (10.05 GB reserved) and pays ~5.8× the step time. Note that
169
175
  streamft's 7B peak (5.51 GB) is *higher* than its 14B peak (3.86 GB) because the 7B run
170
176
  kept all 28 blocks resident while the 14B run kept 6 — the window is a choice, and the
171
177
  14B number is the one to copy for a 6 GB card.
@@ -174,16 +180,58 @@ kept all 28 blocks resident while the 14B run kept 6 — the window is a choice,
174
180
  into shared memory (19.45 GB reserved on a 6 GiB card), and `prepare_model_for_kbit_training`
175
181
  then dies allocating the fp32 norm copy: *CUDA out of memory. Tried to allocate 2.90 GiB;
176
182
  18.00 GiB is already allocated.* The streaming engine runs the same checkpoint at
177
- **12.5 s/step and 3.90 GB** (64/64 layers, held-out 1.8755 to 0.9959).
183
+ **12.5 s/step and 3.90 GB** (64/64 layers).
178
184
 
179
185
  The 3B row is the honest answer to "is this faster?": **no** — on a model that fits, PEFT
180
- is 1.6× faster and uses 1.05 GB more. The 14B row is the design point: PEFT does not
181
- OOM on Windows, it **spills into shared system memory** (16.48 GB reserved on a 6.4 GB
182
- card) and pays 2.8× the step time; streamft stays at 3.86 GB. Over 30 steps and one seed
183
- the 3B quality difference is not meaningful.
186
+ is faster and uses 1.05 GB more. The 14B/32B rows are the design point: PEFT does not
187
+ OOM on Windows, it **spills into shared system memory** and pays 2.8–5.8× the step time.
188
+
189
+ ### Correction: masked gradient (25 Oct, after an external review)
190
+
191
+ `chunked_lm_loss_and_backward_masked` divided every chunk by **that chunk's** valid-token
192
+ count. The reported loss was still the correct mean, so the curves looked right, but the
193
+ accumulated gradient over-weighted chunks with few unmasked tokens — i.e. the prompt-heavy
194
+ start of an SFT row. Measured on a toy model with an uneven mask: **112–427% relative
195
+ gradient error** at seq 512/1024 with 60% of the row masked (chunk 128), while balanced
196
+ masks were unaffected.
197
+
198
+ The fix divides every chunk by the **global** valid count (computed once, no-grad), so the
199
+ gradient is exactly d(mean CE over valid tokens)/dh. Two tests pin it:
200
+ `test_masked_chunked_gradient_matches_full_with_uneven_masks` and
201
+ `test_masked_chunked_handles_fully_masked_chunks`.
202
+
203
+ All SFT runs above were re-run with the fix. Quality held: 3B −0.114 (was −0.119),
204
+ 7B −1.087 (was −1.083), 32B −0.875 (was −0.880); 14B is now 30 steps (−1.40) instead of
205
+ 10. The numbers in the tables are the post-fix ones.
184
206
 
185
207
  Reproduce: `python scripts/compare_peft.py --model checkpoints/qwen3b_bnb4bit --steps 30`
186
- and `... --model checkpoints/qwen14b_nf4 --steps 3`.
208
+ and `... --model checkpoints/qwen14b_nf4 --steps 30`.
209
+
210
+ ### Reproducibility probe
211
+
212
+ Run this and compare the row; it is deterministic (seed 1234) apart from GPU-kernel
213
+ non-determinism:
214
+
215
+ ```bash
216
+ streamft train --model-dir checkpoints/qwen3b_bnb4bit --steps 3 --seq 128 \
217
+ --eval_chunks 1 --tag repro
218
+ ```
219
+
220
+ Reference on the only machine tested so far (RTX 3050 Laptop 6 GB, torch 2.13.0+cu126,
221
+ bitsandbytes 0.50.2, Windows 11):
222
+
223
+ ```text
224
+ losses 3.347981 3.647039 3.049560
225
+ ce_before 2.44565
226
+ ce_after 2.44568
227
+ peak_gb_max 3.068
228
+ adapter_sha_after 422424c59ef004c5
229
+ ```
230
+
231
+ Different hardware will differ in the last digits (kernels, bf16 rounding). What must
232
+ match is the shape: the same three losses to ~1e-3, `grad_layers == n_layers`, and a
233
+ changed adapter hash. If it does not, that is a bug report worth posting with the
234
+ `streamft doctor` output.
187
235
 
188
236
  ## What this does not do
189
237
 
@@ -233,6 +281,7 @@ URLs. The engine lived at `experiments/exp54_disk_qlora.py` + `lcsa/` until the
233
281
  - [Running a 4B model in 6 GB and training 3B parameters on a laptop](https://dev.to/mycute_97b39c4e34027570f9/running-a-4b-model-in-6-gb-and-training-3b-parameters-on-a-laptop-4al)
234
282
  - [The same 32B post on Medium](https://medium.com/@myredditacc9393/fine-tuning-a-32b-model-on-a-6-gb-laptop-gpu-e749df447229)
235
283
  - [Will it fit? A free planner for fine-tuning models that do not fit](https://dev.to/mycute_97b39c4e34027570f9/will-it-fit-a-free-planner-for-fine-tuning-models-that-do-not-fit-on-your-gpu-o50)
284
+ - [Will it fit? on Medium](https://medium.com/@myredditacc9393/will-it-fit-a-free-check-before-you-download-19-gb-of-weights-9097e1fcf93f)
236
285
 
237
286
  ## License
238
287
 
@@ -1,114 +1,179 @@
1
- """Smoke tests for the streamft package (CPU only, no model download).
2
-
3
- They pin the things that broke silently during development:
4
- * a LoRA layer must be a *no-op* at init (B = 0), otherwise "before/after" is a lie;
5
- * chunked cross-entropy must produce exactly d(mean CE)/dh, not a scaled version;
6
- * only the adapter gets gradients (the NF4 base stays frozen).
7
- """
8
-
9
- import math
10
-
11
- import torch
12
- import torch.nn as nn
13
- import torch.nn.functional as F
14
-
15
- from streamft import cli, stream_train
16
- from streamft.lora import LoRALinear, apply_lora, count_lora_params, lora_parameters
17
-
18
-
19
- # ---------------------------------------------------------------- lora
20
-
21
- def test_lora_is_noop_at_init():
22
- torch.manual_seed(0)
23
- base = nn.Linear(16, 8)
24
- lora = LoRALinear(base, r=4, alpha=16)
25
- x = torch.randn(3, 16)
26
- assert torch.allclose(lora(x), base(x), atol=1e-6)
27
- assert lora(x).shape == (3, 8)
28
- assert sum(p.numel() for p in lora.parameters() if p.requires_grad) == 4 * (16 + 8)
29
-
30
-
31
- def test_gradients_reach_only_the_adapter():
32
- torch.manual_seed(0)
33
- base = nn.Linear(16, 8)
34
- lora = LoRALinear(base, r=4)
35
- lora(torch.randn(3, 16)).sum().backward()
36
- assert base.weight.grad is None
37
- assert lora.A.grad is not None
38
- assert lora.B.grad is not None
39
-
40
-
41
- class _Attn(nn.Module):
42
- def __init__(self, d):
43
- super().__init__()
44
- for name in ("q_proj", "k_proj", "v_proj", "o_proj"):
45
- setattr(self, name, nn.Linear(d, d, bias=False))
46
-
47
-
48
- class _Mlp(nn.Module):
49
- def __init__(self, d):
50
- super().__init__()
51
- self.gate_proj = nn.Linear(d, 2 * d, bias=False)
52
- self.up_proj = nn.Linear(d, 2 * d, bias=False)
53
- self.down_proj = nn.Linear(2 * d, d, bias=False)
54
-
55
-
56
- class _Layer(nn.Module):
57
- def __init__(self, d):
58
- super().__init__()
59
- self.self_attn = _Attn(d)
60
- self.mlp = _Mlp(d)
61
-
62
-
63
- class _FakeQwen(nn.Module):
64
- """Just enough structure for apply_lora: model.layers[i].{self_attn,mlp}."""
65
-
66
- def __init__(self, d=16, n=2):
67
- super().__init__()
68
- self.model = nn.Module()
69
- self.model.layers = nn.ModuleList([_Layer(d) for _ in range(n)])
70
-
71
-
72
- def test_apply_lora_counts_and_freezes():
73
- model = _FakeQwen()
74
- apply_lora(model, r_attn=4, r_mlp=4)
75
-
76
- r, d = 4, 16
77
- per_proj_16 = r * (d + d) # q/k/v/o and down_proj
78
- per_proj_32 = r * (d + 2 * d) # gate/up_proj
79
- expected = 2 * (4 * per_proj_16 + 3 * per_proj_32)
80
- assert count_lora_params(model) == expected
81
-
82
- q = model.model.layers[0].self_attn.q_proj
83
- assert isinstance(q, LoRALinear)
84
- assert all(p.requires_grad is False for p in q.base.parameters())
85
-
86
- trainable = [p for p in model.parameters() if p.requires_grad]
87
- assert trainable and len(list(lora_parameters(model))) == len(trainable)
88
-
89
-
90
- # ---------------------------------------------------- chunked loss
91
-
92
- def test_chunked_ce_gradient_matches_full_mean():
93
- torch.manual_seed(0)
94
- d, T, V = 12, 9, 7
95
- head = nn.Linear(d, V, bias=False)
96
- ys = torch.randint(0, V, (1, T))
97
-
98
- h1 = torch.randn(1, T, d, requires_grad=True)
99
- full = F.cross_entropy(head(h1).reshape(-1, V), ys.reshape(-1), reduction="mean")
100
- full.backward()
101
-
102
- h2 = torch.randn(1, T, d, requires_grad=True)
103
- with torch.no_grad():
104
- h2.copy_(h1.detach())
105
- chunked_last, chunked_mean = stream_train.chunked_lm_loss_and_backward(head, h2, ys, chunk=4)
106
-
107
- assert math.isclose(float(chunked_mean.detach()), float(full.detach()), rel_tol=1e-5)
108
- assert torch.allclose(h1.grad, h2.grad, atol=1e-6)
109
-
110
-
111
- # ---------------------------------------------------------------- cli
112
-
113
- def test_cli_is_importable():
114
- assert callable(cli.main)
1
+ """Smoke tests for the streamft package (CPU only, no model download).
2
+
3
+ They pin the things that broke silently during development:
4
+ * a LoRA layer must be a *no-op* at init (B = 0), otherwise "before/after" is a lie;
5
+ * chunked cross-entropy must produce exactly d(mean CE)/dh, not a scaled version;
6
+ * only the adapter gets gradients (the NF4 base stays frozen).
7
+ """
8
+
9
+ import math
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+
15
+ from streamft import cli, stream_train
16
+ from streamft.lora import LoRALinear, apply_lora, count_lora_params, lora_parameters
17
+
18
+
19
+ # ---------------------------------------------------------------- lora
20
+
21
+ def test_lora_is_noop_at_init():
22
+ torch.manual_seed(0)
23
+ base = nn.Linear(16, 8)
24
+ lora = LoRALinear(base, r=4, alpha=16)
25
+ x = torch.randn(3, 16)
26
+ assert torch.allclose(lora(x), base(x), atol=1e-6)
27
+ assert lora(x).shape == (3, 8)
28
+ assert sum(p.numel() for p in lora.parameters() if p.requires_grad) == 4 * (16 + 8)
29
+
30
+
31
+ def test_gradients_reach_only_the_adapter():
32
+ torch.manual_seed(0)
33
+ base = nn.Linear(16, 8)
34
+ lora = LoRALinear(base, r=4)
35
+ lora(torch.randn(3, 16)).sum().backward()
36
+ assert base.weight.grad is None
37
+ assert lora.A.grad is not None
38
+ assert lora.B.grad is not None
39
+
40
+
41
+ class _Attn(nn.Module):
42
+ def __init__(self, d):
43
+ super().__init__()
44
+ for name in ("q_proj", "k_proj", "v_proj", "o_proj"):
45
+ setattr(self, name, nn.Linear(d, d, bias=False))
46
+
47
+
48
+ class _Mlp(nn.Module):
49
+ def __init__(self, d):
50
+ super().__init__()
51
+ self.gate_proj = nn.Linear(d, 2 * d, bias=False)
52
+ self.up_proj = nn.Linear(d, 2 * d, bias=False)
53
+ self.down_proj = nn.Linear(2 * d, d, bias=False)
54
+
55
+
56
+ class _Layer(nn.Module):
57
+ def __init__(self, d):
58
+ super().__init__()
59
+ self.self_attn = _Attn(d)
60
+ self.mlp = _Mlp(d)
61
+
62
+
63
+ class _FakeQwen(nn.Module):
64
+ """Just enough structure for apply_lora: model.layers[i].{self_attn,mlp}."""
65
+
66
+ def __init__(self, d=16, n=2):
67
+ super().__init__()
68
+ self.model = nn.Module()
69
+ self.model.layers = nn.ModuleList([_Layer(d) for _ in range(n)])
70
+
71
+
72
+ def test_apply_lora_counts_and_freezes():
73
+ model = _FakeQwen()
74
+ apply_lora(model, r_attn=4, r_mlp=4)
75
+
76
+ r, d = 4, 16
77
+ per_proj_16 = r * (d + d) # q/k/v/o and down_proj
78
+ per_proj_32 = r * (d + 2 * d) # gate/up_proj
79
+ expected = 2 * (4 * per_proj_16 + 3 * per_proj_32)
80
+ assert count_lora_params(model) == expected
81
+
82
+ q = model.model.layers[0].self_attn.q_proj
83
+ assert isinstance(q, LoRALinear)
84
+ assert all(p.requires_grad is False for p in q.base.parameters())
85
+
86
+ trainable = [p for p in model.parameters() if p.requires_grad]
87
+ assert trainable and len(list(lora_parameters(model))) == len(trainable)
88
+
89
+
90
+ # ---------------------------------------------------- chunked loss
91
+
92
+ def test_chunked_ce_gradient_matches_full_mean():
93
+ torch.manual_seed(0)
94
+ d, T, V = 12, 9, 7
95
+ head = nn.Linear(d, V, bias=False)
96
+ ys = torch.randint(0, V, (1, T))
97
+
98
+ h1 = torch.randn(1, T, d, requires_grad=True)
99
+ full = F.cross_entropy(head(h1).reshape(-1, V), ys.reshape(-1), reduction="mean")
100
+ full.backward()
101
+
102
+ h2 = torch.randn(1, T, d, requires_grad=True)
103
+ with torch.no_grad():
104
+ h2.copy_(h1.detach())
105
+ chunked_last, chunked_mean = stream_train.chunked_lm_loss_and_backward(head, h2, ys, chunk=4)
106
+
107
+ assert math.isclose(float(chunked_mean.detach()), float(full.detach()), rel_tol=1e-5)
108
+ assert torch.allclose(h1.grad, h2.grad, atol=1e-6)
109
+
110
+
111
+ # ---------------------------------------------------------------- cli
112
+
113
+ def test_cli_is_importable():
114
+ assert callable(cli.main)
115
+
116
+
117
+ # ------------------------------------------- masked (SFT) chunked loss
118
+
119
+ def test_masked_chunked_gradient_matches_full_with_uneven_masks():
120
+ """The 25.10 fix: chunks with different valid counts must not be re-weighted.
121
+
122
+ With chunk=3 and a prompt mask over the first 4 positions, chunk 0 has zero valid
123
+ targets, chunk 1 has two, later chunks have three. The old implementation divided
124
+ each chunk by its own count, which inflated the sparse chunks' gradient.
125
+ """
126
+ from streamft.stream_quant_lora import chunked_lm_loss_and_backward_masked
127
+
128
+ torch.manual_seed(0)
129
+ d, T, V = 12, 10, 7
130
+ head = nn.Linear(d, V, bias=False)
131
+ ys = torch.randint(0, V, (1, T))
132
+ ys[0, :4] = -100 # prompt
133
+ ys[0, 7] = -100 # a masked middle position
134
+
135
+ h1 = torch.randn(1, T, d, requires_grad=True)
136
+ full = F.cross_entropy(head(h1).reshape(-1, V), ys.reshape(-1),
137
+ ignore_index=-100, reduction="mean")
138
+ full.backward()
139
+
140
+ h2 = torch.randn(1, T, d, requires_grad=True)
141
+ with torch.no_grad():
142
+ h2.copy_(h1.detach())
143
+ _, mean = chunked_lm_loss_and_backward_masked(head, h2, ys, chunk=3)
144
+
145
+ assert math.isclose(float(mean.detach()), float(full.detach()), rel_tol=1e-6)
146
+ assert torch.allclose(h1.grad, h2.grad, atol=1e-6)
147
+
148
+
149
+ def test_masked_chunked_handles_fully_masked_chunks():
150
+ """A chunk with no valid targets must contribute nothing at all."""
151
+ from streamft.stream_quant_lora import chunked_lm_loss_and_backward_masked
152
+
153
+ torch.manual_seed(0)
154
+ d, T, V = 8, 6, 5
155
+ head = nn.Linear(d, V, bias=False)
156
+ ys = torch.randint(0, V, (1, T))
157
+ ys[0, :3] = -100
158
+ h = torch.randn(1, T, d, requires_grad=True)
159
+ _, mean = chunked_lm_loss_and_backward_masked(head, h, ys, chunk=2)
160
+ logits = head(h).reshape(-1, V)
161
+ tgt = ys.reshape(-1)
162
+ mask = tgt != -100
163
+ ref = F.cross_entropy(logits[mask], tgt[mask], reduction="mean")
164
+ assert math.isclose(float(mean.detach()), float(ref.detach()), rel_tol=1e-6)
165
+
166
+
167
+ # ------------------------------------------------ checkpoint file layouts
168
+
169
+ def test_disk_store_supports_single_safetensors_file(tmp_path):
170
+ """save_pretrained writes one file for small NF4 models; the index is optional."""
171
+ from safetensors.torch import save_file
172
+
173
+ from streamft.disk_quant_store import DiskQuantStore
174
+
175
+ save_file({"a": torch.zeros(4, dtype=torch.uint8),
176
+ "b.c": torch.ones(3)}, str(tmp_path / "model.safetensors"))
177
+ store = DiskQuantStore(str(tmp_path))
178
+ assert store.has("a") and store.has("b.c")
179
+ assert store.get("b.c").tolist() == [1.0, 1.0, 1.0]
streamft-0.2.0/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 LCGA contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
File without changes
File without changes
File without changes
File without changes
File without changes