leanq 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- leanq-0.1.0/LICENSE +21 -0
- leanq-0.1.0/PKG-INFO +253 -0
- leanq-0.1.0/README.md +225 -0
- leanq-0.1.0/README_EN.md +221 -0
- leanq-0.1.0/leanq/__init__.py +1 -0
- leanq-0.1.0/leanq/functional.py +146 -0
- leanq-0.1.0/leanq/inference.py +65 -0
- leanq-0.1.0/leanq/layers.py +80 -0
- leanq-0.1.0/leanq/quant_ops.py +123 -0
- leanq-0.1.0/leanq/tensor.py +24 -0
- leanq-0.1.0/leanq/w4.py +32 -0
- leanq-0.1.0/leanq.egg-info/PKG-INFO +253 -0
- leanq-0.1.0/leanq.egg-info/SOURCES.txt +25 -0
- leanq-0.1.0/leanq.egg-info/dependency_links.txt +1 -0
- leanq-0.1.0/leanq.egg-info/requires.txt +14 -0
- leanq-0.1.0/leanq.egg-info/top_level.txt +1 -0
- leanq-0.1.0/pyproject.toml +47 -0
- leanq-0.1.0/setup.cfg +4 -0
- leanq-0.1.0/tests/test_backward_int8.py +104 -0
- leanq-0.1.0/tests/test_e2e_smoke.py +57 -0
- leanq-0.1.0/tests/test_functional.py +50 -0
- leanq-0.1.0/tests/test_inference.py +68 -0
- leanq-0.1.0/tests/test_layers.py +68 -0
- leanq-0.1.0/tests/test_quant_ops.py +37 -0
- leanq-0.1.0/tests/test_smoothquant.py +80 -0
- leanq-0.1.0/tests/test_tensor.py +21 -0
- leanq-0.1.0/tests/test_w4.py +21 -0
leanq-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 leanq 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.
|
leanq-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: leanq
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: W4A8 quantization for LoRA fine-tuning and on-device inference on consumer GPUs (Ampere, no FP8 needed)
|
|
5
|
+
Author: leanq contributors
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Antithesismen/leanq
|
|
8
|
+
Project-URL: Repository, https://github.com/Antithesismen/leanq
|
|
9
|
+
Project-URL: Issues, https://github.com/Antithesismen/leanq/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/Antithesismen/leanq/commits/master
|
|
11
|
+
Keywords: quantization,int8,w4a8,lora,peft,pytorch,ampere,edge-inference,llm,memory-efficient
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
18
|
+
Classifier: Intended Audience :: Developers
|
|
19
|
+
Classifier: Intended Audience :: Science/Research
|
|
20
|
+
Classifier: Operating System :: OS Independent
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: torch>=2.1.0
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
27
|
+
Provides-Extra: fused
|
|
28
|
+
Requires-Dist: triton>=3.0; sys_platform == "linux" and extra == "fused"
|
|
29
|
+
Provides-Extra: fused-windows
|
|
30
|
+
Requires-Dist: triton-windows; sys_platform == "win32" and extra == "fused-windows"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
# leanq
|
|
34
|
+
|
|
35
|
+
**English** | [中文](README.md)
|
|
36
|
+
|
|
37
|
+
**A quantization library for training and on-device inference of large models on consumer GPUs** (Ampere and later, no FP8 hardware required).
|
|
38
|
+
|
|
39
|
+
leanq implements **W4A8**: weights stored in 4-bit, activations computed in 8-bit. It makes **fine-tuning** faster and lighter on a single consumer card, and is specifically tuned for **edge / on-device inference**.
|
|
40
|
+
|
|
41
|
+
> QLoRA = W4A16. leanq provides the missing half — **A8**.
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Two use cases, each with its own optimization
|
|
46
|
+
|
|
47
|
+
### 1. Fine-tuning (LoRA)
|
|
48
|
+
|
|
49
|
+
Swap `nn.Linear` for `W4A8Linear`, keep your LoRA setup, and the base weight is frozen to int8.
|
|
50
|
+
|
|
51
|
+
- Forward runs on INT8 tensor cores — measured **2× faster** than bf16;
|
|
52
|
+
- Backward stays in bf16 (optional `use_int8_bwd`);
|
|
53
|
+
- **Validated on a real 3B model × real task: 1.11× faster, 30% less VRAM, accuracy unchanged.**
|
|
54
|
+
|
|
55
|
+
### 2. Edge / on-device inference
|
|
56
|
+
|
|
57
|
+
**This is where leanq pays off the most.** Inference is forward-only — no backward pass to dilute the gain — so the INT8 forward speedup lands in full.
|
|
58
|
+
|
|
59
|
+
- **1.6× faster forward** at M=2048 on a laptop Ampere GPU; **up to ~4×** for larger shapes;
|
|
60
|
+
- 4-bit / 8-bit weights translate directly into a **deployable memory footprint** — bigger models or longer context on memory-constrained devices;
|
|
61
|
+
- Two built-in guardrails: falls back to bf16 when the input is too short (<2048 tokens) or free VRAM is low (<1 GiB). It never crashes silently and never slows down without telling you;
|
|
62
|
+
- Zero-copy forward path — no model surgery, just replace and run.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from leanq.inference import W4A8InferenceLinear
|
|
66
|
+
|
|
67
|
+
eng = W4A8InferenceLinear.from_linear(base) # replace one layer
|
|
68
|
+
y = eng(x) # picks int8 or bf16 automatically
|
|
69
|
+
eng.last_route # inspect the chosen route
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## Why leanq
|
|
75
|
+
|
|
76
|
+
Most quantization tooling assumes you have FP8 tensor cores (H100 / Ada / Hopper). On a mainstream Ampere card (RTX 30-series, RTX A-series) there is no FP8 path — but there *is* an INT8 tensor core path that is frequently faster than bf16. leanq packages that path, plus the layout and quantization details that are easy to get wrong, into a small drop-in library.
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## Install
|
|
81
|
+
|
|
82
|
+
**Install from source for now** (not yet on PyPI):
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
git clone https://github.com/Antithesismen/leanq.git
|
|
86
|
+
cd leanq
|
|
87
|
+
pip install -e .
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
If `git clone` is slow, use a mirror:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
git clone https://gh-proxy.com/https://github.com/Antithesismen/leanq.git
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
**Requirements**
|
|
97
|
+
|
|
98
|
+
- Python 3.10+
|
|
99
|
+
- PyTorch 2.1+ with CUDA
|
|
100
|
+
- An Ampere-or-newer NVIDIA GPU (INT8 tensor cores)
|
|
101
|
+
- `triton` is optional but recommended — it enables the fused quantization kernel
|
|
102
|
+
|
|
103
|
+
**Verify the install** (worth doing first):
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
pytest tests/ -v # all tests should pass
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
> The tests require CUDA. To just check that the package imports, run
|
|
110
|
+
> `python -c "import leanq; print(leanq.__doc__)"`.
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
## Quick start
|
|
115
|
+
|
|
116
|
+
### Fine-tuning with LoRA
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
import torch
|
|
120
|
+
from leanq.layers import W4A8Linear
|
|
121
|
+
|
|
122
|
+
base = torch.nn.Linear(4096, 11008, dtype=torch.bfloat16, device="cuda")
|
|
123
|
+
layer = W4A8Linear.from_linear(base, lora_r=16)
|
|
124
|
+
|
|
125
|
+
y = layer(x) # int8 forward
|
|
126
|
+
loss.backward() # gradients flow into LoRA / bias only
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
`from_linear` keeps the original bias and freezes the base weight in int8; only the LoRA branch (and bias) stay trainable.
|
|
130
|
+
|
|
131
|
+
### Replacing a whole model
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from leanq.layers import W4A8Linear
|
|
135
|
+
|
|
136
|
+
def replace_linears(module, lora_r=16):
|
|
137
|
+
"""Collect first, replace second — replacing while iterating will recurse
|
|
138
|
+
into the LoRA layers the replacement itself creates."""
|
|
139
|
+
targets = [(p, n) for p, m in module.named_modules()
|
|
140
|
+
for n, c in m.named_children() if type(c) is torch.nn.Linear]
|
|
141
|
+
for parent, name in targets:
|
|
142
|
+
old = getattr(parent, name)
|
|
143
|
+
setattr(parent, name, W4A8Linear.from_linear(old, lora_r=lora_r))
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Keep these layers in bf16:
|
|
147
|
+
|
|
148
|
+
- **`lm_head`** — its output dimension is the vocabulary size, which is usually not a multiple of 8, so the INT8 kernel rejects it.
|
|
149
|
+
- **Vision towers / projectors** in multimodal models — quantizing them is optional and outside the validated scope.
|
|
150
|
+
|
|
151
|
+
### Inference
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
from leanq.inference import W4A8InferenceLinear
|
|
155
|
+
|
|
156
|
+
eng = W4A8InferenceLinear.from_linear(base)
|
|
157
|
+
y = eng(x)
|
|
158
|
+
eng.last_route # "int8" or "bf16"
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Two guardrails run automatically:
|
|
162
|
+
|
|
163
|
+
- Inputs with fewer than 2048 tokens fall back to bf16 (quantization overhead would dominate).
|
|
164
|
+
- If free VRAM drops below 1 GiB, it falls back to bf16 instead of failing.
|
|
165
|
+
|
|
166
|
+
> Deployment note: inference has no backward pass, no optimizer state, and usually batch size 1 — so memory pressure is far lower than during training. The savings from 4-bit / 8-bit weights translate directly into a larger model or a longer context that actually fits on the device.
|
|
167
|
+
|
|
168
|
+
---
|
|
169
|
+
|
|
170
|
+
## Options
|
|
171
|
+
|
|
172
|
+
| Option | Default | Meaning |
|
|
173
|
+
|---|---|---|
|
|
174
|
+
| `lora_r` | 16 | LoRA rank. Set to 0 for a pure quantized layer. |
|
|
175
|
+
| `lora_alpha` | 32 | LoRA scaling. |
|
|
176
|
+
| `use_int8_bwd` | `False` | Also run the backward GEMM in int8 (a bit faster, lower training accuracy over long runs). |
|
|
177
|
+
| `smooth_scale` | `None` | Enable SmoothQuant smoothing (see the dedicated section below). Requires offline calibration. |
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
## SmoothQuant (handling activation outliers)
|
|
182
|
+
|
|
183
|
+
Large-model activations contain a few channels with extreme magnitude — we measured channels whose peak value was **over 1000× the median channel**. With plain per-token scaling, those few channels inflate the scale and squeeze every other channel into a fraction of the int8 grid. On a synthetic layer with one 100× outlier channel, output error was **9.4%** with plain scaling versus **under 1%** with smoothing.
|
|
184
|
+
|
|
185
|
+
leanq implements SmoothQuant-style smoothing: a per-input-channel factor `s_k` is folded into the weight (`w * s_k`) and divided out of the activation (`x / s_k`). The two cancel mathematically, so the layer's output is unchanged — but the activation now has a well-behaved distribution.
|
|
186
|
+
|
|
187
|
+
### How to use it
|
|
188
|
+
|
|
189
|
+
Smoothing needs an `s_k` vector per layer, which must be **calibrated** from real activations first. Calibration is a one-time offline pass: run a few dozen representative samples through the model, record each layer's per-channel activation maxima, and take `s_k = cmax ** 0.5`.
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
import torch
|
|
193
|
+
from leanq.layers import W4A8Linear
|
|
194
|
+
|
|
195
|
+
# 1) Calibrate: collect per-input-channel activation maxima for each layer.
|
|
196
|
+
# (In your own code: hook the input of each nn.Linear, run N samples, take abs().amax(dim=0).)
|
|
197
|
+
cmax = torch.zeros(in_features, device="cuda")
|
|
198
|
+
# ... accumulate across calibration batches: cmax = max(cmax, x.abs().amax(dim=0))
|
|
199
|
+
|
|
200
|
+
# 2) Derive the smoothing factor (alpha=0.5 is the recommended default).
|
|
201
|
+
s_k = cmax.clamp(min=1e-8).pow(0.5)
|
|
202
|
+
|
|
203
|
+
# 3) Build the layer with smoothing enabled.
|
|
204
|
+
layer = W4A8Linear.from_linear(base, lora_r=16, smooth_scale=s_k)
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
`alpha` (the exponent) controls how much difficulty is moved from activations to weights:
|
|
208
|
+
|
|
209
|
+
| `alpha` | Effect |
|
|
210
|
+
|---|---|
|
|
211
|
+
| 0 | no smoothing (equivalent to plain per-token scaling) |
|
|
212
|
+
| **0.5** | **recommended** — measured best across layers |
|
|
213
|
+
| 1.0 | too aggressive: weight error grows enough to cancel the gain |
|
|
214
|
+
|
|
215
|
+
### Notes
|
|
216
|
+
|
|
217
|
+
- Calibration costs one forward pass over a small sample set (a few dozen samples is enough).
|
|
218
|
+
- `s_k` is stored on the layer as a buffer and saved with the model, so it survives save/load.
|
|
219
|
+
- The factor is **static**, derived offline. It does not adapt at runtime — if your fine-tuning shifts the activation distribution far from the calibration set, re-calibrate.
|
|
220
|
+
- If you skip calibration entirely, the library works fine without smoothing; you just lose the outlier protection.
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## Things that will bite you
|
|
225
|
+
|
|
226
|
+
These are real, verified pitfalls — worth reading before you integrate.
|
|
227
|
+
|
|
228
|
+
**1. `lm_head` must stay in bf16.** Its output dim is the vocabulary size (often not a multiple of 8), and the INT8 kernel requires the reduction dimension to be a multiple of 8.
|
|
229
|
+
|
|
230
|
+
**2. Keep the bias.** If you write your own replacement layer, do not drop `nn.Linear.bias`. Many transformer blocks have one. A dropped bias shifts every output and silently degrades quality — it looks like "quantization is inaccurate" but it is a bug.
|
|
231
|
+
|
|
232
|
+
**3. Minimum sizes.** The INT8 kernel requires more than 16 rows and a reduction dimension that is a multiple of 8. Very small layers should stay in bf16.
|
|
233
|
+
|
|
234
|
+
**4. Quantization granularity matters more than bit-width.** Activations in LLMs have extreme channel outliers (we measured high-to-median channel ratios of over 1000×). Plain per-token scaling is strongly affected by these; SmoothQuant-style smoothing handles them well — see the section above for setup.
|
|
235
|
+
|
|
236
|
+
**5. Long runs are less validated than short ones.** See the limitations section.
|
|
237
|
+
|
|
238
|
+
---
|
|
239
|
+
|
|
240
|
+
## Scope and limitations
|
|
241
|
+
|
|
242
|
+
leanq is tuned for a specific use case: **LoRA fine-tuning of models at the 3B-parameter scale and up on a single consumer GPU, plus inference.**
|
|
243
|
+
|
|
244
|
+
- **Small models or small batches**: not beneficial. Fixed per-layer quantization overhead dominates; measured throughput can be *worse* than bf16.
|
|
245
|
+
- **Training with 12 GB or less VRAM**: 4-bit base weights (NF4) plus gradient checkpointing is usually the better choice.
|
|
246
|
+
- **Full-parameter pre-training from scratch**: out of scope.
|
|
247
|
+
- **Long training runs**: current validation covers a few hundred steps. If you plan multi-thousand-step runs, validate on your own task first.
|
|
248
|
+
|
|
249
|
+
---
|
|
250
|
+
|
|
251
|
+
## License
|
|
252
|
+
|
|
253
|
+
MIT
|
leanq-0.1.0/README.md
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
# leanq
|
|
2
|
+
|
|
3
|
+
[English](README_EN.md) | **中文**
|
|
4
|
+
|
|
5
|
+
**面向消费级 GPU 的大模型量化训练 / 端侧推理库**(Ampere 及以后架构,无需 FP8 硬件)。
|
|
6
|
+
|
|
7
|
+
leanq 实现 **W4A8**:权重以 4bit 存储、激活以 8bit 计算。让你在单张消费级显卡上更快、更省显存地**微调**大模型,并为**端侧 / 边缘推理**做专门优化。
|
|
8
|
+
|
|
9
|
+
> QLoRA = W4A16,leanq 补上缺少的那一半 —— **A8**。
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 两个场景,各有专门的优化
|
|
14
|
+
|
|
15
|
+
### 场景一:微调训练(LoRA)
|
|
16
|
+
|
|
17
|
+
用 `W4A8Linear` 替换 `nn.Linear`,LoRA 配置不变,基座权重冻结为 int8。
|
|
18
|
+
|
|
19
|
+
- 前向走 INT8 张量核心,实测比 bf16 快 **2 倍**;
|
|
20
|
+
- 反向保持 bf16 精度(`use_int8_bwd` 可选开);
|
|
21
|
+
- **真实 3B 模型 × 真实任务实测:1.11x 更快、省 30% 显存、精度持平**。
|
|
22
|
+
|
|
23
|
+
### 场景二:端侧 / 边缘推理
|
|
24
|
+
|
|
25
|
+
**这是 leanq 收益最大的场景。** 推理阶段只有前向、没有反向,所以前向的 INT8 加速可以**全额兑现**,不会被反向拖累摊薄。
|
|
26
|
+
|
|
27
|
+
- **前向加速 1.6 倍起**(M=2048 本机实测),更大输入形状可达 **4 倍量级**;
|
|
28
|
+
- 4bit/8bit 权重直接换取**可部署的显存占用**——显存受限的边缘设备能装下更大的模型;
|
|
29
|
+
- 内置**双护栏**:输入过短(<2048 token)或空闲显存不足(<1 GiB)时自动回退 bf16,不会崩、也不会悄悄变慢;
|
|
30
|
+
- 零拷贝前向路径,无需改模型结构,替换完直接跑。
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from leanq.inference import W4A8InferenceLinear
|
|
34
|
+
|
|
35
|
+
eng = W4A8InferenceLinear.from_linear(base) # 一层替换
|
|
36
|
+
y = eng(x) # 自动选择 int8 / bf16
|
|
37
|
+
eng.last_route # 可查询本次走的路线
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## 为什么需要 leanq
|
|
43
|
+
|
|
44
|
+
市面上多数量化工具假设你有 FP8 张量核心(H100 / Ada / Hopper)。但主流的 Ampere 显卡(RTX 30 系列、RTX A 系列)没有 FP8 通路 —— 不过它有 **INT8 张量核心**,在很多形状下比 bf16 更快。leanq 把这套通路,连同那些容易踩错的布局与量化细节,封装成一个小而可直接替换的库。
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 安装
|
|
49
|
+
|
|
50
|
+
**目前从 GitHub 源码安装**(尚未发布到 PyPI):
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
git clone https://github.com/Antithesismen/leanq.git
|
|
54
|
+
cd leanq
|
|
55
|
+
pip install -e .
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
如果 `git clone` 慢,可以用镜像:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
git clone https://gh-proxy.com/https://github.com/Antithesismen/leanq.git
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**环境要求**
|
|
65
|
+
|
|
66
|
+
- Python 3.10+
|
|
67
|
+
- PyTorch 2.1+ 且带 CUDA
|
|
68
|
+
- NVIDIA Ampere 或更新架构的显卡(需要 INT8 张量核心)
|
|
69
|
+
- `triton` 可选但推荐 —— 装了才能启用融合量化内核
|
|
70
|
+
|
|
71
|
+
**验证安装**(建议先跑这一步,确认环境没问题):
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
pytest tests/ -v # 应全部通过
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
> 注意:测试需要 CUDA。如果只是想先看看代码能不能导入,可以运行
|
|
78
|
+
> `python -c "import leanq; print(leanq.__doc__)"`。
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## 快速开始
|
|
83
|
+
|
|
84
|
+
### 用 LoRA 微调
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
import torch
|
|
88
|
+
from leanq.layers import W4A8Linear
|
|
89
|
+
|
|
90
|
+
base = torch.nn.Linear(4096, 11008, dtype=torch.bfloat16, device="cuda")
|
|
91
|
+
layer = W4A8Linear.from_linear(base, lora_r=16)
|
|
92
|
+
|
|
93
|
+
y = layer(x) # int8 前向
|
|
94
|
+
loss.backward() # 梯度只流进 LoRA / bias
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
`from_linear` 会保留原始 bias,并把基座权重冻结为 int8;只有 LoRA 分支(和 bias)保持可训练。
|
|
98
|
+
|
|
99
|
+
### 替换整个模型
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
from leanq.layers import W4A8Linear
|
|
103
|
+
|
|
104
|
+
def replace_linears(module, lora_r=16):
|
|
105
|
+
"""先收集、再替换 —— 边遍历边替换会递归进替换自身新建的 LoRA 层。"""
|
|
106
|
+
targets = [(p, n) for p, m in module.named_modules()
|
|
107
|
+
for n, c in m.named_children() if type(c) is torch.nn.Linear]
|
|
108
|
+
for parent, name in targets:
|
|
109
|
+
old = getattr(parent, name)
|
|
110
|
+
setattr(parent, name, W4A8Linear.from_linear(old, lora_r=lora_r))
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
以下层请保持在 bf16:
|
|
114
|
+
|
|
115
|
+
- **`lm_head`** —— 它的输出维等于词表大小,通常不是 8 的倍数,INT8 内核会直接拒绝;
|
|
116
|
+
- **多模态模型的视觉塔 / 投影层** —— 是否量化可选,且不在已验证范围内。
|
|
117
|
+
|
|
118
|
+
### 推理
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from leanq.inference import W4A8InferenceLinear
|
|
122
|
+
|
|
123
|
+
eng = W4A8InferenceLinear.from_linear(base)
|
|
124
|
+
y = eng(x)
|
|
125
|
+
eng.last_route # "int8" 或 "bf16"
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
两条护栏自动生效:
|
|
129
|
+
|
|
130
|
+
- 输入少于 2048 token 时回退 bf16(否则量化开销盖过收益);
|
|
131
|
+
- 空闲显存低于 1 GiB 时回退 bf16,而不是直接报错。
|
|
132
|
+
|
|
133
|
+
> 端侧部署提示:推理场景没有反向、没有优化器状态、batch 通常为 1,显存压力远小于训练,
|
|
134
|
+
> 因此 4bit/8bit 权重带来的显存节省可以直接换算成"能部署更大的模型"或"更长的上下文"。
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## 参数
|
|
139
|
+
|
|
140
|
+
| 参数 | 默认值 | 含义 |
|
|
141
|
+
|---|---|---|
|
|
142
|
+
| `lora_r` | 16 | LoRA 秩。设为 0 则为纯量化层。 |
|
|
143
|
+
| `lora_alpha` | 32 | LoRA 缩放系数。 |
|
|
144
|
+
| `use_int8_bwd` | `False` | 反向 GEMM 也走 int8(略快,但长训精度有损)。 |
|
|
145
|
+
| `smooth_scale` | `None` | 启用 SmoothQuant 平滑,需先离线校准(见下方独立小节)。 |
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## SmoothQuant(处理激活异常值)
|
|
150
|
+
|
|
151
|
+
大模型的激活中存在少数幅值极大的通道 —— 我们实测到峰值达到**中位通道的 1000 倍以上**。用朴素的逐 token 缩放时,这几个通道会把 scale 撑大,其余通道全被挤进 int8 格子的零头里。在一个注入 100 倍异常通道的合成层上,输出误差 **9.4%**;开启平滑后降到 **1% 以下**。
|
|
152
|
+
|
|
153
|
+
leanq 实现的是 SmoothQuant 式平滑:逐输入通道的因子 `s_k` 折进权重(`w * s_k`),同时从激活中除掉(`x / s_k`)。两者在数学上相互抵消,所以层的输出不变 —— 但激活的分布变得乖巧了。
|
|
154
|
+
|
|
155
|
+
### 怎么用
|
|
156
|
+
|
|
157
|
+
平滑需要每层一个 `s_k` 向量,它必须**先从真实激活上校准**得到。校准是一次性离线过程:让模型跑几十条有代表性的样本,记录每层逐通道的激活最大值,取 `s_k = cmax ** 0.5`。
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
import torch
|
|
161
|
+
from leanq.layers import W4A8Linear
|
|
162
|
+
|
|
163
|
+
# 1) 校准:采集每层逐输入通道的激活最大值
|
|
164
|
+
# (在你自己的代码里:钩住每个 nn.Linear 的输入,跑 N 条样本,取 abs().amax(dim=0))
|
|
165
|
+
cmax = torch.zeros(in_features, device="cuda")
|
|
166
|
+
# ... 跨校准批次累积:cmax = max(cmax, x.abs().amax(dim=0))
|
|
167
|
+
|
|
168
|
+
# 2) 推导平滑因子(alpha=0.5 是推荐默认值)
|
|
169
|
+
s_k = cmax.clamp(min=1e-8).pow(0.5)
|
|
170
|
+
|
|
171
|
+
# 3) 构建启用平滑的层
|
|
172
|
+
layer = W4A8Linear.from_linear(base, lora_r=16, smooth_scale=s_k)
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
`alpha`(那个指数)控制把多少难度从激活搬到权重上:
|
|
176
|
+
|
|
177
|
+
| `alpha` | 效果 |
|
|
178
|
+
|---|---|
|
|
179
|
+
| 0 | 不平滑(等价于朴素逐 token 缩放) |
|
|
180
|
+
| **0.5** | **推荐** —— 实测跨层表现最优 |
|
|
181
|
+
| 1.0 | 过于激进:权重误差增长到会把收益抵消掉 |
|
|
182
|
+
|
|
183
|
+
### 注意事项
|
|
184
|
+
|
|
185
|
+
- 校准的成本是一次小样本集的前向(几十条样本足够);
|
|
186
|
+
- `s_k` 以 buffer 形式存在层上,会随模型一起保存,所以存盘加载后不会丢;
|
|
187
|
+
- 这个因子是**静态的**,来自离线统计,运行时不会自适应 —— 如果你的微调让激活分布偏离校准集太远,需要重新校准;
|
|
188
|
+
- 完全不做校准也能正常使用,只是少了异常值保护。
|
|
189
|
+
|
|
190
|
+
---
|
|
191
|
+
|
|
192
|
+
## 容易踩的坑
|
|
193
|
+
|
|
194
|
+
这些都是真实踩过、验证过的坑 —— 集成前值得读一遍。
|
|
195
|
+
|
|
196
|
+
**1. `lm_head` 必须留在 bf16。** 它的输出维是词表大小(通常不是 8 的倍数),而 INT8 内核要求归约维是 8 的倍数。
|
|
197
|
+
|
|
198
|
+
**2. 千万保住 bias。** 如果你自己写替换层,不要丢掉 `nn.Linear.bias`。很多 transformer 层都带 bias,丢掉它会让每层输出系统性偏移、精度悄悄变差 —— 表现看起来像"量化不准",实际上是 bug。
|
|
199
|
+
|
|
200
|
+
**3. 有最小尺寸限制。** INT8 内核要求行数大于 16、归约维是 8 的倍数。很小的层请留在 bf16。
|
|
201
|
+
|
|
202
|
+
**4. 量化粒度比比特数更关键。** LLM 的激活存在极端的通道异常值(我们实测通道峰值 / 中位数超过 1000 倍)。朴素逐 token 缩放深受其害;SmoothQuant 式平滑能很好地处理 —— 配置方法见上一节。
|
|
203
|
+
|
|
204
|
+
**5. 长训练验证不如短训练充分。** 详见"适用范围"。
|
|
205
|
+
|
|
206
|
+
---
|
|
207
|
+
|
|
208
|
+
## 适用范围与限制
|
|
209
|
+
|
|
210
|
+
leanq 针对一个特定场景调优:**在单张消费级显卡上,对 3B 及以上规模的模型做 LoRA 微调,以及推理。**
|
|
211
|
+
|
|
212
|
+
- **小模型 / 小 batch**:没有收益。逐层的量化固定开销会占主导,实测吞吐甚至可能**比 bf16 更差**;
|
|
213
|
+
- **显存 ≤ 12 GB 的训练**:4bit 基座权重(NF4)+ 梯度检查点通常是更好的选择;
|
|
214
|
+
- **全参数从头预训练**:不在范围内;
|
|
215
|
+
- **长训练**:目前只验证了几百步。如果你打算跑几千步以上,请先在自己的任务上验证。
|
|
216
|
+
|
|
217
|
+
---
|
|
218
|
+
|
|
219
|
+
## 许可证
|
|
220
|
+
|
|
221
|
+
MIT
|
|
222
|
+
|
|
223
|
+
---
|
|
224
|
+
|
|
225
|
+
**注**:本库的完整实测数据、工程细节与设计决策记录在 `docs/README_INTERNAL.md`(中文,内部文档)。开源英文版见 [README_EN.md](README_EN.md)。
|