Skip to content

FP8 LoRA: fp8 forward and input gradient on the frozen 16-bit base - #16423

Merged
danielhanchen merged 68 commits into
mainfrom
dh/fp8-lora-frozen-base
Nov 4, 2026
Merged

danielhanchen merged 68 commits into
mainfrom
dh/fp8-lora-frozen-base

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

Summary

Add an explicit FP8 recipe for LoRA over frozen 16-bit base layers. Forward and input-gradient GEMMs use FP8; LoRA parameters and updates retain their existing precision. Exact master weights remain available for saving, adapter merging and generation.

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name,
    load_in_4bit = False,
    float8_training = "fp8_lora",
)

Use the explicit "fp8_lora" recipe. True and "tensorwise" remain refused until the precision registry supports a named default.

Behavior

  • Cache frozen FP8 weights and use the supported scaling for the device: tensorwise on L4, rowwise on RTX PRO 6000 Blackwell. Compiler-visible custom operations retain their backward definitions.
  • Restore exact masters and dense execution for inference, merging and plain unload. Training setup enables the requested recipe again. Deep copies preserve their own bindings and weights.
  • Preserve native MLP biases, normalization dtypes and LoRA accumulation. Canonical native/generated RMSNorm and MLP bindings preserve the independent FP8 reference gradients.
  • Keep masters resident for distributed runs and direct weight readers; exclude shared/sharded weights, block-swapped layers, output heads and routers.
  • Reject incompatible quantized bases, QAT and unsupported hardware before loading. Limit compatibility fallbacks to recognized output-type refusals; propagate unrelated failures.

Validation

The current production code passes all 7,840 gradient comparisons and exact A/A controls on L4 and G4, with exact 20-step loss arrays, real FP8 forward/input-gradient engagement, zero 16-bit base fallbacks and zero graph breaks. The disabled-binding negative control fails 7,327 comparisons. Separate real GPU differentials cover biased MLPs, mixed/FP32 normalization and both unload paths. Native golden, compiled golden and Compute Sanitizer checks are recorded separately.

The exclusive G4 Qwen3-4B training comparison uses six fresh processes per arm, ABBA x3, 61 optimizer steps, batch 2, accumulation 3, sequence 2048 and seed 3407:

Metric Baseline FP8 LoRA
Median steady optimizer step 1.221756844 s 0.909647090 s
Across-run median spread 0.001248705 s 0.004362128 s
Training peak allocation 30,927.54 MiB 20,967.45 MiB
Unique graphs (training + held-out evaluation) 10 8
Graph breaks 0 0

Steady training is 1.3431x faster and 32.2% lower training allocation. Host RSS increases from approximately 9,153 MiB to 13,423 MiB because exact masters are retained in host memory. Across 80 paired held-out 512-token windows, the NLL difference is -0.000165524 with bootstrap 95% CI [-0.000914062, +0.000592836]; no accuracy difference is resolved.

Both inference APIs pass on an exclusive G4, with six processes per arm per condition, identical 64-token outputs and no measured regression. The following are steady medians from fresh compiler-cache processes; cells show baseline / FP8-trained-path setup:

API Prefill tok/s Decode tok/s TTFT ms Steady peak GiB First-call phase peak GiB
generic 181.21 / 180.87 40.65 / 40.52 36.281 / 36.139 1.191298 / 1.191298 1.306471 / 1.306471
optimized 304.79 / 303.58 89.06 / 88.24 22.894 / 23.014 1.278602 / 1.278602 1.278602 / 1.278602

A separate primed Mega-cache comparison also passes for the generic loader. The optimized loader does not arm Mega-cache; its second condition is a repeated control. Inductor/Triton directories remain fresh per process, and steady measurements follow in-process warmup. Cold-phase latency and steady throughput are recorded separately.

A separate cold-cost audit uses three fresh processes per arm. First optimizer steps measure 14.191 / 12.053 seconds, and the reported _compile.compile_inner category measures 11.428 / 8.723 seconds, with zero graph breaks and positive gradients. These initialization costs are separate from the 61-step steady benchmark; nested compiler categories are not summed.

Scoped tests pass on Linux 365, Windows 364 and macOS 326 cases, with platform skips and eight GPU deselections retained. Real gfx1151 Linux ROCm passes base 237/head 363/integration 363; Windows CPU passes base 201/head 334/integration 334. Selected CPU compatibility matrices cover the Torch 2.6 floor, Transformers 4.57.6 through the tested 5.x releases and PEFT 0.18.0 through 0.20.0.

The exact-head switchboard is CURRENT/NO_REGRESSION. Regression smoke matches 66 passed, 13 xpass and 24 skipped on both arms. Two Gemma4 jobs retain identical baseline/head checkpoint-error VOIDs; matched workaround controls are separate evidence. The same-source backend g-r diagnostic passes 35,322 tests and 103 subtests, with 578 skips; the earlier worker loss did not recur. The initial worker-death cause remains unproven.

Physical Windows NVIDIA, Windows ROCm kernels, Apple GPU FP8, genuine multi-GPU FP8 and MIG execution were not measured. UI impact is NO; this change has no UI screenshot pair.

…tural HP layers, engagement

One table entry per format (fp16, bf16, FP8 tensorwise / rowwise / rowwise_with_gw_hp / blockwise,
MXFP8, MXFP6, NVFP4, grouped MoE FP8 / MXFP8, QAT schemes, frozen fp8 bases) with per-GEMM
fwd / dgrad / wgrad dtypes and scaling, high-precision layer policy, GradScaler kind and a per-GPU
gate table filled from the L4 / RTX PRO 6000 probe.

float8_training reads its named recipes and measured-faster table from the registry (unchanged
values), refuses MXFP6 / MXFP8 / NVFP4 / blockwise with their own reasons before the model is
loaded (fp16 for formats whose quantizer rejects it, blockwise off sm90), skips MoE routers found
by structure as well as by name, and records engagement. QAT records how many layers it
fake-quantizes. UNSLOTH_STRICT_ENGAGE=1 turns a zero-layer conversion into an error.
float8_training with LoRA (full_finetuning = False) now runs the frozen base GEMMs in fp8 instead of
refusing: the base weight is quantized once (tensorwise e4m3, cached in both orientations, requantized
when the weight changes in place), activations are cast tensorwise e4m3 and output gradients e5m2, and
torch._scaled_mm writes bfloat16 (cast back for float16 activations). The LoRA branch stays 16 bit.
float8_training = 'fp8_lora' runs wherever the GPU has fp8 tensor cores; True only where the registry
row fp8_lora_tensorwise is named. T4 / A100 / ROCm, float32, 4 / 8 bit / fp8 bases and QAT refuse before
the model loads. Unsloth's LoRA kernels take the fp8 state as a packed weight state; the PEFT path runs
the same ops through the base layer's forward. Both are opaque ops under torch.compile.
… as the expert count

Qwen3-Next has num_experts == moe_intermediate_size == 512, so every expert and
shared-expert gate_proj matched the config-width fallback and was kept out of
float8 conversion (size_filter = False) and listed as a router. Skip modules
inside an expert / shared expert, and accept gate_proj only beside an experts
container.
…ratch paths

The sm89 / sm120 / sm100 gate evidence printed outputs/precision_probe and a plans/ file in
user-facing refusals; neither exists in the repo.
UNSLOTH_FP8_LORA_SCALING=row quantizes activations and output gradients with one e4m3 scale per row
(one Triton pass), the weight keeping its cached tensorwise scale broadcast over the output columns, so
a massive-activation token no longer pushes the rest of the tensor into e4m3 subnormals.
…ts list

An MoE with more experts per block than blocks (Qwen2-MoE: 60 experts, 24 layers) returned
model.layers.0.mlp.experts, so first_n / last_n / last_frac kept experts in high precision instead
of the first / last decoder blocks. Ignore experts lists and lists nested inside another block list.
…) calls

A plain TorchDispatchMode makes Dynamo refuse fullgraph frames (non-infra torch dispatch mode
present). The counter now sets ignore_compile_internals, so compiled callables run and their
low-precision GEMMs are still counted at runtime.

[skip ci]
From the L4 / RTX PRO 6000 A/B: rowwise _scaled_mm is slower than bf16 on the L4 but the fastest choice on
the RTX PRO 6000, so auto picks per-token scales on compute capability 12.x (registry row
fp8_lora_rowwise) and tensorwise elsewhere. The transposed fp8 copy for dgrad is no longer cached by
default (about 1% slower, 0.4 / 1.3 GB less at Qwen3-0.6B / 1.7B); the transpose runs inside the opaque
dgrad op, so torch.compile never traces an fp8 transpose (Inductor's 2D-tiled fp8 transposes write
corrupt bytes on sm89). Gates stay explicit with the measured evidence.
…ecision ops

decoder_layers accepts a one-block decoder, finds the language decoder from the input
embedding's nearest stack (Idefics3 / SmolVLM on transformers 4.57 returned the vision
encoder), and gives an encoder-only model (BERT) its single stack. Lists of bare Linears
are not block stacks.

find_routers treats stacked 3-D expert weights as an experts container whatever their
name and reads a router's width through a gating module that wraps one Linear
(GraniteMoE / GraniteMoeHybrid on 4.57 found no router).

find_output_heads keeps task heads outside the base model (score, classifier) when the
model has no output embedding.

count_lowp_gemms counts opaque custom ops that run low-precision GEMMs inside
(unsloth::nvfp4_qat_linear, unsloth fp8 block matmuls, unsloth_zoo::mxfp4_ogs_moe,
fbgemm f8f8bf16 family) once at their boundary, matched by qualified name.

New parametrized test over 43 tiny transformers configs on the meta device.
…transpose for dgrad

The GPU now holds only the fp8 copy of each converted base weight (1 byte per weight against
bf16 LoRA's 2). The 16-bit master moves to pinned host memory as the same Parameter, so
state_dict, save and merge still read the exact weight: fast_dequantize copies it back as is,
PEFT merge / unmerge and moves to another device or dtype restore it first, and decode rows
use the dequantized fp8 weight. Kept on the GPU for 16-bit dgrad, distributed runs and shared
Parameters; UNSLOTH_FP8_LORA_OFFLOAD_MASTER=0 opts out.

dgrad's K-major operand is transposed by a Triton kernel with one square tile size (non-square
2D fp8 transposed stores miscompile on sm89). Gate evidence no longer names scratch paths.
# Conflicts:
#	tests/test_precision_registry.py
#	tests/test_precision_selectors_families.py
#	unsloth/models/float8_training.py
#	unsloth/models/loader.py
#	unsloth/precision/engage.py
#	unsloth/precision/recipes.py
#	unsloth/precision/selectors.py
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-04T01:55:51.754184Z fef0c61 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.

…the device, added adapters land on the compute device

[skip ci]
… before placement, load_state_dict requantizes eagerly

[skip ci]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 3, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: d96be6b104

ℹ️ 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 3, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 4, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e4f395ebaf

ℹ️ 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 4, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: a4124b6517

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 231bb13b08

ℹ️ 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 Etherll/unsloth that referenced this pull request Nov 4, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: fef0c61003

ℹ️ 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
danielhanchen merged commit ee3fa40 into main Nov 4, 2026
@danielhanchen
danielhanchen deleted the dh/fp8-lora-frozen-base branch November 4, 2026 04:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant