Repository navigation
Fix phone-deployment QAT for Gemma3 and LoRA, and write the matching ExecuTorch export config - #14376
Conversation
…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.
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. |
…where a sibling exists [skip ci]
…rchs, also on Hub saves; make the QAT embedding class picklable [skip ci]
|
@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: 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".
|
|
||
| # 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"} |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
… fresh processes can load it [skip ci]
…kle through Module state [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
) ## 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.
…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>
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.int8-int4. Gemma3 used to be switched toInt4WeightOnlyConfig(group_size = 128), a CUDA layout ExecuTorch's XNNPACK backend cannot run. The loss spike that motivated the switch came from torchao replacingGemma3TextScaledWordEmbeddingwith a plainFakeQuantizedEmbedding, which drops theembed_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. Onlyfrom_pretrainedknew the alias.int4/fp8-int4skip Linears whose in_features is not a multiple of 128 instead of crashing on the first forward, and warn about them, likeint8-int4andcactusalready do.QATLoRALinear.forward; the adapters are merged into the base weight before the real quantization.UNSLOTH_QAT_FAKE_QUANTIZE_LORA=1keeps the previous behaviour.save_pretrained_torchaoon 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 architecturesexport_llmsupports (Llama, Qwen2 / 3 / 3.5, Phi-3, LFM2), writes them toexecutorch_export_config.yamlnext 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 customTorchAOConfigdoes not. ExecuTorch'sexport_llmdefaults (group size 128, HQQ) do not match the trained scheme.Results
gemma-3-270m-it, LoRA, eval loss on a fixed text, no training:
int8-int4(silently switched to CUDA int4)int8-int4Qwen3-0.6B on CPU, QAT fake-quant model vs ExecuTorch's quantization:
8da4w, group 32, affine, embedding 8,0 (what this PR writes)export_llmdefaults (group 128, HQQ)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 intests/saving/test_qat_torchao_save.py(PEFT and full models with a stale-torchaodirectory, custom recipe, Gemma3, Hub).Not covered
.pteexport or on-device XNNPACK run.