streamft 0.2.1__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.
- streamft-0.2.2/LICENSE +202 -0
- {streamft-0.2.1/streamft.egg-info → streamft-0.2.2}/PKG-INFO +30 -3
- {streamft-0.2.1 → streamft-0.2.2}/README.md +29 -2
- {streamft-0.2.1 → streamft-0.2.2}/pyproject.toml +1 -1
- {streamft-0.2.1 → streamft-0.2.2}/streamft/__main__.py +7 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft/autotune.py +14 -2
- {streamft-0.2.1 → streamft-0.2.2}/streamft/cli.py +23 -8
- {streamft-0.2.1 → streamft-0.2.2}/streamft/data.py +19 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft/disk_quant_store.py +18 -2
- {streamft-0.2.1 → streamft-0.2.2}/streamft/fit.py +3 -1
- {streamft-0.2.1 → streamft-0.2.2/streamft.egg-info}/PKG-INFO +30 -3
- {streamft-0.2.1 → streamft-0.2.2}/tests/test_streamft_smoke.py +179 -164
- streamft-0.2.1/LICENSE +0 -21
- {streamft-0.2.1 → streamft-0.2.2}/setup.cfg +0 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft/__init__.py +0 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft/doctor.py +0 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft/lora.py +0 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft/metrics.py +0 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft/stream_quant_lora.py +0 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft/stream_train.py +0 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft.egg-info/SOURCES.txt +0 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft.egg-info/dependency_links.txt +0 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft.egg-info/entry_points.txt +0 -0
- {streamft-0.2.1 → streamft-0.2.2}/streamft.egg-info/requires.txt +0 -0
- {streamft-0.2.1 → 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.
|
|
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
|
|
@@ -55,7 +55,8 @@ The 32B weights are **19.2 GB**. They never fully live in VRAM. At 1024 tokens/s
|
|
|
55
55
|
throughput is **3.1×** the 128-token rate, because the per-step I/O is amortised over
|
|
56
56
|
more tokens. 50 steps of Dolly-15k SFT moved eval loss **1.8755 → 0.9661**.
|
|
57
57
|
|
|
58
|
-
**Start with [`
|
|
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,
|
|
59
60
|
the six traps, and which numbers are real. The measurement protocol, the discarded rows
|
|
60
61
|
and the correction of an earlier wrong claim ("8.6× / 100 tok/s") are in
|
|
61
62
|
[`LONGCTX_FINDINGS.md`](LONGCTX_FINDINGS.md).
|
|
@@ -206,7 +207,32 @@ All SFT runs above were re-run with the fix. Quality held: 3B −0.114 (was −0
|
|
|
206
207
|
Reproduce: `python scripts/compare_peft.py --model checkpoints/qwen3b_bnb4bit --steps 30`
|
|
207
208
|
and `... --model checkpoints/qwen14b_nf4 --steps 30`.
|
|
208
209
|
|
|
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.
|
|
235
|
+
|
|
210
236
|
## What this does not do
|
|
211
237
|
|
|
212
238
|
- **2k context does not fit** on 6 GB. It is ~0.6 GB short: with `--activation-cache cpu`
|
|
@@ -255,6 +281,7 @@ URLs. The engine lived at `experiments/exp54_disk_qlora.py` + `lcsa/` until the
|
|
|
255
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)
|
|
256
282
|
- [The same 32B post on Medium](https://medium.com/@myredditacc9393/fine-tuning-a-32b-model-on-a-6-gb-laptop-gpu-e749df447229)
|
|
257
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)
|
|
258
285
|
|
|
259
286
|
## License
|
|
260
287
|
|
|
@@ -25,7 +25,8 @@ The 32B weights are **19.2 GB**. They never fully live in VRAM. At 1024 tokens/s
|
|
|
25
25
|
throughput is **3.1×** the 128-token rate, because the per-step I/O is amortised over
|
|
26
26
|
more tokens. 50 steps of Dolly-15k SFT moved eval loss **1.8755 → 0.9661**.
|
|
27
27
|
|
|
28
|
-
**Start with [`
|
|
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,
|
|
29
30
|
the six traps, and which numbers are real. The measurement protocol, the discarded rows
|
|
30
31
|
and the correction of an earlier wrong claim ("8.6× / 100 tok/s") are in
|
|
31
32
|
[`LONGCTX_FINDINGS.md`](LONGCTX_FINDINGS.md).
|
|
@@ -176,7 +177,32 @@ All SFT runs above were re-run with the fix. Quality held: 3B −0.114 (was −0
|
|
|
176
177
|
Reproduce: `python scripts/compare_peft.py --model checkpoints/qwen3b_bnb4bit --steps 30`
|
|
177
178
|
and `... --model checkpoints/qwen14b_nf4 --steps 30`.
|
|
178
179
|
|
|
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.
|
|
205
|
+
|
|
180
206
|
## What this does not do
|
|
181
207
|
|
|
182
208
|
- **2k context does not fit** on 6 GB. It is ~0.6 GB short: with `--activation-cache cpu`
|
|
@@ -225,6 +251,7 @@ URLs. The engine lived at `experiments/exp54_disk_qlora.py` + `lcsa/` until the
|
|
|
225
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)
|
|
226
252
|
- [The same 32B post on Medium](https://medium.com/@myredditacc9393/fine-tuning-a-32b-model-on-a-6-gb-laptop-gpu-e749df447229)
|
|
227
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)
|
|
228
255
|
|
|
229
256
|
## License
|
|
230
257
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "streamft"
|
|
7
|
-
version = "0.2.
|
|
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
|
-
|
|
93
|
-
|
|
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(
|
|
84
|
-
dst =
|
|
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(
|
|
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(
|
|
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(
|
|
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 =
|
|
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
|
-
|
|
444
|
-
|
|
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
|
-
|
|
47
|
-
|
|
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:
|
|
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:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: streamft
|
|
3
|
-
Version: 0.2.
|
|
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
|
|
@@ -55,7 +55,8 @@ The 32B weights are **19.2 GB**. They never fully live in VRAM. At 1024 tokens/s
|
|
|
55
55
|
throughput is **3.1×** the 128-token rate, because the per-step I/O is amortised over
|
|
56
56
|
more tokens. 50 steps of Dolly-15k SFT moved eval loss **1.8755 → 0.9661**.
|
|
57
57
|
|
|
58
|
-
**Start with [`
|
|
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,
|
|
59
60
|
the six traps, and which numbers are real. The measurement protocol, the discarded rows
|
|
60
61
|
and the correction of an earlier wrong claim ("8.6× / 100 tok/s") are in
|
|
61
62
|
[`LONGCTX_FINDINGS.md`](LONGCTX_FINDINGS.md).
|
|
@@ -206,7 +207,32 @@ All SFT runs above were re-run with the fix. Quality held: 3B −0.114 (was −0
|
|
|
206
207
|
Reproduce: `python scripts/compare_peft.py --model checkpoints/qwen3b_bnb4bit --steps 30`
|
|
207
208
|
and `... --model checkpoints/qwen14b_nf4 --steps 30`.
|
|
208
209
|
|
|
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.
|
|
235
|
+
|
|
210
236
|
## What this does not do
|
|
211
237
|
|
|
212
238
|
- **2k context does not fit** on 6 GB. It is ~0.6 GB short: with `--activation-cache cpu`
|
|
@@ -255,6 +281,7 @@ URLs. The engine lived at `experiments/exp54_disk_qlora.py` + `lcsa/` until the
|
|
|
255
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)
|
|
256
282
|
- [The same 32B post on Medium](https://medium.com/@myredditacc9393/fine-tuning-a-32b-model-on-a-6-gb-laptop-gpu-e749df447229)
|
|
257
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)
|
|
258
285
|
|
|
259
286
|
## License
|
|
260
287
|
|
|
@@ -1,164 +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)
|
|
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)
|
|
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.1/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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|