Skip to content

Add unsloth.precision: one registry for low-precision recipes, refusals and high-precision layers - #16387

Merged
danielhanchen merged 21 commits into
mainfrom
dh/precision-registry
Nov 1, 2026
Merged

danielhanchen merged 21 commits into
mainfrom
dh/precision-registry

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Why

Low-precision training choices are spread across float8_training.py, the QAT schemes in _utils.py and the FP8 / NVFP4 / MXFP4 kernels, each with its own name checks. Requests for formats Unsloth cannot train in yet (MXFP6, MXFP8 or NVFP4 under float16, blockwise FP8 off Hopper) fall through to a generic "not supported" or, worse, start loading first. The float8 layer filter also matches routers by exact name only, so a router called wg is converted to fp8.

What

A new unsloth.precision package that every low-precision path reads from:

  • Recipe registry: one entry per format with the forward / input-grad / weight-grad dtypes and scaling granularity, the GradScaler kind, and a per-GPU gate table (T4 fp16 only; L4 fp8; RTX PRO 6000 per the measured table below).
  • High-precision layers by structure: output head and tied weights, embeddings, MoE routers (found by shape, not name) and the first / last blocks.
  • Refusals before any model mutation: MXFP6 training, float16 with MXFP8 / NVFP4 / blockwise FP8, blockwise FP8 off sm90, and MXFP8 / NVFP4 training marked as not yet available, each with its own message.
  • Engagement: UNSLOTH_STRICT_ENGAGE=1 turns "converted zero layers" into an error, and a counter records low-precision matmul calls.

float8_training.py now reads its recipe names and measured-faster table from the registry with unchanged values (a test pins them to the previous literals). The loader passes dtype, so a float16 MXFP8 request is refused before loading. QAT records how many layers it fake-quantizes.

One intended behaviour change: the float8 filter also keeps shape-detected routers in high precision. On dense and MoE Qwen3 the converted set is identical to before.

Measured support (torch 2.13, torchao 0.18, op level, fp32 reference)

format RTX PRO 6000 (sm120) bf16 L4 (sm89) bf16
float8 tensorwise pass, compiled 1.56-1.61x eager pass; compiled weight grad NaN at 2048x4096x4096 (kept refused, as before)
float8 rowwise pass, 0.54-1.24x pass, 0.69-1.14x
MXFP8 linear (torchao) pass, 1.49-1.55x not supported
NVFP4 training (torchao) fails (stochastic rounding / Inductor swizzle) not supported
blockwise FP8 (torchao) sm90 only sm90 only
fp8 frozen weight (fwd + dX) 1.42-1.64x 1.38-1.50x

Tests

  • tests/test_precision_registry.py: 26 CPU tests (refusals raise before load, registry values pinned to the previous literals, structural router / head / embedding selection, strict engagement).
  • Float8, QAT and precision suites: 182 passed / 14 skipped (156 / 14 before, the difference is the new file).
  • Before this change: MXFP6 and float16 MXFP8 / NVFP4 requests get the generic message, a router named wg is converted to fp8, and strict mode with zero converted layers returns []. After: specific refusals, the router stays in high precision, strict mode raises.

Not covered

  • No model-level accuracy or step-time change is claimed; the table is op level.
  • Hopper and B200 cells, and multi-GPU fp8.

…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.
@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 ⚠️ Failed 2026-11-01T10:23:57.171765Z
We couldn’t complete this review. Comment @codex review to try again.
94a8548 PR opened
ℹ️ 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.

… 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.
…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]
…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.
…ainers that own stacked experts

SwitchTransformers keeps its experts in a ModuleDict, so its routers were missed and a wrapped router's
inner Linear could be converted to fp8. JetMoE's attention MoE container (self_attention.experts) owns
stacked expert weights and its own router, but every module under a path containing 'expert' was skipped.
Expert subtrees are now excluded by structure: members of an experts collection and shared-expert MLPs.
Adds SwitchTransformers and JetMoE family rows and a ModuleDict float8 filter case.

[skip ci]
…gerly (torch < 2.9 has no ignore_compile_internals)

[skip ci]
@danielhanchen
danielhanchen merged commit 0bfae01 into main Nov 1, 2026
@danielhanchen
danielhanchen deleted the dh/precision-registry branch November 1, 2026 13:56
danielhanchen added a commit that referenced this pull request Nov 1, 2026
…16428)

## Summary

`Source lint`'s "No new risky loader call sites" step fails on every PR
based on current main. #16413 shows it, a frontend-only PR:

```
1 risky loader call site(s) not in the baseline:

  unsloth/models/float8_training.py:29  [dynamic-import] spec_from_file_location
```

#16387 (`0bfae01738`, "Add unsloth.precision") added `_load_precision()`
to `unsloth/models/float8_training.py`. It imports `unsloth.precision`.
When the file is loaded on its own, as the gloo test workers do by path
without the `unsloth` package, it falls back to
`spec_from_file_location` on `unsloth/precision/__init__.py` in the
sibling directory. The path is built from `__file__` and a constant, not
from any input, so it is safe. It just was not recorded.

## Change

`python scripts/lint_risky_loaders.py --update`, as the step asks, then
the new entry's `REVIEW ME` replaced with why it is safe. The diff adds
that one entry and changes nothing else in the baseline.

## Testing

- `python scripts/lint_risky_loaders.py`: exit 1 on main with the
finding above; here, `ok: 116 risky loader call site(s), all recorded`.
- `tests/security/test_lint_risky_loaders.py`: 46 passed.
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