leanq 0.1.0__py3-none-any.whl
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/__init__.py +1 -0
- leanq/functional.py +146 -0
- leanq/inference.py +65 -0
- leanq/layers.py +80 -0
- leanq/quant_ops.py +123 -0
- leanq/tensor.py +24 -0
- leanq/w4.py +32 -0
- leanq-0.1.0.dist-info/METADATA +253 -0
- leanq-0.1.0.dist-info/RECORD +12 -0
- leanq-0.1.0.dist-info/WHEEL +5 -0
- leanq-0.1.0.dist-info/licenses/LICENSE +21 -0
- leanq-0.1.0.dist-info/top_level.txt +1 -0
leanq/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""W4A8 LoRA fine-tuning library for consumer Ampere GPUs (no FP8 needed)."""
|
leanq/functional.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""int8_linear: 前向激活与权重都量化到 int8,走 _int_mm;梯度用 STE(直通)。
|
|
2
|
+
|
|
3
|
+
快速路径布局铁律(本机对照实验钉死,2026-11-29):
|
|
4
|
+
- _int_mm(A, B) 要求:A 行主序、B 逻辑 (K,N) 且 stride=(1,K)(列连续)。
|
|
5
|
+
- nn.Linear 权重 (N,K) 行主序存储时,w_q.t() 视图的物理内存恰好满足 B 的要求
|
|
6
|
+
——零拷贝、零物化。禁止画蛇添足加 .contiguous()(会把 stride 弄回 (N,1)
|
|
7
|
+
掉进 3 倍慢速路径,实测 1.48ms vs 4.72ms)。
|
|
8
|
+
- 显存纪律:不常驻 bf16 权重副本;反向 W 从 int8 现场反量化,用完即释。
|
|
9
|
+
- MVP 反向 dX 用反量化 bf16 GEMM(正确性优先);int8 反向留 MVP 后。
|
|
10
|
+
"""
|
|
11
|
+
import torch
|
|
12
|
+
|
|
13
|
+
from .quant_ops import fused_quantize
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def check_int8_dims(N, K, where=""):
|
|
17
|
+
"""_int_mm 的硬件约束:K(归约维)必须是 8 的倍数,否则内核直接拒绝。
|
|
18
|
+
提前给出可读报错,避免底层 mat2.size(1) 报错难懂。
|
|
19
|
+
典型踩坑:lm_head 输出维 = 词表大小(如 152681),非 8 倍数 → 这层必须留 bf16。"""
|
|
20
|
+
if K % 8 != 0:
|
|
21
|
+
raise ValueError(
|
|
22
|
+
f"{where} 维度不满足 INT8 要求: K(输入维)={K} 不是 8 的倍数。"
|
|
23
|
+
f"该层请保留 bf16(典型场景:lm_head 的词表投影维不是 8 的倍数)。")
|
|
24
|
+
return True
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def prepare_weight(w_bf16, smooth_scale=None):
|
|
28
|
+
"""(N,K) bf16 → (w_q: (N,K) int8 行主序, w_scale: (N,1) fp16)。一次性成本。
|
|
29
|
+
保持 nn.Linear 原生布局;forward 用 w_q.t() 视图直接命中快速路径。
|
|
30
|
+
|
|
31
|
+
smooth_scale: SmoothQuant 平滑因子 s_k,形状 (K,) 或 (1,K),逐**输入通道**。
|
|
32
|
+
传了就按 w_eff = w * s_k 量化(把激活的通道异常值难度搬到权重侧)。
|
|
33
|
+
实测(lora_test/verify_smoothquant.py,真实激活+权重):
|
|
34
|
+
alpha=0.5 时输出误差 11.73%/8.14%/6.07% → 3.60%/2.38%/2.09%(降 65~71%);
|
|
35
|
+
权重误差仅从 1.2% 升至 2.4%,激活误差从 8.4% 降至 3.5%,负担转移划算。
|
|
36
|
+
注意:调用方必须同时在激活侧做 x / s_k(见 Int8LinearFn 的 smooth_scale 参数),
|
|
37
|
+
否则数值不正确(数学上 w*s_k 与 x/s_k 必须成对出现)。"""
|
|
38
|
+
N, K = w_bf16.shape
|
|
39
|
+
check_int8_dims(N, K, where="prepare_weight")
|
|
40
|
+
w = w_bf16
|
|
41
|
+
if smooth_scale is not None:
|
|
42
|
+
s = smooth_scale.reshape(-1).to(w_bf16.device).to(torch.float32)
|
|
43
|
+
if s.numel() != K:
|
|
44
|
+
raise ValueError(f"smooth_scale 长度 {s.numel()} 与输入维 K={K} 不符")
|
|
45
|
+
w = (w_bf16.to(torch.float32) * s.unsqueeze(0)).to(torch.bfloat16)
|
|
46
|
+
amax = w.abs().amax(dim=1, keepdim=True).to(torch.float32) # per-output-channel
|
|
47
|
+
w_scale = (amax / 127.0).clamp(min=1e-8)
|
|
48
|
+
w_q = (w.to(torch.float32) / w_scale).round().clamp(-127, 127).to(torch.int8)
|
|
49
|
+
return w_q, w_scale.to(torch.float16)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Int8LinearFn(torch.autograd.Function):
|
|
53
|
+
@staticmethod
|
|
54
|
+
def forward(ctx, x_bf16, w_q, w_scale, use_int8_bwd=False, quant_mode="pertoken",
|
|
55
|
+
smooth_scale=None):
|
|
56
|
+
shape_3d = None
|
|
57
|
+
x2d = x_bf16
|
|
58
|
+
if x_bf16.dim() == 3: # (B, S, H) → (B*S, H):_int_mm 只吃 2D
|
|
59
|
+
shape_3d = x_bf16.shape
|
|
60
|
+
x2d = x_bf16.reshape(-1, x_bf16.shape[-1])
|
|
61
|
+
# 量化策略(真实模型实测,见 lora_test/probe_act_quant.py 与 verify_smoothquant.py):
|
|
62
|
+
# LLM 激活有极强通道异常值(LocateAnything 达 1362x),朴素 per-token 误差 9.4%;
|
|
63
|
+
# 截断类方案全部更差(89%);
|
|
64
|
+
# SmoothQuant(s_k = cmax^0.5 离线统计、权重侧 w*s_k、激活侧 x/s_k)实测把
|
|
65
|
+
# 输出误差从 11.7% 降到 3.6%(降 70%),且权重误差仅 1.2%→2.4%,负担转移划算。
|
|
66
|
+
# 传了 smooth_scale 就走 SmoothQuant;否则保持原 per-token。
|
|
67
|
+
if smooth_scale is not None:
|
|
68
|
+
s = smooth_scale.reshape(-1).to(x2d.device).to(torch.float32)
|
|
69
|
+
x2d = (x2d.to(torch.float32) / s.unsqueeze(0)).to(torch.bfloat16)
|
|
70
|
+
qx = fused_quantize(x2d, mode=quant_mode if smooth_scale is None else "pertoken")
|
|
71
|
+
out_i32 = torch._int_mm(qx.data, w_q.t())
|
|
72
|
+
# dequant:qx.scale 恒为 (M,1),与 w_scale (N,1) 广播成 (M,N)。
|
|
73
|
+
# SmoothQuant 路径下权重已乘过 s_k、激活已除过 s_k,两者相互抵消,无需额外还原。
|
|
74
|
+
y = out_i32.to(torch.bfloat16) * (qx.scale.to(torch.bfloat16) * w_scale.t().to(torch.bfloat16))
|
|
75
|
+
if shape_3d is not None:
|
|
76
|
+
y = y.reshape(*shape_3d[:-1], -1)
|
|
77
|
+
|
|
78
|
+
ctx.save_for_backward(w_q, w_scale)
|
|
79
|
+
ctx.use_int8_bwd = use_int8_bwd
|
|
80
|
+
ctx.quant_mode = quant_mode
|
|
81
|
+
ctx.smooth_scale = smooth_scale
|
|
82
|
+
return y
|
|
83
|
+
|
|
84
|
+
@staticmethod
|
|
85
|
+
def backward(ctx, grad_y):
|
|
86
|
+
"""dX 反向双路线(5000 步实验结论:int8 反向致 acc 平台期落后官方 13 点,默认精度优先)。
|
|
87
|
+
- bf16 路线(默认):现场 dequant W → bf16 GEMM,梯度无损,整步速度 ~1.1x
|
|
88
|
+
- int8 路线(use_int8_bwd=True):量化dY + 列连续 requant 缓存 + _int_mm,
|
|
89
|
+
整步再 +8% 速度但长训精度有损(两次量化+requant 误差累积),供实验/速度敏感场景。
|
|
90
|
+
布局事实(locate_slowpath.py):反向 B=(N,K) 行连续 2.9ms 慢路径、列连续 0.90ms 快路径,
|
|
91
|
+
数据分布无关。int8 路线的缓存挂在 w_q._dX_cache,首步付 ~2.5ms,显存 +22MiB/层。"""
|
|
92
|
+
w_q, w_scale = ctx.saved_tensors
|
|
93
|
+
grad_x = None
|
|
94
|
+
if ctx.needs_input_grad[0]:
|
|
95
|
+
if ctx.use_int8_bwd:
|
|
96
|
+
g2d = grad_y
|
|
97
|
+
if grad_y.dim() == 3:
|
|
98
|
+
g2d = grad_y.reshape(-1, grad_y.shape[-1])
|
|
99
|
+
K = w_q.shape[1]
|
|
100
|
+
qg = fused_quantize(g2d, mode=ctx.quant_mode)
|
|
101
|
+
cache = getattr(w_q, "_dX_cache", None)
|
|
102
|
+
if cache is None:
|
|
103
|
+
w_dq = w_q.to(torch.float32) * w_scale.to(torch.float32) # (N,K) 行 dequant
|
|
104
|
+
cmax = w_dq.abs().amax(dim=0, keepdim=True)
|
|
105
|
+
col_s = (cmax / 127.0).clamp(min=1e-8)
|
|
106
|
+
wq_col = ((w_dq / col_s).round().clamp(-127, 127)).to(torch.int8)
|
|
107
|
+
wq_col_cm = wq_col.t().contiguous().t() # 逻辑 (N,K),物理 stride(1,N) 快路径
|
|
108
|
+
cache = (wq_col_cm, col_s.to(torch.bfloat16).reshape(1, K))
|
|
109
|
+
w_q._dX_cache = cache
|
|
110
|
+
wq_col_cm, col_s_bf = cache
|
|
111
|
+
out = torch._int_mm(qg.data, wq_col_cm)
|
|
112
|
+
grad_x = out.to(torch.bfloat16) * (qg.scale.to(torch.bfloat16) * col_s_bf)
|
|
113
|
+
if grad_y.dim() == 3:
|
|
114
|
+
grad_x = grad_x.reshape(*grad_y.shape[:-1], -1)
|
|
115
|
+
else:
|
|
116
|
+
# bf16 精度路线(默认):现场 dequant W (N,K),梯度无损,临时分配用完即释
|
|
117
|
+
w_dq = w_q.to(torch.bfloat16) * w_scale.to(torch.bfloat16)
|
|
118
|
+
grad_x = grad_y.to(torch.bfloat16) @ w_dq
|
|
119
|
+
# ⚠️ SmoothQuant 的梯度修正(易错点,按链式法则严格推导):
|
|
120
|
+
# 前向:x' = x / s_k(逐输入通道),W' = W * s_k(同维抵消),故 y 数值不变;
|
|
121
|
+
# 量化作用于 x',即 xq ≈ x'。
|
|
122
|
+
# 反向:需要的是对**原始 x** 的梯度。因 x' = x / s_k,
|
|
123
|
+
# 链式:dL/dx = dL/dx' * (1/s_k) = (dY @ W') / s_k。
|
|
124
|
+
# (早期写成 *s_k 是方向错了,实测梯度放大 2.6 倍,被梯度尺度测试抓住。)
|
|
125
|
+
if ctx.smooth_scale is not None:
|
|
126
|
+
s = ctx.smooth_scale.reshape(-1).to(grad_x.device).to(torch.float32)
|
|
127
|
+
grad_x = (grad_x.float() / s.unsqueeze(0)).to(torch.bfloat16)
|
|
128
|
+
if grad_y.dim() == 3:
|
|
129
|
+
grad_x = grad_x.reshape(*grad_y.shape[:-1], -1)
|
|
130
|
+
# 对 w_q/w_scale 无梯度(冻结基座,LoRA 才是可训练参数)
|
|
131
|
+
return grad_x, None, None, None, None, None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def int8_linear_prepared(x, w_q, w_scale, use_int8_bwd=False, quant_mode="pertoken",
|
|
135
|
+
smooth_scale=None):
|
|
136
|
+
"""热路径:x (M,K)/(B,S,K) bf16 + prepare_weight 产物 → y (M,N)/(B,S,N) bf16
|
|
137
|
+
use_int8_bwd: True=反向走 int8(更快但长训精度有损);默认 False=bf16 反向(精度优先)
|
|
138
|
+
quant_mode: 激活量化粒度,"pertoken"(默认);"perchannel" 仅离线实验用(前向会拒绝)
|
|
139
|
+
smooth_scale: SmoothQuant 平滑因子 (K,);传了即启用平滑(须与 prepare_weight 的配对)"""
|
|
140
|
+
return Int8LinearFn.apply(x, w_q, w_scale, use_int8_bwd, quant_mode, smooth_scale)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def int8_linear(x, w_bf16, use_int8_bwd=False, quant_mode="pertoken", smooth_scale=None):
|
|
144
|
+
"""便捷入口(每次重量化权重,仅供测试/脚本);生产用 prepare_weight + int8_linear_prepared"""
|
|
145
|
+
w_q, w_scale = prepare_weight(w_bf16, smooth_scale=smooth_scale)
|
|
146
|
+
return int8_linear_prepared(x, w_q, w_scale, use_int8_bwd, quant_mode, smooth_scale)
|
leanq/inference.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""端侧/边缘推理路线(依据三机裁决《W4A8_技术结论.md》):
|
|
2
|
+
- 推理只有前向,4x 全额吃到,无反向拖累——最大收益场景;
|
|
3
|
+
- 前向用零拷贝最快布局(wq.t() 视图,stride(1,K));
|
|
4
|
+
- 两条硬约束护栏:M<2048 量化开销吃掉收益(0.90x 净亏)→ 回退 bf16;
|
|
5
|
+
free 显存 <1GiB → 回退 bf16(拷贝成本涨 80 倍的教训);
|
|
6
|
+
- 与训练路线共享 prepare_weight / fused_quantize,无重复实现。"""
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
from .functional import prepare_weight
|
|
10
|
+
from .quant_ops import fused_quantize
|
|
11
|
+
|
|
12
|
+
M_THRESHOLD = 2048 # 小 M 不做 int8(量化开销主导,净亏)
|
|
13
|
+
FREE_MEM_THRESHOLD = 1 * 2**30 # 1 GiB
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def should_use_int8(free_bytes: int, M: int) -> bool:
|
|
17
|
+
"""路由规则表(三机裁决四硬约束之二)。"""
|
|
18
|
+
if M < M_THRESHOLD:
|
|
19
|
+
return False
|
|
20
|
+
if free_bytes < FREE_MEM_THRESHOLD:
|
|
21
|
+
return False
|
|
22
|
+
return True
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class W4A8InferenceLinear(torch.nn.Module):
|
|
26
|
+
"""推理专用:无梯度图、无 LoRA,纯前向 + 自动路由。
|
|
27
|
+
|
|
28
|
+
last_route 记录最近一次实际走的路线("int8"/"bf16"),供调用方与测试断言。"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, in_features, out_features):
|
|
31
|
+
super().__init__()
|
|
32
|
+
self.in_features, self.out_features = in_features, out_features
|
|
33
|
+
self.register_buffer("w_q", torch.zeros(out_features, in_features, dtype=torch.int8))
|
|
34
|
+
self.register_buffer("w_scale", torch.ones(out_features, 1, dtype=torch.float16))
|
|
35
|
+
self.last_route = None
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def from_linear(cls, linear: torch.nn.Linear):
|
|
39
|
+
mod = cls(linear.in_features, linear.out_features)
|
|
40
|
+
w_q, w_scale = prepare_weight(linear.weight.detach())
|
|
41
|
+
mod.w_q = w_q.to(linear.weight.device)
|
|
42
|
+
mod.w_scale = w_scale.to(linear.weight.device)
|
|
43
|
+
return mod
|
|
44
|
+
|
|
45
|
+
def forward(self, x):
|
|
46
|
+
M = x.numel() // x.shape[-1]
|
|
47
|
+
free_bytes = torch.cuda.mem_get_info()[0] if x.is_cuda else 2**62
|
|
48
|
+
route = "int8" if should_use_int8(free_bytes, M) else "bf16"
|
|
49
|
+
self.last_route = route
|
|
50
|
+
if route == "bf16":
|
|
51
|
+
# 回退路线:权重按行 dequant 后走 bf16 GEMM(无梯度,临时分配即弃)
|
|
52
|
+
w_dq = self.w_q.to(torch.bfloat16) * self.w_scale.to(torch.bfloat16)
|
|
53
|
+
return torch.nn.functional.linear(x, w_dq)
|
|
54
|
+
# int8 快速路线:零拷贝视图 + 融合量化
|
|
55
|
+
shape_3d = None
|
|
56
|
+
x2d = x
|
|
57
|
+
if x.dim() == 3:
|
|
58
|
+
shape_3d = x.shape
|
|
59
|
+
x2d = x.reshape(-1, x.shape[-1])
|
|
60
|
+
qx = fused_quantize(x2d)
|
|
61
|
+
out_i32 = torch._int_mm(qx.data, self.w_q.t())
|
|
62
|
+
y = out_i32.to(torch.bfloat16) * (qx.scale.to(torch.bfloat16) * self.w_scale.t().to(torch.bfloat16))
|
|
63
|
+
if shape_3d is not None:
|
|
64
|
+
y = y.reshape(*shape_3d[:-1], -1)
|
|
65
|
+
return y
|
leanq/layers.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""W4A8Linear: 基座权重 int8 冻结缓存(行 scale,前向零拷贝视图)+ LoRA 旁路 bf16 可训练。
|
|
2
|
+
支持 SmoothQuant:传入 smooth_scale (K,) 后,权重侧量化 w*s_k、激活侧 x/s_k,
|
|
3
|
+
把 LLM 激活的通道异常值难度搬到权重上(实测输出误差降 70%,见 tests/test_smoothquant.py)。
|
|
4
|
+
|
|
5
|
+
⚠️ bias 处理(2026-11-29 踩坑修正):真实模型(LocateAnything/Qwen2)218 个 Linear 带 bias,
|
|
6
|
+
早期实现直接丢弃 bias,导致每层输出系统性偏移、loss 从 3.7 崩到 8.9。
|
|
7
|
+
bias 必须原样保留为 bf16 参数并在 forward 中加上(bias 只有 N 个元素,不量化也几乎不占显存)。
|
|
8
|
+
|
|
9
|
+
W4 打包存储(真正 4bit 落盘)在 save/load 序列化层做;显存里基座驻留 int8(1 字节/参)。
|
|
10
|
+
"""
|
|
11
|
+
import torch
|
|
12
|
+
|
|
13
|
+
from .functional import int8_linear_prepared, prepare_weight
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class W4A8Linear(torch.nn.Module):
|
|
17
|
+
def __init__(self, in_features, out_features, lora_r=16, lora_alpha=32,
|
|
18
|
+
use_int8_bwd=False, smooth_scale=None, bias=False):
|
|
19
|
+
super().__init__()
|
|
20
|
+
self.in_features, self.out_features = in_features, out_features
|
|
21
|
+
self.register_buffer("w_q", torch.zeros(out_features, in_features, dtype=torch.int8))
|
|
22
|
+
self.register_buffer("w_scale", torch.ones(out_features, 1, dtype=torch.float16))
|
|
23
|
+
# 偏置:保持 bf16 原样(N 个元素,可忽略显存,但绝不能丢)
|
|
24
|
+
if bias:
|
|
25
|
+
self.bias = torch.nn.Parameter(torch.zeros(out_features, dtype=torch.bfloat16),
|
|
26
|
+
requires_grad=True)
|
|
27
|
+
else:
|
|
28
|
+
self.register_parameter("bias", None)
|
|
29
|
+
# SmoothQuant 平滑因子(离线校准得到的固定常量,非可学习)
|
|
30
|
+
if smooth_scale is not None:
|
|
31
|
+
self.register_buffer("smooth_scale",
|
|
32
|
+
smooth_scale.detach().reshape(-1).to(torch.float32),
|
|
33
|
+
persistent=True)
|
|
34
|
+
else:
|
|
35
|
+
self.smooth_scale = None
|
|
36
|
+
self.lora_r = lora_r
|
|
37
|
+
self.scaling = (lora_alpha / lora_r) if lora_r > 0 else 0.0
|
|
38
|
+
# 反向路线开关:False=bf16 反向(默认,精度优先);True=int8 反向(速度优先,长训精度有损)
|
|
39
|
+
self.use_int8_bwd = use_int8_bwd
|
|
40
|
+
if lora_r > 0:
|
|
41
|
+
self.lora_A = None # from_linear 里按设备创建
|
|
42
|
+
self.lora_B = None
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def from_linear(cls, linear: torch.nn.Linear, lora_r=16, lora_alpha=32,
|
|
46
|
+
use_int8_bwd=False, smooth_scale=None):
|
|
47
|
+
has_bias = linear.bias is not None
|
|
48
|
+
mod = cls(linear.in_features, linear.out_features, lora_r, lora_alpha,
|
|
49
|
+
use_int8_bwd, smooth_scale, bias=has_bias)
|
|
50
|
+
w = linear.weight.detach() # (N, K) bf16
|
|
51
|
+
s = None if smooth_scale is None else smooth_scale.detach().reshape(-1).to(w.device)
|
|
52
|
+
w_q, w_scale = prepare_weight(w, smooth_scale=s)
|
|
53
|
+
mod.w_q = w_q.to(linear.weight.device)
|
|
54
|
+
mod.w_scale = w_scale.to(linear.weight.device)
|
|
55
|
+
if has_bias:
|
|
56
|
+
# 保留原 bias 数值(bf16)
|
|
57
|
+
mod.bias = torch.nn.Parameter(linear.bias.detach().clone().to(torch.bfloat16),
|
|
58
|
+
requires_grad=True)
|
|
59
|
+
if s is not None:
|
|
60
|
+
mod.smooth_scale = s.to(torch.float32)
|
|
61
|
+
if lora_r > 0:
|
|
62
|
+
mod.lora_A = torch.nn.Linear(mod.in_features, lora_r, bias=False,
|
|
63
|
+
dtype=torch.bfloat16, device=w.device)
|
|
64
|
+
mod.lora_B = torch.nn.Linear(lora_r, mod.out_features, bias=False,
|
|
65
|
+
dtype=torch.bfloat16, device=w.device)
|
|
66
|
+
torch.nn.init.kaiming_uniform_(mod.lora_A.weight, a=5 ** 0.5)
|
|
67
|
+
torch.nn.init.zeros_(mod.lora_B.weight)
|
|
68
|
+
return mod
|
|
69
|
+
|
|
70
|
+
def forward(self, x):
|
|
71
|
+
s = self.smooth_scale
|
|
72
|
+
if s is not None and not torch.is_tensor(s):
|
|
73
|
+
s = None
|
|
74
|
+
y = int8_linear_prepared(x, self.w_q, self.w_scale, self.use_int8_bwd,
|
|
75
|
+
smooth_scale=s)
|
|
76
|
+
if self.bias is not None:
|
|
77
|
+
y = y + self.bias.to(y.dtype)
|
|
78
|
+
if self.lora_r > 0:
|
|
79
|
+
y = y + self.lora_B(self.lora_A(x)) * self.scaling
|
|
80
|
+
return y
|
leanq/quant_ops.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""融合量化:把 amax/scale/round/cast 链路合成一个编译单元,砍掉中间张量往返。
|
|
2
|
+
|
|
3
|
+
⚠️ 激活异常值问题的实证结论(2026-11-29,真实 LocateAnything 激活,见
|
|
4
|
+
lora_test/probe_act_quant.py 与 check_why.py):
|
|
5
|
+
|
|
6
|
+
策略 含 1 个 100x 异常通道时的误差
|
|
7
|
+
per-token amax(原始) 9.42% 异常通道撑大 scale,正常通道被压死
|
|
8
|
+
robust per-token 89.47% ← 截断异常值,直接丢信息,最差
|
|
9
|
+
per-channel 0.73% 让异常通道自己用大 scale,各自保留精度
|
|
10
|
+
SmoothQuant(0.5) 0.95% 把通道难度搬到权重侧,激活侧回到温和分布
|
|
11
|
+
|
|
12
|
+
决策:
|
|
13
|
+
- 截断类(clip/分位数/robust)一律不用——L2 误差爆炸,与"省显存"目标相悖;
|
|
14
|
+
- **默认 per-token**(保持现状):因为 per-channel 的 scale 作用在归约维 K,
|
|
15
|
+
无法事后乘回 out,严格实现需随输入重量化权重,成本高于收益;
|
|
16
|
+
- **推荐路径是 SmoothQuant**:平滑因子 s_k = cmax^0.5 是**离线固定**的
|
|
17
|
+
(对权重侧一次性折算 w' = w * s_k),运行时激活只需 x/s_k 后按 per-token 量化,
|
|
18
|
+
零额外开销即可拿到 0.95% 的误差——这是本库后续要实现的主方案。
|
|
19
|
+
|
|
20
|
+
当前实现保留三种 mode 供实验对比,默认 pertoken(行为与历史版本一致)。
|
|
21
|
+
"""
|
|
22
|
+
import torch
|
|
23
|
+
|
|
24
|
+
torch._dynamo.config.cache_size_limit = 64
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _quant_pertoken(x):
|
|
28
|
+
"""逐 token 绝对 amax(默认,与历史版本行为一致)。"""
|
|
29
|
+
amax = x.abs().amax(dim=-1, keepdim=True).to(torch.float32)
|
|
30
|
+
scale = (amax / 127.0).clamp(min=1e-8)
|
|
31
|
+
q = (x.to(torch.float32) / scale).round().clamp(-127, 127).to(torch.int8)
|
|
32
|
+
return q, scale.to(torch.float16)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _quant_perchannel(x):
|
|
36
|
+
"""逐通道 amax(scale 形状 (1,K))。仅用于误差对比实验:
|
|
37
|
+
该 scale 作用在归约维,无法事后乘回,前向直接用会算错——见下方 fused_quantize 拦截。"""
|
|
38
|
+
amax = x.abs().amax(dim=0, keepdim=True).to(torch.float32)
|
|
39
|
+
scale = (amax / 127.0).clamp(min=1e-8)
|
|
40
|
+
q = (x.to(torch.float32) / scale).round().clamp(-127, 127).to(torch.int8)
|
|
41
|
+
return q, scale.to(torch.float16)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _quant_smooth(x, alpha=0.5):
|
|
45
|
+
"""SmoothQuant 式:把逐通道平滑因子并入 scale,反量化时一步乘回。
|
|
46
|
+
注意:只有在**权重侧同步做过 w*s_k** 时数值才正确;此处提供
|
|
47
|
+
scale=(s*smooth) 的等价形式,便于将来与 prepare_weight 配合。"""
|
|
48
|
+
cmax = x.abs().amax(dim=0, keepdim=True).to(torch.float32).clamp(min=1e-8)
|
|
49
|
+
smooth = cmax.pow(alpha)
|
|
50
|
+
xs = x.to(torch.float32) / smooth
|
|
51
|
+
amax = xs.abs().amax(dim=-1, keepdim=True)
|
|
52
|
+
scale = (amax / 127.0).clamp(min=1e-8)
|
|
53
|
+
q = (xs / scale).round().clamp(-127, 127).to(torch.int8)
|
|
54
|
+
return q, (scale * smooth).to(torch.float16)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
_MODES = {
|
|
58
|
+
"pertoken": _quant_pertoken, # 默认
|
|
59
|
+
"perchannel": _quant_perchannel, # 仅对比实验(scale 形状不兼容前向,会被拦截)
|
|
60
|
+
"smooth": _quant_smooth, # 需权重侧协同
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _has_triton():
|
|
65
|
+
try:
|
|
66
|
+
import triton # noqa: F401
|
|
67
|
+
return True
|
|
68
|
+
except Exception:
|
|
69
|
+
return False
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
_fused_cache = {}
|
|
73
|
+
_compile_ok = None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _get_fused(fn):
|
|
77
|
+
global _compile_ok
|
|
78
|
+
key = id(fn)
|
|
79
|
+
if key in _fused_cache:
|
|
80
|
+
return _fused_cache[key]
|
|
81
|
+
impl = fn
|
|
82
|
+
if _compile_ok is not False and _has_triton():
|
|
83
|
+
try:
|
|
84
|
+
impl = torch.compile(fn, dynamic=False)
|
|
85
|
+
_compile_ok = True
|
|
86
|
+
except Exception:
|
|
87
|
+
impl, _compile_ok = fn, False
|
|
88
|
+
else:
|
|
89
|
+
_compile_ok = False
|
|
90
|
+
_fused_cache[key] = impl
|
|
91
|
+
return impl
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def fused_quantize(x, mode="pertoken"):
|
|
95
|
+
"""量化激活并返回 QuantTensor。
|
|
96
|
+
mode: pertoken(默认)/ smooth / perchannel(仅对比实验,前向会拒绝)
|
|
97
|
+
scale 形状恒为 (M,1),保证 Int8LinearFn 的 dequant 公式统一可用。"""
|
|
98
|
+
from .tensor import QuantTensor
|
|
99
|
+
if x.dim() < 2:
|
|
100
|
+
amax = x.abs().amax().to(torch.float32).clamp(min=1e-8)
|
|
101
|
+
s = amax / 127.0
|
|
102
|
+
q = (x.to(torch.float32) / s).round().clamp(-127, 127).to(torch.int8)
|
|
103
|
+
return QuantTensor(q, s.reshape(1).to(torch.float16))
|
|
104
|
+
if mode == "perchannel":
|
|
105
|
+
raise ValueError(
|
|
106
|
+
"perchannel 模式的 scale 作用在归约维,无法在 GEMM 后乘回;"
|
|
107
|
+
"请改用 mode='smooth'(SmoothQuant,需与 prepare_weight 协同)"
|
|
108
|
+
"或保持默认 mode='pertoken'。详见模块 docstring 的实测对比。")
|
|
109
|
+
fn = _MODES.get(mode, _quant_pertoken)
|
|
110
|
+
impl = _get_fused(fn)
|
|
111
|
+
try:
|
|
112
|
+
q, s = impl(x)
|
|
113
|
+
except Exception:
|
|
114
|
+
global _compile_ok
|
|
115
|
+
_fused_cache[id(fn)] = fn
|
|
116
|
+
_compile_ok = False
|
|
117
|
+
q, s = fn(x)
|
|
118
|
+
return QuantTensor(q, s)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def is_fused():
|
|
122
|
+
_get_fused(_quant_pertoken)
|
|
123
|
+
return bool(_compile_ok)
|
leanq/tensor.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""QuantTensor: int8 数据 + fp16 scale。反向激活、权重 A8 侧统一用它承载。"""
|
|
2
|
+
import torch
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class QuantTensor:
|
|
6
|
+
def __init__(self, data: torch.Tensor, scale: torch.Tensor):
|
|
7
|
+
self.data = data # int8
|
|
8
|
+
self.scale = scale # fp16, 形状广播对齐 data 的行
|
|
9
|
+
|
|
10
|
+
def dequantize(self) -> torch.Tensor:
|
|
11
|
+
return self.data.to(torch.float16) * self.scale
|
|
12
|
+
|
|
13
|
+
def to_colmajor(self) -> "QuantTensor":
|
|
14
|
+
"""物理布局重排为列主序(快速路径硬要求),数值不变。"""
|
|
15
|
+
t = self.data.t().contiguous().t()
|
|
16
|
+
return QuantTensor(t, self.scale)
|
|
17
|
+
|
|
18
|
+
@staticmethod
|
|
19
|
+
def quantize(x: torch.Tensor, bits: int = 8, dim: int = -1) -> "QuantTensor":
|
|
20
|
+
amax = x.abs().amax(dim=dim, keepdim=True).to(torch.float32)
|
|
21
|
+
qmax = 2 ** (bits - 1) - 1 # 127
|
|
22
|
+
scale = (amax / qmax).clamp(min=1e-8).to(torch.float16)
|
|
23
|
+
q = (x.to(torch.float32) / scale.to(torch.float32)).round().clamp(-qmax, qmax)
|
|
24
|
+
return QuantTensor(q.to(torch.int8), scale)
|
leanq/w4.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""int4 对称量化:2 值/字节打包 + fp16 组 scale。存储格式,计算前解包到 bf16/int8。"""
|
|
2
|
+
import torch
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def pack_w4(w: torch.Tensor, group: int = 64):
|
|
6
|
+
"""w: (K, N) bf16 → packed (K/2, N) uint8 + scales (K/group, N) fp16"""
|
|
7
|
+
K, N = w.shape
|
|
8
|
+
assert K % group == 0, f"K={K} not divisible by group={group}"
|
|
9
|
+
wg = w.to(torch.float32).reshape(K // group, group, N)
|
|
10
|
+
amax = wg.abs().amax(dim=1, keepdim=True) # (K//g, 1, N)
|
|
11
|
+
scale = (amax / 7.0).clamp(min=1e-8).to(torch.float16) # int4 主体范围 [-7,7]
|
|
12
|
+
q = (wg / scale.to(torch.float32)).round().clamp(-8, 7).to(torch.int8) # 存 [-8,7]
|
|
13
|
+
lo = (q[:, 0::2] & 0x0F).to(torch.uint8) # 偶数行放低 4 位
|
|
14
|
+
hi = (q[:, 1::2] & 0x0F).to(torch.uint8) # 奇数行放高 4 位
|
|
15
|
+
packed = lo | (hi << 4)
|
|
16
|
+
return packed.reshape(-1, N).contiguous(), scale.reshape(K // group, N)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def unpack_w4(packed: torch.Tensor, scales: torch.Tensor, group: int = 64):
|
|
20
|
+
"""packed (K/2, N) uint8 + scales (K/group, N) fp16 → (K, N) bf16"""
|
|
21
|
+
N = packed.shape[-1]
|
|
22
|
+
G = scales.shape[0] # K // group
|
|
23
|
+
p = packed.reshape(G, group // 2, N)
|
|
24
|
+
lo = (p & 0x0F).to(torch.int16) # 4-bit 还原成带符号
|
|
25
|
+
lo = torch.where(lo > 7, lo - 16, lo).to(torch.int8)
|
|
26
|
+
hi = ((p >> 4) & 0x0F).to(torch.int16)
|
|
27
|
+
hi = torch.where(hi > 7, hi - 16, hi).to(torch.int8)
|
|
28
|
+
q = torch.empty(G, group, N, dtype=torch.int8, device=p.device)
|
|
29
|
+
q[:, 0::2] = lo # 偶数行来自低 4 位
|
|
30
|
+
q[:, 1::2] = hi # 奇数行来自高 4 位
|
|
31
|
+
w = q.to(torch.float16) * scales.unsqueeze(1).to(torch.float16)
|
|
32
|
+
return w.reshape(-1, N)
|
|
@@ -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
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
leanq/__init__.py,sha256=O-We4SZrMoCvZWRXhGV3CBK6a709dsAbKWnU2wegcg8,78
|
|
2
|
+
leanq/functional.py,sha256=YwoddH9vUYrRmyhd1k1N2qTPk_zBDh4EnRY3NIBcCwU,9217
|
|
3
|
+
leanq/inference.py,sha256=_o-3yMpad08W9ygJ1-XewZLi2gtv8UGH2NDHaqyA_6o,2850
|
|
4
|
+
leanq/layers.py,sha256=Gkjf5JZMgiEwIEAd4cF6WxhdGqy2tn6V6NRrnZbAqbk,4304
|
|
5
|
+
leanq/quant_ops.py,sha256=SY4Mj6RC8cR5tlH5K19ImlEhcZ31RZvTCABhbv-J688,4916
|
|
6
|
+
leanq/tensor.py,sha256=WE8B46ye5BlSWXKeOIvMNsE5uSDt98EZH0UdsBPUhDA,1061
|
|
7
|
+
leanq/w4.py,sha256=trTUicogrj1pnMb6K-xW-L1NCZSaxJc29VGrypjzT90,1817
|
|
8
|
+
leanq-0.1.0.dist-info/licenses/LICENSE,sha256=1S9qzq1ngGJEHtTZvc94s77OjcXorEQ-o1Go7oETnPY,1075
|
|
9
|
+
leanq-0.1.0.dist-info/METADATA,sha256=lH42N0Wy0q7zclIIQ3ZjC5ZkRQjZau0gYEwv_NSMFAo,11243
|
|
10
|
+
leanq-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
leanq-0.1.0.dist-info/top_level.txt,sha256=Vwna76YF1YtTL6mYpl8gMmE_5pAeO4tNa0fnNJ_UQsg,6
|
|
12
|
+
leanq-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
leanq
|