Repository navigation
Pass gradients through compressed-tensors activation quantization so W8A8 checkpoints train with LoRA - #11585
Conversation
…n so W8A8 checkpoints train with LoRA
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex security review |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Confirmed main has no handling for compressed-tensors activation quantization dropping input gradients, so LoRA on W8A8 checkpoints currently trains on near-zero gradients. Will get this reviewed. |
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.
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.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…rains 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.
…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.
…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.
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.
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.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: edb6878fb1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if can_use_fp8_rowwise_gemv(input, self.weight, self.weight_scale): | ||
| out = fp8_rowwise_gemv(input, self.weight, self.weight_scale) | ||
| else: | ||
| out = fp8_linear(input, self.weight, self.weight_scale) |
There was a problem hiding this comment.
Preserve the checkpoint's activation quantization scheme
When UNSLOTH_COMPRESSED_TENSORS_FP8_KERNELS=1, this forward routes every supported FP8 weight through fp8_linear without checking scheme.input_activations. The block and FBGEMM paths inside fp8_linear dynamically quantize the input to FP8, so weight-only checkpoints unexpectedly become W8A8, while checkpoints specifying static FP8 or INT8 activations are quantized again with a different scheme. This changes model outputs and training results; routing should be restricted to compatible dynamic-FP8 activation schemes, or use a weight-only/dequantized matmul for other schemes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing: this route is opt-in (UNSLOTH_COMPRESSED_TENSORS_FP8_KERNELS=1), only float 8-bit weights are routed (INT8 schemes never are), and it runs the same FP8 kernels as Unsloth's native FP8 checkpoints; by default these checkpoints are decompressed and keep their own activation scheme.
| try: | ||
| _decompress(model) | ||
| except Exception as e: | ||
| print(f"Unsloth: could not decompress the compressed-tensors checkpoint after load: {e}") | ||
| return False |
There was a problem hiding this comment.
Propagate decompression failures when no retry hook exists
If decompress_model raises on a compressed-tensors version or Transformers integration that did not install ct_decompress_hook, this handler only prints the exception and lets model loading continue. Unlike the hook-present path, nothing will retry decompression on the first forward, so PEFT can later receive the still-compressed or partially decompressed modules and fail with the missing-weight error this change is intended to prevent. When there was no original hook to replace, the load should fail immediately rather than returning an unusable model.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing: without the hook this is transformers 4.x, where CompressedLinear still decompresses itself on its first call, so continuing keeps the load working as it does on main; where both fail, main fails at the same PEFT step.
…s 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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 39cebc13e1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| module.forward = _unsloth_compressed_tensors_fp8_forward.__get__(module) | ||
| module._unsloth_compressed_tensors_fp8 = True | ||
| converted += 1 |
There was a problem hiding this comment.
Unwrap same-device offload caches on routed models
When FP8 routing is enabled with compressed-tensors >= 0.19, this replaces each layer's forward but leaves its _parameters as an OffloadCache. The newly added cleanup explicitly notes that these same-device caches cannot be traced by torch.compile, yet it is called only after decompression, which this successful routing path skips. Consequently, routed models from those releases can fail or graph-break during compiled training; call _remove_same_device_compressed_tensors_offload(model) before returning from the converted path as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing: in compressed-tensors 0.19.0 the OffloadCache wrapping comes from from_accelerate(model) inside ModelCompressor.decompress_model (model_compressor.py:191); the routed path never calls decompress_model, so no cache exists to unwrap.
| if can_use_fp8_rowwise_gemv(X, W, W_quant): | ||
| out = fp8_rowwise_gemv(X, W, W_quant) |
There was a problem hiding this comment.
Preserve activation quantization in the decode GEMV
During no-grad single-token decoding of a rowwise FP8 layer, this branch replaces fp8_linear, which dynamically quantizes X (and honors weight.input_scale_ub), with a GEMV that multiplies the original BF16/FP16 activation directly. Prefill and batched decoding therefore use W8A8 semantics while the one-token path uses weight-only semantics, and inputs affected by quantization or clipping can produce materially different logits. Unlike the earlier opt-in routing concern, this also affects ordinary native rowwise FP8 modules without either compressed-tensors routing environment variable; the fast path should retain the checkpoint's activation quantization or be restricted to explicitly weight-only layers.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing: the GEMV computes the exact dequantized product, closer to the bf16 model than the quantized-activation product, and without FBGEMM the prefill path on main is already weight-only; this is a precision choice, not a wrong result.
…lback 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.
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.
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.
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…W8A8 checkpoints train with LoRA (unslothai#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>
What this fixes
LoRA on a compressed-tensors checkpoint that quantizes activations (FP8 dynamic, INT8 W8A8) barely trains. compressed-tensors fake-quantizes the activation inside
forward_quantize, which runs under@torch.no_grad()(compressed_tensors/quantization/lifecycle/forward.py, 0.17.0). With the base weight frozen under LoRA, the quantized base layer then passes no gradient back to its input, so every LoRA adapter below it sees almost none. The forward is correct, the gradients are not.On
ibm-granite/granite-4.1-30b-FP8the LoRA-A gradient, as a fraction of the 16-bit model's on the same batch:q_projq_projdown_projChange
An import fix in
unsloth/import_fixes.py, called from_gpu_init.py:fix_compressed_tensors_activation_quant_gradient()wraps compressed-tensors'forward_quantizeso that, for activations only, the gradient passes straight through the quantizer: a small autograd function returns the quantized tensor itself and hands the incoming gradient to the input unchanged. The forward output is bit-identical, including where a static scale saturates (thevalue + (quantized - value).detach()form rounds there in bf16), weights are never touched, and weight-only schemes take the original path. The wrapper applies only when the input requires grad, the quantized output does not, and grad mode is on. It patches immediately if compressed-tensors is already imported, otherwise when that module first loads (asys.meta_pathfinder, like the other import hooks in this file), and does nothing when compressed-tensors is not installed.Tests
New
tests/test_compressed_tensors_activation_ste.py, run from outside the repository against each tree:The fourth test drives an INT8 W8A8 layer with a calibrated per-tensor input scale that clips most of its input, in bf16, and checks the forward with gradients on equals the no-grad forward exactly; the previous revision failed it. The first three also pass on transformers 4.57.6 with torch 2.6 and compressed-tensors 0.11.0 and 0.13.0. The existing import_fixes suites: 57 passed, 2 skipped.
Real model
granite-4.1-30b, LoRA r=16, same 10 batches for every row (each step is a different batch, so compare rows, not steps):loss_type="nll"(bf16)Loading and FP8 kernel routing
get_peft_modelwith'Linear' object has no attribute 'weight', and FP8 / INT8 loads on transformers 4.57.6.UNSLOTH_COMPRESSED_TENSORS_FP8_KERNELS=1(per-tensor and per-channel), plusUNSLOTH_COMPRESSED_TENSORS_FP8_BLOCK_KERNELS=1for block scales. A per-tensor scale is routed as one scale per row. On B200 it saves about 20% peak training memory (Qwen3-8B-FP8-dynamic: 36.3 GB to 29.3 GB), but dequantizing per step trained 35-65% slower and decoded 18-40% slower than the decompressed bf16 model, and block scales were about 2.5x slower to train and 4-5x slower to decode, so the default keeps the bf16 path.Qwen3-8B-FP8-dynamic, B200, base vs this branch alternated on one GPU (LoRA r=16, 4x1024 tokens):
gemma-3-1b-it LoRA, 61 steps, final loss (bf16 reference 1.383): INT8 W8A8 main 1.880 vs this branch 1.404; FP8-dynamic main 1.848 vs this branch 1.389.
torch.compile
The single-token FP8 GEMV reads the multi-device check once at import, since
torch.cuda.device_count()inside a compiled region graph-breaks; the other FP8 kernels keep the per-call check, because letting Dynamo trace all ofFP8BlockQuantLinearmade torch 2.11 compile its backward to a zero input gradient (covered by a new test). Checked on torch 2.11, 2.12.1, 2.13 and 2.14 (cu130): the opt-in FP8 forward and the GEMV compile withfullgraph=Trueand no breaks, graph counts on native FP8 and W8A8 LoRA runs match main and stay flat after the first step, and on 2.14, where compressed-tensors' activation quantization now compiles fullgraph, this branch gets the correct input gradient while main gets none.