Skip to content

Fix phone-deployment QAT for Gemma3 and LoRA, and write the matching ExecuTorch export config - #14376

Merged
danielhanchen merged 12 commits into
mainfrom
dh/s2-w1-qat
Oct 20, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
dh/s2-w1-qat

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes for qat_scheme = "phone-deployment" (int8-int4) and the other torchao QAT schemes, so a model trained for phones actually exports to ExecuTorch with the numerics it was trained with.

  • Gemma3 stays on int8-int4. Gemma3 used to be switched to Int4WeightOnlyConfig(group_size = 128), a CUDA layout ExecuTorch's XNNPACK backend cannot run. The loss spike that motivated the switch came from torchao replacing Gemma3TextScaledWordEmbedding with a plain FakeQuantizedEmbedding, which drops the embed_scale (sqrt(hidden_size)) multiply. Embedding subclasses now keep their own forward through QAT prepare and convert, which also covers the other scaled embeddings (Gemma, Gemma2, Gemma3n, Gemma4).
  • get_peft_model(qat_scheme = "phone-deployment") works. Only from_pretrained knew the alias.
  • int4 / fp8-int4 skip Linears whose in_features is not a multiple of 128 instead of crashing on the first forward, and warn about them, like int8-int4 and cactus already do.
  • LoRA adapters are no longer fake-quantized. Only the frozen base weights (and activations) are, matching torchtune's QATLoRALinear.forward; the adapters are merged into the base weight before the real quantization. UNSLOTH_QAT_FAKE_QUANTIZE_LORA=1 keeps the previous behaviour.
  • save_pretrained_torchao on a phone-deployment model prints the ExecuTorch flags that reproduce the QAT numerics (qmode 8da4w, group_size 32, use_hqq false, embedding_quantize 8,0) and, for local saves of architectures export_llm supports (Llama, Qwen2 / 3 / 3.5, Phi-3, LFM2), writes them to executorch_export_config.yaml next to the quantized checkpoint. Other architectures such as Gemma3 get a pointer to optimum-executorch with the same settings. Only Unsloth's own phone recipe gets the hint; a custom TorchAOConfig does not. ExecuTorch's export_llm defaults (group size 128, HQQ) do not match the trained scheme.

Results

gemma-3-270m-it, LoRA, eval loss on a fixed text, no training:

arm eval loss
no QAT 1.812
main, int8-int4 (silently switched to CUDA int4) 2.098
this PR, int8-int4 2.152
this PR with the embedding fix disabled 18.97

Qwen3-0.6B on CPU, QAT fake-quant model vs ExecuTorch's quantization:

ExecuTorch settings KL vs QAT model ppl
8da4w, group 32, affine, embedding 8,0 (what this PR writes) 0 (bit-exact) 30.3
export_llm defaults (group 128, HQQ) 0.38 35.6

Tests

tests/test_qat_phone_deployment.py (14 tests: alias, Gemma3 scheme kept, embed_scale kept through prepare / convert for several convert paths, int4 divisibility, LoRA exclusion across 4 schemes, opt-out) plus picklability of the generated embedding class, and save-path cases in tests/saving/test_qat_torchao_save.py (PEFT and full models with a stale -torchao directory, custom recipe, Gemma3, Hub).

main this PR
phone-deployment tests 13 failed, 1 passed 14 passed
phone + saving tests, torch 2.14.1 / transformers 5.20.2 / peft 0.21.2 13 failed, 13 passed 28 passed
phone tests, torch 2.10 / transformers 4.57.6 / peft 0.18.0 14 passed

Not covered

  • No .pte export or on-device XNNPACK run.
  • No training-length comparison of LoRA adapters with and without fake quantization; only step-0 loss was measured for Gemma3.

…t_model

torchao swaps every nn.Embedding for a plain FakeQuantizedEmbedding, which
drops the embed_scale multiply of Gemma3TextScaledWordEmbedding (and the
other scaled word embeddings). That, not the vocabulary size, is why
int8-int4 QAT on Gemma3 started at a loss near 17; the workaround switched
to Int4WeightOnlyConfig, a CUDA layout ExecuTorch cannot run. Keep the
subclass forward through QAT prepare and convert, drop the switch, and
accept qat_scheme="phone-deployment" in _prepare_model_for_qat so
get_peft_model takes the same alias as from_pretrained.
…p size

int4 and fp8-int4 QAT only checked in_features >= 128, so a Linear such as
in_features 960 or 2880 was fake-quantized and the first forward failed in
the PerGroup(128) reshape. Leave those layers in full precision with a
warning, as int8-int4 and cactus already do.
QAT LoRA should fake-quantize only the frozen base weight, as torchtune's
QATLoRALinear does: lora_A and lora_B are merged into the base weight before
quantization, so quantizing them separately adds noise that never ships.
UNSLOTH_QAT_FAKE_QUANTIZE_LORA=1 restores the old behaviour; models without
LoRA modules are unchanged.
…torchao save

ExecuTorch export_llm defaults to 8da4w group_size 128 with HQQ, which does
not match the int8-int4 QAT recipe (PerGroup(32) affine int4 Linears, int8
per-row embeddings). save_pretrained_torchao now prints the matching flags
and writes executorch_export_config.yaml next to the saved model.
@danielhanchen danielhanchen self-assigned this Oct 20, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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-10-20T18:50:28.677357Z 48d20b6 Manual request
🔒 Security Review ⚠️ Failed 2026-10-20T16:03:03.751068Z 78bd7c6 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…rchs, also on Hub saves; make the QAT embedding class picklable

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: fa2a7c2871

ℹ️ 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/save.py

# HF model_types whose architecture ExecuTorch's export_llm ModelType covers (llama2/3.x, smollm2, qwen2.5, qwen3,
# qwen3.5, phi-4-mini, lfm2); anything else (Gemma3, ...) goes through optimum-executorch instead.
_EXPORT_LLM_MODEL_TYPES = {"llama", "qwen2", "qwen3", "qwen3_5", "qwen3_5_text", "phi3", "lfm2"}

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 Gate export hints by supported model variant

For unsupported variants that share one of these broad Hugging Face model_type values, this writes a config and recommends export_llm even though no usable base.model_class exists. For example, every dense Qwen3 model reports qwen3, but ExecuTorch currently supports only the 0.6B, 1.7B, and 4B variants, as documented in its Qwen3 support list; saving a phone-deployment Qwen3-8B model therefore produces guidance the user cannot complete. Check the concrete architecture/size against ExecuTorch's ModelType entries rather than accepting the entire model family.

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.

Not changing this. In export_llm every ExecuTorch-defined model_class (all qwen3_, qwen3_5_, llama3*, lfm2_*) builds the same Llama2Model from base.params (examples/models/llama/export_llama_lib.py, EXECUTORCH_DEFINED_MODELS and _load_llama_model); the model_class value only picks the Hugging Face repo to download when no checkpoint is passed. The size comes from the params json, which the generated config tells the user to supply along with the converted checkpoint, so a Qwen3-8B exports the same way as the listed sizes.

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 Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 48d20b6289

ℹ️ 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 7c0e7d2 into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the dh/s2-w1-qat branch October 20, 2026 19:24
danielhanchen added a commit that referenced this pull request Oct 20, 2026
)

## Problem


`tests/test_qat_phone_deployment.py::test_fake_quantized_embedding_unpickles_in_fresh_process`,
added in #14376, fails in the CPU `Repo tests (CPU, rest)` shard on
every PR whose merge includes #14376 (for example #14350):

```
File "/home/runner/work/unsloth/unsloth/unsloth/_gpu_init.py", line 245, in <module>
  import unsloth_zoo
...
NotImplementedError: Unsloth cannot find any torch accelerator? You need a GPU.
```

The test pickles the fake-quantized embedding and loads it in a fresh
`python -c` child. That class is defined in `unsloth.models._utils`, so
unpickling imports `unsloth`. With a CPU-only torch, `unsloth` refuses
to import. That refusal is by design, so the product is right and the
test is not. The parent test process gets the CUDA spoof from
`tests/conftest.py`, but the child has no conftest.

## Fix

The child adds `tests/` to `sys.path`. When torch reports no CUDA, it
applies `_zoo_aggressive_cuda_spoof` before unpickling, the same spoof
the CPU CI uses. On a host with a real GPU the branch is skipped, so the
child loads the embedding exactly as before.

## Verification

In a CPU-only venv (torch 2.10.0+cpu, torchao 0.18.0, unsloth-zoo
`e1d0b6d6d4` as CI installs it), with `PYTHONPATH` cleared:

- main: the test fails with the error above.
- This change: `tests/test_qat_phone_deployment.py` 20 passed.
debojyoti-dev pushed a commit to debojyoti-dev/unsloth that referenced this pull request Oct 22, 2026
…ked paths (unslothai#14702)

QAT restores Embedding subclasses such as Gemma3TextScaledWordEmbedding
on top of torchao's FakeQuantizedEmbedding (unslothai#14376). Two paths still
skipped the weight fake quantizer, so training saw the unquantized
embedding that export later quantizes.

1. Float32 Gemma. With UNSLOTH_FORCE_FLOAT32, unsloth_zoo replaces the
Gemma3 / Gemma4 embedding forward with one that calls
F.embedding(self.weight) directly. The restored class only fake
quantized through super().forward(), so the quantizer never ran.
2. Accelerate hooks. _copy_embedding_subclass_state copied the instance
forward that add_hook_to_module installs. That forward is a partial
bound to the old module, so the replacement ran the old, unquantized
embedding.

Fix:
- The restored class runs the original forward on the fake quantized
weight (scoped reparametrization). A plain lookup sits behind super(),
so the upstream path is still quantized exactly once.
- The instance forward is no longer copied. The Accelerate hook is
re-attached to the replacement (offload hooks excluded).

Tiny Gemma3 on CPU, int8-int4, fake quantizer calls per embedding
forward:

| Path | Before | After |
|---|---|---|
| upstream forward | 1 | 1 |
| UNSLOTH_FORCE_FLOAT32 forward | 0 (output equals unquantized) | 1 |
| AlignDevicesHook on the embedding | 0 (output equals unquantized) | 1
|

Tests: new cases in tests/test_qat_phone_deployment.py cover the
direct-weight forward, the hooked embedding and fullgraph tracing. The
direct-weight and hooked cases fail before this change. The QAT test
files pass on CPU (85 passed, 7 CUDA-only skips).


## Scope of the embedding swap (later commits)

- An offloaded embedding (one Accelerate `AlignDevicesHook`, also inside
a `SequentialHook`) keeps its hook on the fake quantized replacement; at
save time its weight and buffers are loaded from `weights_map` on CPU
before conversion or stripping.
- An embedding with any other instance `forward` override or forward
hooks is left out of QAT with a one-time warning and is trained and
saved unquantized, with its override and hooks untouched. Previously it
was swapped and the hooks were silently dropped.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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