Skip to content

Commit 9d15a59

Browse files
Pass gradients through compressed-tensors activation quantization so W8A8 checkpoints train with LoRA (#11585)
* Pass gradients through compressed-tensors activation fake quantization so W8A8 checkpoints train with LoRA * Trim comments * Return early from the activation STE wrapper when grad mode is off Inference runs forward_quantize under no_grad or inference_mode, so check torch.is_grad_enabled() before unpacking arguments and type checks. Cuts the added per-call cost on the decode path roughly in half. * Keep the quantized activation exactly in the STE forward value + (out - value).detach() rounds in bf16, so a static W8A8 scale that saturates changed the forward values the checkpoint was calibrated for. A small autograd function now returns the quantized tensor itself and passes the gradient straight through. Adds a saturating static-scale test. * Run compressed-tensors FP8 Linears on Unsloth's FP8 kernels so LoRA trains without decompressing Keep FP8 weights and scales as loaded, route each forward through fp8_linear (on the fly dequantization, identity input gradient) and drop the first-forward decompression hook. Fix weight_dequant on a transposed square per-row view, read the block size from the scale, and fall back to dequant + matmul in the per-row path when FBGEMM is absent. * Add the bias once in single-token FP8 decode and wait for a zoo that keeps FP8 inputs fast_linear_forward passed the bias into fp8_linear, whose per-channel path adds it, then added it again. Compressed-tensors FP8 checkpoints with q/k/v biases (Qwen2.5 FP8-dynamic) now reach that path. Route compressed-tensors FP8 Linears to the FP8 kernels only when the installed unsloth_zoo compiled LoRA forward no longer casts inputs to the FP8 weight dtype; older zoos keep the decompress path. * Decompress compressed-tensors checkpoints at load, outside inference mode Checkpoints that do not route to the FP8 kernels (INT8 W8A8, or FP8 with an older unsloth_zoo) were decompressed by compressed-tensors on their first forward. PEFT's direct .forward calls can skip that hook, and when the first forward is a generate() it runs under inference_mode, so every weight becomes an inference tensor and the next LoRA backward fails with 'Inference tensors cannot be saved for backward'. Decompress once after load instead, and swap the lazy hook for one that leaves inference mode, so the fallback is safe too. FP8 routing is now all or nothing so the two never mix. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Run the load-decompress test without importing unsloth CPU CI runners have no unsloth_zoo, so importing unsloth failed collection. The function only needs torch; the test now takes it straight from loader_utils.py. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Unwrap compressed-tensors 0.19 offload caches and add an FP8 decode GEMV compressed-tensors 0.19 decompress_model wraps every module's parameters in an OffloadCache even with nothing offloaded; its data pointer comparison breaks Dynamo, so FastModel failed on every decompressed checkpoint with 'Unsupported: Data pointer comparison' (main included). Same-device caches are unwrapped after decompression; real offloading is left alone. Single-token decode on per-row FP8 weights dequantized the whole weight every step when FBGEMM is absent. A split-K Triton GEMV now reads the FP8 weight once and applies the row scale in the reduction, deterministically, for up to four rows with grad off; everything else is unchanged. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Make the FP8 decode GEMV a single launch for one token The split-K version spent more host time on its reduction, cast and launch math than the GPU spent on the matmul, so end-to-end decode stayed slower than bf16. One launch that accumulates a full tile and reduces once matches or beats a bf16 matmul on every Qwen2.5-3B layer shape, and it now runs for a single token only: from four rows a bf16 matmul wins, since each row re-reads the weight. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Route compressed-tensors FP8 to the FP8 kernels only on GPU weights The FP8 kernels are triton, so a checkpoint loaded on CPU would have been routed to kernels that cannot run there; main decompresses it and trains. Weights off the GPU keep that path. * Trim comments in compressed-tensors changes * Keep block FP8 compressed-tensors on the decompress path, route per-tensor scales per row The block FP8 kernel trains about 2.5x slower and decodes about 4x slower than the decompressed bf16 model on B200, so block routing is opt-in via UNSLOTH_COMPRESSED_TENSORS_FP8_BLOCK_KERNELS=1. A per-tensor scale is broadcast to one scale per row, which takes the faster and more accurate rowwise path. * Make compressed-tensors FP8 kernel routing opt-in Keeping FP8-dynamic weights in FP8 saves about 20% peak training memory on Qwen3-8B but dequantizing per step trains 35-65% slower and decodes 18-40% slower than the decompressed bf16 model on B200. Default to decompressing once at load; UNSLOTH_COMPRESSED_TENSORS_FP8_KERNELS=1 opts into the FP8 kernels. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Read the FP8 multi-device check once so compiled FP8 kernels do not graph break torch.cuda.device_count() inside a compiled region returns a non-Tensor and breaks the graph; the single-token FP8 GEMV hit it three times under torch.compile(fullgraph=True). * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Keep the per-call FP8 device count outside the decode GEMV Reading the multi-device check once let Dynamo trace all of FP8BlockQuantLinear, and torch 2.11 compiled its backward to a zero input gradient. Only the forward-only GEMV uses the import-time count now; the other FP8 kernels behave as on main. * Shorten FP8 device-count comment * Dequantize rowwise FP8 fallback to the input dtype, save routed scales in checkpoint shape The rowwise dequant fallback now also serves missing FBGEMM and pre-sm89 GPUs, where fp16 inputs met a bf16 weight and failed in torch.matmul. A routed compressed-tensors module saves its weight_scale in the shape the quantization config declares, not the per-row broadcast. * Drop the compressed-tensors decompress hook inside the decompress callback compressed-tensors 0.19.0 decompress_model leaves ct_decompress_hook registered, so after a failed load-time attempt the retry hook ran decompression again on every forward. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Expand saved compressed-tensors scales back to the routed shape on load The state_dict hook saves weight_scale in the checkpoint shape; the matching load pre-hook lets a routed module load its own state_dict again. * Decompress compressed-tensors FP8 for full finetuning instead of routing Routed FP8 weights are frozen, so full_finetuning=True with the opt-in FP8 kernels left every base weight untrained; full finetuning now always takes the decompressed bf16 weights. * Trim comments after review --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent ef63a38 commit 9d15a59

11 files changed

Lines changed: 1070 additions & 16 deletions
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# SPDX-License-Identifier: AGPL-3.0-only
2+
# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.
3+
#
4+
# This program is free software: you can redistribute it and/or modify
5+
# it under the terms of the GNU Affero General Public License as published
6+
# by the Free Software Foundation, either version 3 of the License, or
7+
# (at your option) any later version.
8+
#
9+
# This program is distributed in the hope that it will be useful,
10+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
# GNU Affero General Public License for more details.
13+
#
14+
# You should have received a copy of the GNU Affero General Public License
15+
# along with this program. If not, see <https://www.gnu.org/licenses/>.
16+
17+
"""Each case runs in a subprocess: the patch changes compressed-tensors module state."""
18+
19+
import os
20+
import subprocess
21+
import sys
22+
import textwrap
23+
24+
import pytest
25+
26+
pytest.importorskip("compressed_tensors")
27+
28+
_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29+
30+
_RUNNER = textwrap.dedent(
31+
"""
32+
import importlib.util, json, sys
33+
mode = sys.argv[1]
34+
if mode != "base":
35+
spec = importlib.util.spec_from_file_location("unsloth_import_fixes_under_test", sys.argv[2])
36+
fixes = importlib.util.module_from_spec(spec)
37+
spec.loader.exec_module(fixes)
38+
if mode == "lazy":
39+
assert "compressed_tensors.quantization.lifecycle.forward" not in sys.modules
40+
fixes.fix_compressed_tensors_activation_quant_gradient()
41+
import compressed_tensors # noqa: F401
42+
if mode != "lazy":
43+
fixes.fix_compressed_tensors_activation_quant_gradient()
44+
fixes.fix_compressed_tensors_activation_quant_gradient() # idempotent
45+
import torch
46+
from compressed_tensors.quantization import (
47+
QuantizationArgs, QuantizationConfig, QuantizationScheme, apply_quantization_config,
48+
)
49+
torch.manual_seed(0)
50+
model = torch.nn.Sequential(torch.nn.Linear(64, 32, bias = False))
51+
static = len(sys.argv) > 3 and sys.argv[3] == "static"
52+
if static: # INT8 W8A8 with a calibrated per-tensor input scale that saturates
53+
activations = QuantizationArgs(
54+
num_bits = 8, type = "int", strategy = "tensor", dynamic = False, symmetric = True,
55+
)
56+
else:
57+
activations = QuantizationArgs(
58+
num_bits = 8, type = "float", strategy = "token", dynamic = True, symmetric = True,
59+
)
60+
scheme = QuantizationScheme(targets = ["Linear"], input_activations = activations)
61+
apply_quantization_config(model, QuantizationConfig(config_groups = {"group_0": scheme}, quantization_status = "frozen"))
62+
lin = model[0]
63+
lin.weight.requires_grad_(False) # the frozen base layer under a LoRA adapter
64+
if static:
65+
model.to(torch.bfloat16)
66+
lin.input_scale.data.fill_(0.01) # clips at 1.27, so most of randn * 4 saturates
67+
x = (torch.randn(4, 64) * (4 if static else 1)).to(lin.weight.dtype).requires_grad_(True)
68+
y = lin(x)
69+
with torch.no_grad():
70+
y_nograd = lin(x)
71+
out = {"has_grad_fn": y.grad_fn is not None, "same_forward": bool(torch.equal(y.detach(), y_nograd))}
72+
if y.grad_fn is not None:
73+
(gx,) = torch.autograd.grad(y.sum(), x)
74+
ref = torch.ones(4, 32, dtype = lin.weight.dtype) @ lin.weight
75+
out["grad_err"] = float((gx - ref).abs().max().float())
76+
import compressed_tensors.quantization.lifecycle.forward as f
77+
out["patched"] = bool(getattr(f.forward_quantize, "_unsloth_activation_ste", False))
78+
print(json.dumps(out))
79+
"""
80+
)
81+
82+
83+
def _run(mode, scheme = "dynamic"):
84+
proc = subprocess.run(
85+
[
86+
sys.executable,
87+
"-c",
88+
_RUNNER,
89+
mode,
90+
os.path.join(_ROOT, "unsloth", "import_fixes.py"),
91+
scheme,
92+
],
93+
capture_output = True,
94+
text = True,
95+
timeout = 600,
96+
env = dict(os.environ, CUDA_VISIBLE_DEVICES = ""),
97+
)
98+
assert proc.returncode == 0, proc.stdout[-2000:] + proc.stderr[-4000:]
99+
import json
100+
101+
return json.loads(proc.stdout.strip().splitlines()[-1])
102+
103+
104+
def test_without_the_fix_the_input_gradient_is_lost():
105+
out = _run("base")
106+
assert not out["has_grad_fn"]
107+
108+
109+
@pytest.mark.parametrize("mode", ["eager", "lazy"])
110+
def test_activation_quantization_passes_the_gradient_straight_through(mode):
111+
out = _run(mode)
112+
assert out["patched"]
113+
assert out["has_grad_fn"]
114+
assert out["same_forward"] # the quantized forward is untouched
115+
assert out["grad_err"] < 1e-5 # dX = dY @ W, as if the activation were not quantized
116+
117+
118+
def test_a_saturating_static_scale_keeps_the_forward_bit_identical():
119+
out = _run("eager", "static")
120+
assert out["patched"]
121+
assert out["has_grad_fn"]
122+
assert out["same_forward"]

0 commit comments

Comments
 (0)