Repository navigation
QAT: fake quantize Gemma embeddings on the float32 and Accelerate-hooked paths - #14702
Conversation
…ked paths The restored Embedding subclass relied on the original forward calling super().forward(). unsloth_zoo's UNSLOTH_FORCE_FLOAT32 Gemma3 / Gemma4 forward calls F.embedding(self.weight) directly, so it skipped the weight fake quantizer. Run the original forward on the fake quantized weight instead, with a plain lookup behind super() so it is quantized once. Copying instance attributes also copied Accelerate's hook forward, a partial bound to the old module, so a dispatched embedding ran the old unquantized module. Skip the instance forward and re-attach the hook to the replacement.
|
@codex review |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 993c9907a1
ℹ️ 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".
| if hook is None or hasattr(dst, "_hf_hook") or getattr(hook, "offload", False): | ||
| return # offload hooks own the weights map; they are not rebuilt here |
There was a problem hiding this comment.
Preserve offload hooks on replacement embeddings
With an Accelerate CPU- or disk-offloaded model, AlignDevicesHook(offload=True) stores the real embedding weight in weights_map and leaves the module parameter on the meta device between calls. This branch discards that hook, while the new forward no longer delegates to the hooked source module, so the replacement attempts to fake-quantize a meta weight and the first model forward fails. The offload hook and its weight mapping need to be rebuilt for the replacement, or this configuration must be rejected before replacing the embedding.
Useful? React with 👍 / 👎.
With the embedding offloaded to CPU or disk, AlignDevicesHook(offload=True) keeps the real weight in weights_map and leaves the parameter on meta between calls. The replacement embedding dropped that hook, so its forward fake quantized a meta weight and returned a meta tensor. Re-attach the offload hook to the replacement (keeping its original devices), so the weight is loaded before fake quantization and offloaded again after. Offload hooks that cannot be moved (no weights_map, a weights_map missing the embedding's parameters, place_submodules, or a non AlignDevicesHook) are refused with a clear error before QAT replaces the embedding.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3541a24cc7
ℹ️ 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".
| offload = getattr(hook, "offload", False) | ||
| if offload: |
There was a problem hiding this comment.
Materialize offloaded weights before conversion
When a non-PEFT QAT model has an AlignDevicesHook(offload=True), this path deliberately leaves the replacement embedding's weight on meta between forwards. Saving later calls _convert_torchao_model, whose two quantize_ transforms read the weight directly without invoking the hook; FakeQuantizedEmbedding.to_embedding() therefore produces another meta embedding, after which PTQ conversion either fails on the meta tensor or saves no real embedding weight. The offloaded weight must be materialized for conversion (and the hook handled on the final replacement), or this configuration should be rejected before QAT preparation.
Useful? React with 👍 / 👎.
| # An instance `forward` is a runtime wrapper (Accelerate's hook) bound to src: copying it runs src, not dst. | ||
| if ( | ||
| name.startswith("_") | ||
| or name == "forward" |
There was a problem hiding this comment.
Preserve non-Accelerate instance forwards
When an embedding subclass has a legitimate instance-level forward override, this unconditional skip silently replaces that behavior with original_cls.forward. Not every instance override is an Accelerate wrapper: for example, _install_offload_embedding_hooks in unsloth/models/vision.py installs _unsloth_offload_forward this way, and downstream code can similarly patch routing or output semantics per instance. Such embeddings lose the override after QAT preparation (and a host-offloaded embedding can consequently attempt its lookup with inputs on the wrong device); identify the Accelerate wrapper specifically and preserve or rebind other instance forwards to the replacement.
Useful? React with 👍 / 👎.
…overrides Converting or stripping QAT reads embedding weights directly, not through forward, so an offloaded fake quantized embedding (weight on meta between calls) converted to another meta embedding. Before _convert_torchao_model and _strip_torchao_fake_quantization, load its real weight from the offload hook's weights_map onto the execution device and drop the hook. Copying subclass state skipped every instance forward. Only Accelerate's wrapper must be skipped; other overrides bound to the old module (e.g. Unsloth's offloaded embedding forward) are now rebound to the replacement, along with their forward pre / post hooks and _unsloth_ flags. An override under an Accelerate hook is recovered from _old_forward before the hook is re-attached. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 799eef967d
ℹ️ 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".
| isinstance(forward, functools.partial) and forward.args and forward.args[0] is src | ||
| ): | ||
| return # bound to src in a way that cannot be rebound safely | ||
| dst.forward = forward |
There was a problem hiding this comment.
Fake-quantize copied instance forwards
When an embedding has a legitimate instance-level override that reads self.weight directly, assigning that method here bypasses the generated class's forward, which is the only place weight_fake_quantizer is applied. Unlike the test override, such a method need not delegate through type(self).forward; QAT then trains against the full-precision lookup even though conversion quantizes the embedding, recreating the numerical mismatch this change is intended to prevent. The copied override should run within the fake-weight reparametrization scope rather than being installed as the raw callable.
Useful? React with 👍 / 👎.
| if torchao_config.prequantization_transform is not None: | ||
| torchao_config.prequantization_transform(model) | ||
| embedding_subclasses = _embedding_subclasses(model) | ||
| _check_offloaded_embeddings(embedding_subclasses) |
There was a problem hiding this comment.
Validate only embeddings selected for QAT
When a model has an unsupported offload hook on an embedding subclass but the selected recipe quantizes only linear layers (for example the built-in int4 or int8 schemes), this unconditional check still raises even though quantize_ would leave that embedding and its hook untouched. This regresses otherwise valid QAT preparation for such offloaded models; restrict the validation to embeddings matched by at least one configured filter.
Useful? React with 👍 / 👎.
| from accelerate.hooks import remove_hook_from_module | ||
| from accelerate.utils import set_module_tensor_to_device | ||
|
|
||
| device = hook.execution_device if hook.execution_device is not None else "cpu" |
There was a problem hiding this comment.
Materialize offloaded embeddings on the storage device
For normal Accelerate CPU/disk offload, execution_device is the CUDA device used only during a forward, while the real embedding is kept in weights_map on CPU or disk. Selecting that CUDA device here moves the entire full-precision embedding onto the GPU during save-time conversion or stripping; because these models generally offload the embedding specifically when it does not fit in VRAM, saving can now OOM before quantization. Materialize from weights_map on CPU (or its storage device) for conversion instead of using the forward execution device.
Useful? React with 👍 / 👎.
…ds, check only selected embeddings Materialize an offloaded fake quantized embedding from its weights_map on the CPU, where offload stores it, instead of the execution GPU, which may not fit it; its buffers follow so the module stays on one device. A copied instance forward override that reads self.weight directly skipped the weight fake quantizer. Run it, like the generated class forward, with the weight swapped for its fake quantized value. The swap is re-entrant (inside it weight is a plain tensor), so an override that calls the class forward is still quantized once. The converted plain embedding no longer inherits weight_fake_quantizer. Refuse an unmovable offload hook only on embeddings a configured QAT filter selects, so Linear-only recipes (int4, int8) prepare as before. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5efc24be99
ℹ️ 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".
| from accelerate.hooks import remove_hook_from_module | ||
| from accelerate.utils import set_module_tensor_to_device | ||
|
|
||
| values = {n: hook.weights_map[n] for n, _ in module.named_parameters(recurse = False)} |
There was a problem hiding this comment.
Materialize offloaded buffers from the weights map
When Accelerate dispatches an embedding with offload_buffers=True and the module was initialized on meta, this snapshot preserves only parameters. After the hook is removed, registered buffers such as an embedding scale can therefore remain on meta, and the later set_module_tensor_to_device(module, name, "cpu") call has no value with which to materialize them, causing both conversion and fake-quantization stripping to fail while saving. Capture offloaded direct buffers from hook.weights_map alongside the parameters and supply those values when moving them to CPU.
Useful? React with 👍 / 👎.
…conversion With Accelerate offload_buffers = True on a meta-initialized module, the embedding's registered buffers (Gemma's embed_scale) also live only in the hook's weights_map. Materializing kept just the parameters, so after removing the hook the buffers stayed on meta and conversion / strip failed with 'embed_scale is on the meta device, we need a value'. Capture direct buffers present in weights_map with the parameters and load them onto the CPU; a meta buffer with no stored value raises a clear error. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 019facbec1
ℹ️ 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".
| and getattr(hook, "offload", False) | ||
| and getattr(hook, "weights_map", None) is not None |
There was a problem hiding this comment.
Detect offload hooks inside SequentialHook
When an offloaded embedding has another Accelerate hook chained with add_hook_to_module(..., append=True), _hf_hook is a SequentialHook, so this top-level offload check is false even though one of its child hooks is an AlignDevicesHook(offload=True). Preparation consequently accepts and moves the composite hook, but conversion skips materialization and attempts to convert the meta embedding weight. Inspect nested hooks for an offload hook, or reject this supported chained-hook configuration before QAT preparation.
Useful? React with 👍 / 👎.
| return _call_with_fake_quantized_weight(self, fn, *args, **kwargs) | ||
|
|
||
| return _unsloth_fake_weight_forward |
There was a problem hiding this comment.
Make wrapped instance forwards pickle-safe
When an embedding has a pickleable instance-level bound forward, this nested wrapper is rebound onto the fake-quantized replacement and retained in the module state returned by __reduce_ex__. Python serializes a bound method by its function name, but _unsloth_fake_weight_forward is a local function and is not an attribute on the rebuilt module, so unpickling the QAT embedding fails with AttributeError; this affects torch.save and spawned workers for the instance-forward path added here. Use a module-level wrapper or explicitly reconstruct the wrapped forward during unpickling.
Useful? React with 👍 / 👎.
| for handle_id, hook in getattr(src, hooks_name).items(): | ||
| dst_hooks.setdefault(handle_id, hook) |
There was a problem hiding this comment.
Preserve removability when transferring forward hooks
When the source embedding has an instance forward plus a removable user hook, copying the hook directly into the replacement's registry leaves the returned RemovableHandle weak-referencing the old module's registry. Calling handle.remove() later—such as when disabling NEFTune or input-require-grad hooks—removes only the obsolete copy while the replacement continues invoking the hook. Transfer only the internal offload hooks or recreate and retain handles for hooks that are moved.
Useful? React with 👍 / 👎.
…rebinding them Rebinding instance-level forward overrides and forward hooks onto the fake quantized replacement kept producing edge cases (fake quantization scope, pickling local wrappers, RemovableHandles pointing at the old registry). Narrow what QAT swaps: - supported: plain and subclass embeddings with no instance forward, or only Accelerate's wrapper over the class forward, with at most one AlignDevicesHook, also inside a SequentialHook (the whole hook moves; a nested offload hook is found for the checks and for materializing before convert / strip). Plain nn.Embedding keeps its Accelerate hook too. - anything else (an instance override, forward pre / post hooks, two AlignDevicesHooks) is left out of QAT with one warning naming the reason; the filters skip it at prepare, convert and save, so it is trained and saved unquantized and nothing is rebound. - transformers' enable_input_require_grads hook and PEFT's make_inputs_require_grad hook are not reasons to skip: they are re-registered on the replacement (enable_input_require_grads is re-run so its owner's handles stay valid).
|
Round 5 is addressed in the latest commit by narrowing what the QAT embedding swap supports instead of copying more state onto the replacement:
Tests in |
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
pre-commit.ci fails `ruff-format-with-kwargs` on every open PR (#14806, #14805, #14803, #14790, #14785, #14781, #14780, #14777, #14776, #14775, #14774, #14773, #14772, #14770, #14769, #14768, and others): "files were modified by this hook". pre-commit.ci runs the hooks on all files, and 20 files on main (26 by the time this lands) are not in the formatter's output, so every PR is reformatted outside its own diff. Where pre-commit.ci can push, its autofix commit drags those unrelated files into the PR (for example #14790's touches `tests/test_block_compile.py`, `tests/test_bnb_integration_compile.py` and `unsloth/models/_utils.py`). The drift came in with PRs merged today, among them #14702, #14751, #14759, #14784, #14786, #14787, #14788, #14791 and the FP8 block decode, GRPO routing replay, 4-bit decode, compiled blocks and MoE LoRA target changes. ### Change `python scripts/run_ruff_format.py` (the hook's own entry point, `ruff==0.6.9` as pinned in `.pre-commit-config.yaml`) applied to those 20 files, plus 6 more from #14739, #14779 and #14806, which merged while this was open. Formatting only. ### Verification - Every changed file parses to an identical AST before and after. - A second run of the hook over the same files changes nothing (fixed point), and over all tracked Python files on this branch it changes nothing. - `ruff check` passes on the changed files; `tests/test_formatter_fixed_point.py` passes (16). Open PRs pick this up on their next pre-commit.ci run after merging main.
…all (#15385) ## Summary `_call_with_fake_quantized_weight` (added in #14702) decides whether it is already inside its own scope by checking the weight's type: a non-`nn.Parameter` weight was taken to mean "already fake quantized", and the original forward ran on it unchanged. Two legitimate callers also hand the module a plain tensor as `module.weight`: - FSDP1, which installs tensor views of its flat parameter during forward and backward (both `use_orig_params=False` and `True`). Unsloth still supports FSDP1 (`accelerate launch` with FSDP version 1, see `fsdp2_launch.fsdp_version_from_env`). - `torch.func.functional_call` / `torch.nn.utils.stateless`. In both cases the QAT embedding silently trained and evaluated against the unquantized weight: zero quantizer calls per forward, finite gradients, no warning. ## Fix - Track the scope with a per-module flag (`_unsloth_weight_fake_quantized`) instead of the weight's type, so a nested call still quantizes exactly once and every other weight, Parameter or plain tensor, is fake quantized. - When `weight` lives in the instance dict, swap that entry. FSDP1 with `use_orig_params=True` keeps the `Parameter` registered in `_parameters` while its view in `__dict__` shadows it, so swapping only the registered parameter left the unquantized view visible. - Ordinary, Accelerate-hooked, offloaded and `torch.compile(fullgraph=True)` paths are unchanged. ## Tests New in `tests/test_qat_phone_deployment.py` (CPU, gloo, single rank): | Test | origin/main | this branch | |---|---|---| | `test_functional_call_plain_tensor_weight_is_fake_quantized` | FAIL (0 quantizer calls) | PASS | | `test_fsdp1_embedding_is_fake_quantized[False]` | FAIL (0 quantizer calls) | PASS | | `test_fsdp1_embedding_is_fake_quantized[True]` | FAIL (0 quantizer calls) | PASS | | `test_nested_fake_quantized_weight_call_quantizes_once` | PASS | PASS | The rest of the file, including the #14702 tests (`test_gemma3_embedding_forward_is_fake_quantized_once[upstream|direct_weight]`, `test_accelerate_hooked_embedding_runs_fake_quantized_forward`, `test_fake_quantized_embedding_forward_compiles_fullgraph`, the offload tests), passes on both: 54 passed on this branch, 51 passed and 3 failed on origin/main. The other QAT and FSDP test files (`tests/utils/test_qat.py`, `tests/test_qat_*.py`, `tests/saving/test_qat_torchao_save.py`, `tests/test_fsdp2_native_qat_convert_generate_gloo.py`, and others) give 335 passed, 17 skipped. Tested with torch 2.13, torchao 0.18, transformers 5.17. Not run: multi-rank FSDP1 on GPUs, or older torch versions. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
QAT restores Embedding subclasses such as Gemma3TextScaledWordEmbedding on top of torchao's FakeQuantizedEmbedding (#14376). Two paths still skipped the weight fake quantizer, so training saw the unquantized embedding that export later quantizes.
Fix:
Tiny Gemma3 on CPU, int8-int4, fake quantizer calls per embedding forward:
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)
AlignDevicesHook, also inside aSequentialHook) keeps its hook on the fake quantized replacement; at save time its weight and buffers are loaded fromweights_mapon CPU before conversion or stripping.forwardoverride 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.