Skip to content

LoRA: opt-in rotated int8 frozen base for consumer Blackwell (UNSLOTH_LORA_BASE_INT8=1) - #19965

Merged
danielhanchen merged 8 commits into
mainfrom
int8-lora-base-sm120
Nov 27, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
int8-lora-base-sm120

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Summary

This adds an opt-in rotated INT8 frozen base for LoRA on consumer Blackwell (RTX 50, sm120). Enable it with UNSLOTH_LORA_BASE_INT8=1 (or float8_training = "int8_lora") on a 16-bit base. It changes nothing unless enabled.

On a GeForce RTX 5090 the FP32-accumulate tensor paths run at half rate. The RTX Blackwell whitepaper lists bf16 at 209.5 TFLOPS, fp8 at 419 and INT8 at 838 TOPS. Measured on a 5090 under Windows (torch 2.14.1, triton-windows 3.8), summed over one Qwen3-8B layer's GEMMs at 8192 tokens:

  • The int8 GEMM in this PR runs at 3.03x a bf16 GEMM and 1.54x fp8 tensorwise (A/A 0.25%).
  • The same box runs the existing fp8 LoRA routes at Qwen3-1.7B 40-50% slower than 16-bit LoRA. The Windows wheels have no row-wise _scaled_mm.

How it works

  • Weight (stored once): the frozen weight W [out, in] is stored as int8 codes of W @ H, where H is a block-diagonal Walsh-Hadamard of order 128 along the input dim. Each output row gets one fp32 scale. That is 1 byte per weight, with the 16-bit master in host RAM as fp8 LoRA does.
  • Forward:
    • One Triton kernel rotates and quantizes the activation per token.
    • The int8 GEMM accumulates in int32 and applies the dequant plus the LoRA term (lora_first) in its epilogue.
  • Input gradient: dY @ W = (dY * s) @ Q @ H.
    • The weight row scale folds into dY before its per-token quantization.
    • The same int8 codes, transposed per call, are the second operand. UNSLOTH_INT8_LORA_CACHE_T=1 keeps the transposed copy instead.
    • The GEMM epilogue undoes the rotation on each 128-column block, split into two bf16 halves so it keeps fp32 accuracy.
  • Why rotate: the rotation spreads activation outliers across each block. Plain per-token int8 was +0.89% eval loss with the int8 forward at Qwen3-1.7B. Rotated it is +0.16%, against +0.42% for fp8 rowwise.
  • Shared quantization: q / k / v and gate / up read the same input and share one activation quantization. In eager mode this is an identity plus version-counter cache. Inside compiled regions it is CSE of the pure custom op.
  • Plumbing: it reuses the fp8 LoRA plumbing. Int8LoRABaseState subclasses Fp8LoRABaseState, so Unsloth's fused LoRA kernels call matmul / lora_first / dgrad / dgrad_accum unchanged, and attach, master offload, merge and save all apply.
  • Gates:
    • Refused where the Triton int8 tiles were measured slower than bf16: A100 0.22x and L4 0.53x (the Triton >= 3.8 sm8x int8 spill), plus T4 and ROCm. sm90 and sm100 are unprobed.
    • Models with hidden size below 2048 convert nothing. Qwen3-0.6B measured slower than bf16 at every token count on an RTX PRO 6000.
    • Calls under 2048 rows run the 16-bit GEMM.
    • The environment opt-in never fails a load. Where the int8 base cannot run it prints why and trains in 16 bit, while float8_training = "int8_lora" refuses.
    • Override env vars: UNSLOTH_INT8_LORA_MIN_HIDDEN, UNSLOTH_INT8_LORA_MIN_ROWS, UNSLOTH_INT8_LORA_SHARE_XQ=0.

Accuracy

Setup:

  • Unsloth FastLanguageModel, r=16 on all seven projections, alpaca-cleaned, bs 4 x 1024, 100 steps, lr 2e-4.
  • Eval on 32 held-out rows, with the arm's own forward and with the trained adapter on the exact 16-bit base.
  • Runs on a B200 (numerics only).
model arm eval, own forward eval, exact base step-0 LoRA grad cosine vs bf16
Qwen3-1.7B bf16 A/A +0.003% +0.003% 0.99998
Qwen3-1.7B fp8 LoRA +0.322% -0.148% 0.978
Qwen3-1.7B int8 (this PR) +0.017% -0.123% 0.985
Llama-3.2-3B bf16 A/A -0.015% -0.015% 0.99998
Llama-3.2-3B fp8 LoRA +0.168% -0.065% 0.976
Llama-3.2-3B int8 (this PR) -0.030% -0.040% 0.996

Speed

GEMM level on an RTX PRO 6000 (sm120 workstation card, no half-rate FP32 accumulate, so int8 = fp8 = ~1.9x bf16 per GEMM). Forward twice (checkpoint recompute) plus input gradient, activation quantization included, over one decoder layer:

tokens Qwen3-1.7B Qwen3-4B Qwen3-8B Llama-3-8B
2048 1.01x 1.12x 1.25x 1.23x
8192 1.17x 1.28x 1.45x 1.46x
16384 1.27x 1.33x 1.50x 1.53x

End to end inside Unsloth on the RTX PRO 6000 (FastLanguageModel, bf16 base, r=16 on all projections, unsloth gradient checkpointing, bs 4 x 2048 = 8192 tokens per step, 25 steps). Each run is a fresh process with fresh compile caches, interleaved bf16, int8, fp8, fp8, int8, bf16, bf16. Values are median s/step:

model bf16 (A/A spread) fp8 LoRA (rowwise) int8 (this PR) int8 vs bf16 int8 vs fp8 peak GB bf16 / int8
Qwen3-1.7B 0.2527 (0.09%) 0.2559 0.2402 1.05x 1.07x 17.9 / 16.5
Qwen3-4B 0.5482 (0.16%) 0.5352 0.4947 1.11x 1.08x 35.9 / 32.3
Qwen3-8B 0.8856 (0.69%) 0.7826 0.7242 1.22x 1.08x 51.2 / 44.3
  • Every int8 run converted all base layers (196 / 252) and made 0 16-bit fallback calls.
  • The rotated activation quantization ran 3996 times for 6804 forward GEMMs (q / k / v and gate / up share one).
  • The RTX PRO 6000 has full-rate FP32 accumulate, so this is the low end. On the RTX 5090 the int8 GEMM's advantage over bf16 and fp8 is 1.6x / 1.3x larger.

End to end on the RTX 5090: a device task is queued.

Tests

  • tests/test_int8_lora_cuda.py (GPU):
    • Forward and input gradient against an fp64 emulation of the same algorithm (< 4e-3) and against the exact 16-bit linear (< 3e-2), bf16 and fp16, five shapes including M not a multiple of the tile.
    • The epilogue delta added once.
    • Negative controls: an unrotated activation or a missing epilogue un-rotation must land far off.
    • The shared activation quantization and its invalidation on in-place writes, inference tensors and equal-valued copies.
    • The row gate as a kill switch: 0 int8 calls and an output bit-equal to F.linear.
    • Master offload.
    • torch.compile(fullgraph = True) with 0 graph breaks and compiled == eager bit for bit.
  • tests/test_int8_lora_recipe.py (CPU): registry entry, env opt-in resolution, refusals (4 / 8 bit / fp8 / QAT bases, sm75 / sm80 / sm89, no Triton), the 16-bit fallback of the env opt-in, eligibility, the hidden-size gate through enable_fp8_lora.
  • Existing suites: tests/test_precision_registry.py, tests/test_fp8_lora.py and tests/test_float8_training.py pass unchanged.
  • Sanitizer (B200):
    • memcheck and initcheck: run over the fused LoRA MLP / QKV / O suite on int8 bases. initcheck is clean. memcheck reports no memory errors in any kernel. Its only reports are two cuFuncSetAttribute "invalid argument" CUDA API calls from Triton's launcher, which a plain Triton int8 GEMM control with the same > 48 KB shared memory tiles also produces.
    • Engagement: every forward / backward launched the rotated quant, the int8 GEMM and the input-gradient kernels.
  • Torch floor: the module imports and registers its custom ops on torch 2.6 / Triton 3.2.
  • Unsloth runs: 0 graph breaks in the bf16, fp8 and int8 arms alike, every base layer converted (196 / 196 at 1.7B), 0 16-bit fallbacks at these token counts.

Not covered

  • sm90 / sm100 timing.
  • The RTX 5090 end-to-end run (pending).
  • Windows CI for the Triton int8 path.
  • Grouped (MoE expert) int8 GEMMs: MoE experts keep their existing path.

…_LORA_BASE_INT8=1)

The frozen base GEMMs of a LoRA linear (forward and input gradient) run as int8 on a block-Hadamard
rotated weight with per-token int8 activations, through the fp8 LoRA plumbing (attach, master offload,
merge, save) and Unsloth's fused LoRA kernels. On an RTX 5090 the int8 GEMM is 3x a bf16 GEMM and
1.5x fp8. Off by default; refused on sm75 / sm80 / sm89 / ROCm where the Triton int8 tiles were
measured slower than bf16; models narrower than hidden size 2048 and calls under 2048 rows stay 16 bit.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T15:13:39.400069Z f823346 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 4baa0591d8

ℹ️ 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".

shimmyshimmer pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review (new head 15a466d)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 15a466d4c4

ℹ️ 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".

Comment thread unsloth/kernels/int8_lora.py Outdated
Comment on lines +182 to +183
amax = tl.maximum(amax, tl.abs(x * c))
rmax = tl.maximum(tl.max(amax, axis = 0), 1e-30)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve NaNs in the activation quantization scales

When a row of dY contains a NaN alongside finite values, these reductions discard the NaN and produce a finite scale. The subsequent clamp and int8 cast cannot preserve NaNs either, so the input-gradient GEMM can return finite gradients where the corresponding dense GEMM would propagate NaNs. The rotated forward quantizer has the same issue. This silently masks numerical failures during training; track NaNs and mark the affected row scales as NaN, as the existing _fp8_rowwise_cast_kernel does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cff4eb9. Both quantizers now count NaNs while they reduce. These are the rotated forward quant, which counts them after the rotation, and the scaled dY quant. A row with a NaN gets a NaN scale, so that whole output row comes out NaN, as the 16-bit GEMM would give. New test test_nan_rows_propagate (bf16 and fp16) checks the NaN row and that every other row stays finite, for both the forward and the input gradient.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review (head cff4eb9)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cff4eb9aee

ℹ️ 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".

Comment thread unsloth/models/float8_training.py Outdated
Comment on lines +461 to +463
if float8_training in (None, False) and not full_finetuning and int8_lora_requested():
why = "the base is loaded quantized (load_in_4bit / 8bit / fp8)" if quantized_base else None
why = why or int8_lora_unavailable()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve FP32 loads when enabling INT8 through the environment

On a supported GPU, setting UNSLOTH_LORA_BASE_INT8=1 and loading an unquantized model with dtype=torch.float32 now fails even when float8_training is unset. This helper checks the GPU and quantization flags but not the requested dtype, so both loaders inject "int8_lora"; _resolve_int8_lora then calls _check_precision_recipe, which rejects FP32 because the new recipe only accepts BF16/FP16. Pass the requested dtype into this preflight and ignore the environment opt-in for unsupported dtypes, preserving the documented non-failing fallback while retaining refusal for explicit INT8 requests.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e87a04a. float8_training_request now takes the requested dtype, and both loaders pass it. With UNSLOTH_LORA_BASE_INT8=1, a float32 load gets a message and stays float32 rather than failing. An explicit float8_training = "int8_lora" still refuses fp32 with the registry's dtype reason. Tests: test_env_opt_in_on_fp32_load_is_ignored.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review (head e87a04a)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e87a04a197

ℹ️ 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".

Comment thread unsloth/models/float8_training.py Outdated
Comment on lines +462 to +466
if float8_training in (None, False) and not full_finetuning and int8_lora_requested():
why = "the base is loaded quantized (load_in_4bit / 8bit / fp8)" if quantized_base else None
if why is None and dtype in (torch.float32, "float32", "fp32"):
why = "the int8 base needs bf16 / fp16 activations, the model loads in float32"
why = why or int8_lora_unavailable()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip the environment opt-in for QAT loads

On a supported GPU, loading a 16-bit base with qat_scheme="int8-int4" and UNSLOTH_LORA_BASE_INT8=1 fails even when float8_training is unset. Both loaders call this helper without passing qat_scheme, so it injects "int8_lora"; their subsequent resolve_fp8_lora call passes the QAT scheme to _resolve_int8_lora, which raises PrecisionRefused. Include QAT in this preflight and leave the original request unchanged for environment-only opt-ins, preserving the documented non-failing fallback while still rejecting an explicit INT8 request.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a68680d. The env preflight now also takes qat_scheme (both loaders pass it), so a QAT load with UNSLOTH_LORA_BASE_INT8=1 prints a message and keeps its 16-bit base. I applied the same treatment to tensor / pipeline / expert parallel runs (UNSLOTH_TP_SIZE, UNSLOTH_EP_SIZE), which refuse a converted frozen base at trainer init. An explicit float8_training = "int8_lora" still refuses QAT. Tests: test_env_opt_in_on_qat_load_is_ignored, test_env_opt_in_under_tp_or_ep_is_ignored.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review (head a68680d)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a68680de2a

ℹ️ 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".

Comment thread unsloth/models/loader.py Outdated
_int8_request = float8_training_request(
kwargs.get("float8_training", None),
full_finetuning,
quantized_base = bool(load_in_4bit or load_in_8bit or load_in_fp8 not in (False, None)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve the INT8 opt-in after normalizing checkpoint precision

On a supported GPU, loading a Hub checkpoint ending in -bf16 with the default loading flags and UNSLOTH_LORA_BASE_INT8=1 silently skips INT8 conversion. This preflight sees the default load_in_4bit=True and discards the environment request, but the later bf16_repo_loads_16bit branch clears the quantization flags and loads a 16-bit base. Neither loader revisits the discarded request afterward, so an eligible 16-bit model trains without the requested optimization. Resolve the environment opt-in using the effective checkpoint precision in both loaders.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f823346. The env opt-in is no longer pre-flighted from the load flags. Both loaders now decide it right before mark_fp8_lora, from the loaded model itself, via int8_lora_from_env. A '-bf16' checkpoint that loaded 16 bit despite the load_in_4bit default converts. A model whose Linear weights are quantized (bitsandbytes quant_state, fp8) or float32 is skipped with a message. Full finetuning, QAT and tensor / pipeline / expert parallel runs are also skipped. An explicit float8_training request is never overridden. Tests cover each case on CPU, and a B200 smoke through FastLanguageModel with the env set converted 196 / 196 Qwen3-1.7B layers.

…16' precision normalization), not on the load flags
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review (head f823346)

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: f823346973

ℹ️ 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".

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 27, 2026
@danielhanchen
danielhanchen merged commit 9728dee into main Nov 27, 2026
3 of 62 checks passed
@danielhanchen
danielhanchen deleted the int8-lora-base-sm120 branch November 27, 2026 15:29
danielhanchen added a commit that referenced this pull request Nov 27, 2026
…since #19965) (#20004)

## Problem


`tests/test_triton_constexpr_comments.py::test_every_constexpr_line_has_a_comment`
fails on main (`53a74eb64e`) in `Repo tests (CPU, rest)`:

```
tl.constexpr parameters without a comment:
  unsloth/kernels/int8_lora.py:213 _int8_mm_kernel.BLOCK_M
  unsloth/kernels/int8_lora.py:214 _int8_mm_kernel.BLOCK_N
  unsloth/kernels/int8_lora.py:215 _int8_mm_kernel.BLOCK_K
  unsloth/kernels/int8_lora.py:216 _int8_mm_kernel.GROUP_M
  unsloth/kernels/int8_lora.py:264 _int8_dgrad_kernel.HAS_D
  unsloth/kernels/int8_lora.py:265 _int8_dgrad_kernel.INV_SQRT_G
  unsloth/kernels/int8_lora.py:267 _int8_dgrad_kernel.BLOCK_M
  unsloth/kernels/int8_lora.py:269 _int8_dgrad_kernel.GROUP_M
```

#19965 added `unsloth/kernels/int8_lora.py`, and these eight parameters
have no comment. It shows on any PR whose `rest` shard runs, for example
the #19837 staging run.

## Fix

Comments only, no code change. Each of the eight parameters gets a
one-line comment saying what it is:
- the tile sizes
- the `K % BLOCK_K == 0` precondition that lets the K loop load unmasked
- the swizzle group
- the dgrad epilogue add
- the `1 / sqrt(G)` normalisation

## Verification

- `tests/test_triton_constexpr_comments.py`: 4 passed. Before, on main:
1 failed, listing the eight parameters above.
- `ruff format` and `ruff check`: clean.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant