Skip to content

fix(generate): make optimize() compile the forward generate() runs (#4669) - #4912

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4669
Nov 17, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4669

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4669 (item 2; item 1 was already fixed by #4727).

Verdict per reported symptom

symptom verdict evidence
static cache 2-4x slower than eager on default CUDA kernels already fixed (#4727) _generation_compile_kwargs (base.py:3294) injects disable_compile=True unless every quantized linear declares SUPPORTS_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 nothing generate() runs open -> fixed here optimize() did self.model = torch_compile(self.model); OptimizedModule.__getattr__ hands generate back to the unwrapped module, so dynamo compiled 0 frames and timing was unchanged.
no fake impls / data_ptr()/id() guards open by design, documented kernels still declare SUPPORTS_COMPILE=False; the policy keeps them eager (docs/generation-compile-policy.md).

Fix

gptqmodel/models/base.py: optimize() compiles model.forward in place (the issue's suggested fix) instead of replacing self.model:

  • self.model stays the original nn.Module, so generate() -> self(...) -> compiled forward;
  • the repo's torch_compile fallback is preserved (_torchdynamo_orig_callable);
  • a repeated optimize() unwraps the previous proxy and recompiles the eager callable — no stacked wrappers;
  • hooks, to()/dtype moves and a direct model(...) verified on the real model.

Measured (Llama-3.2-1B-Instruct GPTQ, GPTQ_TORCH, fp16, GB10, 4 prompts x 16 greedy, steady state)

path before optimize() after optimize()
dynamic 0.250 s (256 tok/s), 0 graphs 0.316 s (202 tok/s), 122 graphs on first call
static (policy) 0.251 s (255 tok/s), 0 graphs 0.288 s (222 tok/s)

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, real torch.compile): generate() compiles >=1 frame after optimize(), direct forward matches eager, repeated optimize() does not stack, hooks/to() survive.

  • new test 4 passed; red on parent (copy/checkout/restore, no stash) 2 failed
  • tests/test_generation_compile_policy_4669.py 15 passed; tests/test_torch_compile_fallback.py 17 passed; combined 36 passed
  • ruff check gptqmodel tests docs: clean

Residual risk

  • The first generate() after optimize() pays the full compile cost (82 s for 16 tokens on this model with GPTQ_TORCH).
  • The compiled forward is 0.79x (dynamic) / 0.87x (static) eager speed for this graph-breaking kernel.
  • Compiling can flip a near-tie greedy token (documented for FP8/AWQ); tokens matched here.
  • torch.save(model) after optimize() still fails, but it fails identically without optimize() on this HF model, so no regression.

…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.
@Qubitium
Qubitium merged commit 8bd9169 into main Nov 17, 2026
9 checks passed
@Qubitium
Qubitium deleted the fix/issue-4669 branch November 17, 2026 18:32
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant