Repository navigation
fix(generate): make optimize() compile the forward generate() runs (#4669) - #4912
Merged
Merged
Conversation
…4669) `GPTQModel.generate()` calls `self.model.generate`; transformers' `generate` calls `self(...)`, i.e. the module's own `forward`. `optimize()` replaced `self.model` with a `torch.compile` `OptimizedModule`, whose `__getattr__` hands `generate` back to the unwrapped module, so generation stayed on the eager `forward` and dynamo compiled 0 frames (#4669 item 2). Compile `model.forward` in place instead. `self.model` stays the original `nn.Module`, a direct `model(...)` call and `generate()` both enter the compiled path, the compile fallback is preserved, and a repeated `optimize()` unwraps the previous proxy instead of stacking wrappers. Measured on Llama-3.2-1B-Instruct GPTQ (GPTQ_TORCH, fp16, GB10, 4 prompts x 16 greedy tokens, steady state): before optimize: dynamic 0.250 s (256 tok/s), static 0.251 s (255 tok/s), 0 dynamo graphs after optimize: dynamic 0.316 s (202 tok/s, 122 graphs on the first call), static 0.288 s (222 tok/s) Greedy tokens matched the eager dynamic and static runs here; compiling can still flip a near-tie token, as documented for FP8/AWQ. The static-cache auto-compile stays off by default for graph-breaking kernels (#4727); `optimize()` is the explicit opt-in, and such a kernel is slower compiled, which the issue predicted. Item 1 (static-cache 2-4x slowdown) is already fixed by #4727 and re-verified on this box: static 0.251 s vs dynamic 0.250 s, 0 graphs, identical tokens.
This was referenced Nov 17, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 17, 2026
#4937) (#4986) #4912 made `BaseQModel.optimize()` compile `model.forward` in place so `generate()` enters the compiled path (#4669). Compiling the *bound* method stored that bound method inside the compiled wrapper, and installing the wrapper as an instance attribute closed a `model -> forward -> model` cycle: the model and its VRAM survived the last user reference until a full cyclic `gc.collect()`. Compile the unbound class function instead and reach the instance through a weak reference, the same pattern `TorchLinear.optimize()` uses for `dequantize_weight` (#4871). `_CompiledModelForward` exposes `_torchdynamo_orig_callable` on demand (a stored bound method would recreate the cycle), so unwrapping callers still see the eager callable, and a repeated `optimize()` recompiles the same unbound function instead of stacking proxies. When compilation is unavailable the instance attribute is removed, so the class method is used again.
sLaffey
pushed a commit
to sLaffey/GPTQModel
that referenced
this pull request
Nov 18, 2026
…elCloud#4967) (ModelCloud#4971) `tests/test_docs_contract_refs.py` was red on main again: four citations into `gptqmodel/models/base.py` were 114 lines out of the 8-line window, because base.py keeps growing under them (ModelCloud#4894, ModelCloud#4906, ModelCloud#4912, ModelCloud#4930): docs/awq-scale-folding.md _select_prev_op 5489 -> 5667 docs/calibration-replay.md capture_layer_type_replay_kwargs 4022 -> 4200 docs/calibration-replay.md _build_layer_type_position_embeddings 4005 -> 4183 docs/fp8-scale-semantics.md _decoder_fp8_scale_semantics 4752 -> 4930 Re-anchoring the numbers would rot again at the next base.py change, so the guard now accepts a symbol-anchored citation (`path.py::symbol`) and those four docs use it. The test still resolves the symbol in the source, so a renamed or removed symbol fails; only the line number stops being part of the contract. The line-number form stays for files that are not growing. Also re-anchored the stale `:5531` on the adjacent `:postnorm` row to `base.py::_select_prev_op` and `POST_NORM_FLAG` (base.py:560). And the test now runs pre-merge: it is the first file in the AWQ CPU `unit` suite, and `docs/**` plus the test itself are added to that workflow's path filter, so a base.py or docs change runs it. On unmodified main: 4 failed, 16 passed. With the fix: 20 passed. Copying only the new test onto main (docs still citing line numbers) also fails all four, which proves the new form is actually enforced. Closes ModelCloud#4967.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #4669 (item 2; item 1 was already fixed by #4727).
Verdict per reported symptom
_generation_compile_kwargs(base.py:3294) injectsdisable_compile=Trueunless every quantized linear declaresSUPPORTS_COMPILE. Measured on GB10, Llama-3.2-1B GPTQ/GPTQ_TORCH, 4x16 greedy: static 0.251 s vs dynamic 0.250 s, 0 dynamo graphs, identical tokens.model.optimize()compiles nothinggenerate()runsoptimize()didself.model = torch_compile(self.model);OptimizedModule.__getattr__handsgenerateback to the unwrapped module, so dynamo compiled 0 frames and timing was unchanged.data_ptr()/id()guardsSUPPORTS_COMPILE=False; the policy keeps them eager (docs/generation-compile-policy.md).Fix
gptqmodel/models/base.py:optimize()compilesmodel.forwardin place (the issue's suggested fix) instead of replacingself.model:self.modelstays the originalnn.Module, sogenerate()->self(...)-> compiledforward;torch_compilefallback is preserved (_torchdynamo_orig_callable);optimize()unwraps the previous proxy and recompiles the eager callable — no stacked wrappers;to()/dtype moves and a directmodel(...)verified on the real model.Measured (Llama-3.2-1B-Instruct GPTQ,
GPTQ_TORCH, fp16, GB10, 4 prompts x 16 greedy, steady state)optimize()optimize()Greedy tokens matched eager on both paths.
optimize()is the explicit opt-in; a graph-breaking kernel is slower compiled — what the issue predicted, and why the static-cache auto-compile stays off by default.Tests
New
tests/test_optimize_generate_4669.py(CPU, realtorch.compile):generate()compiles >=1 frame afteroptimize(), direct forward matches eager, repeatedoptimize()does not stack, hooks/to()survive.tests/test_generation_compile_policy_4669.py15 passed;tests/test_torch_compile_fallback.py17 passed; combined 36 passedruff check gptqmodel tests docs: cleanResidual risk
generate()afteroptimize()pays the full compile cost (82 s for 16 tokens on this model withGPTQ_TORCH).torch.save(model)afteroptimize()still fails, but it fails identically withoutoptimize()on this HF model, so no regression.