Skip to content

feat(looper): fuse downstream processors into producers - #3859

Open
Qubitium wants to merge 8 commits into
mainfrom
feat/processor-fusion
Open

Qubitium wants to merge 8 commits into
mainfrom
feat/processor-fusion

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

feat(looper): fuse downstream processors into producers

Summary

Adds an inline continuation contract to gptqmodel/looper so a downstream
processor can execute inside its upstream producer's frame, while the
intermediates are still live, instead of receiving them through
NamedModule.state.

First use: GPTQ -> EoRA. GPTQ no longer computes or stages w - wq; it
publishes the weights it owns (wq and w), and EoRA derives its own residual
at GPTQ's POST_QUANTIZE stage.

Fusion is opt-in and off by default (QuantizeConfig(processor_fusion=True)).
See "Numerical contract" below: the fused schedule is not equivalent to the
separate EoRA pass.

Ownership rule

A processor publishes only data it owns.

processor owns publishes
GPTQ source weight w, reconstruction wq, packed dtype-cast source wq, w, optional w_packed_source
EoRA the residual w - wq, adapter adapter (to module.state)

The subtraction is EoRA's derivation, so GPTQProcessor._w_wq_diff is gone and
"w_wq_diff" is no longer in GPTQ's emits.

Flow

Before: two processor passes, precomputed diff

flowchart LR
    subgraph before["Before: two processor passes"]
        G0["GPTQ subset 0"] --> G1["GPTQ subset 1"] --> GN["GPTQ subset N"]
        G0 -.->|"compute + stage w_wq_diff fp32"| ST[("NamedModule.state")]
        G0 -.->|"stage wq cpu"| ST
        GN --> E0["EoRA subset 0"]
        E0 --> E1["EoRA subset 1"] --> EN["EoRA subset N"]
        ST -.->|"read one layer later"| E0
    end
Loading

After: one fused stage, EoRA derives the residual

flowchart LR
    subgraph after["After: one fused stage"]
        FWD["producer forward<br/>(hook composed with consumer)"] --> Q["g.quantize()"]
        Q --> SC["ArtifactScope at POST_QUANTIZE"]
        SC --> WQ["wq (borrowed)"]
        SC --> W["w (live source weight)"]
        SC --> PK["w_packed_source (optional)"]
        WQ --> EP["EoRA.process() inline"]
        W --> EP
        PK --> EP
        EP --> RES["module_weight_residual(w, wq)"]
        RES --> AD["adapter -> module.state"]
        WQ --> FW["install wq"]
    end
    AD --> FIN["reverse finalize: EoRA, then GPTQ pack"]
Loading
GPTQ.process(module):
  g.quantize()
    -> scope at POST_QUANTIZE
         publish wq                     (borrowed)
         publish w                      (still the source weight)
         publish w_packed_source        (AUTO_NF12 only)
         -> EoRA.process()              (inline)
              -> w - wq                (EoRA's own subtraction)
              -> adapter
    -> install wq
    -> scope closes, packed source released

What changed

file change
gptqmodel/looper/processor_fusion.py new: ProcessorStages, InlineConfig, ArtifactScope, ExecutionStage, ProcessorFusionPlan, plan_processor_fusion, compose_forward_hooks, ProcessorFusionError
gptqmodel/eora/eora.py new module_weight_residual() — owns the subtraction and the AUTO_NF12 fused decode
gptqmodel/looper/loop_processor.py emits / stages / inline / inline_processors, publish(), dispatch_inline(), on_inline_source_replaced()
gptqmodel/looper/gptq_processor.py emits=("wq", "w"); publishes wq/w and dispatches inline consumers at POST_QUANTIZE; _w_wq_diff removed
gptqmodel/looper/eora_processor.py declares the InlineConfig; derives the residual via _resolve_residual(); non-destructive on_inline_source_replaced()
gptqmodel/looper/module_looper.py builds the fusion plan from the explicit opt-in
gptqmodel/looper/stage_layer.py iterates execution stages instead of the flat processor list
gptqmodel/looper/stage_subset.py composes consumer hooks into the producer hook; refreshes consumers after module replacement
gptqmodel/quantization/config.py new processor_fusion field (default False)
tests/test_processor_fusion.py planner, scope lifetime, hook composition, contract tests
tests/test_auto_dtype_cast.py residual tests retargeted to module_weight_residual / EoRA

Design

  • ProcessorStages names points inside a producer: PREPROCESS,
    POST_QUANTIZE, POST_INSTALL, PRE_RELEASE. It is named "stages" to stay
    distinct from the existing ProcessorLifecycleConfig / LoopProcessor.lifecycle.
  • InlineConfig declares how a consumer can be fused: allowed producers,
    injection stage, whether its forward hook joins the producer's forward, and
    the artifacts it consumes/produces.
  • ArtifactScope holds recipes, not tensors, until first access. Values are
    borrowed for the scope's lifetime and invalidated on exit. detach() is the
    only retention path and is counted; try_get() reads optional artifacts.
  • ExecutionStage / ProcessorFusionPlan are the planned execution order.
    Fused consumers get no stage of their own.
  • Planning attaches a consumer to an earlier producer only when the producer
    emits every consumed artifact, opens the requested stage, and the consumer's
    can_fuse_with() accepts it. Otherwise the consumer keeps its own stage and
    the existing module.state handoff.
  • Forward fusion composes the consumer's pre_process_fwd_hook into the
    producer's hook (compose_forward_hooks). A separate register_forward_hook
    would miss the last module of every subset, because HookedLinear.forward()
    raises the early-stop exception before ordinary post-forward hooks run.
  • Finalize order is unchanged: fused consumers stay in looper.processors
    and are finalized in reverse.

Numerical contract

The fused schedule is not equivalent to the separate EoRA pass, and this PR
does not claim parity:

  • Unfused: EoRA runs after GPTQ over the whole layer, installing wq + B @ A
    between its own subsets, so later EoRA subsets see corrected upstream
    activations.
  • Fused: EoRA runs inside GPTQ's subset loop, where those corrections do not
    exist. Installing them there would change GPTQ's trajectory instead.

Consequently the activation statistics and the resulting adapters differ. That
is why processor_fusion defaults to False and requires an explicit opt-in.
A validated numerical contract for the fused trajectory is a prerequisite for
enabling it by default.

Enabling and safety

Fusion is selected by config only, never by an environment variable:

QuantizeConfig(method=METHOD.GPTQ, bits=4, processor_fusion=True, ...)

ModuleLooper additionally refuses to fuse when disk_write_expected is set
(checkpoint capture or offload_to_disk), because those paths still expect
separately staged secondary artifacts.

Consumer compatibility is checked by the consumer itself. EoRA's
can_fuse_with() requires the producer to have prepared the same
CalibrationConfig.dataset object.

Review follow-up

finding resolution
P1: inline hook never runs when the producer raises the early stop Consumer hooks are composed into the producer hook via compose_forward_hooks(); regression test models HookedLinear running forward_hook and then raising the stop
P1: inline.preprocess() after module replacement discards collected statistics Replaced with on_inline_source_replaced(); EoRA refreshes placement only and keeps _segment_accumulators
P2: fused/unfused parity claim was wrong Fusion is now opt-in and off by default; the parity claim is removed and replaced with an explicit numerical-contract section
Env-var behaviour switch violates AGENTS.md GPTQMODEL_DISABLE_PROCESSOR_FUSION deleted; control moved to QuantizeConfig.processor_fusion

Verification

  • ruff check gptqmodel tests — clean.
  • python3 -m py_compile on every changed file.
  • tests/test_processor_fusion.py: planner selection/fallback, lazy scope,
    single materialization, replace, try_get, closed-scope rejection, detach
    accounting, hook composition (early-stop ordering, skipped consumers, batch
    index copy), and the GPTQ/EoRA contract declarations.

Full GPU numerics/EoRA tests still need to run in CI; this environment has no
torch installed.

Follow-ups

  1. Declare emits = ("wq", "w") in AWQ / QQQ / VPTQ / Paro and drop their
    precomputed w_wq_diff so EoRA is producer-agnostic.
  2. Extend the checkpoint adapter to accept fused secondary results and remove
    the disk_write_expected gate.
  3. Establish a validated numerical contract for the fused EoRA trajectory before
    considering it as a default.

@Qubitium
Qubitium force-pushed the feat/processor-fusion branch 2 times, most recently from af61a11 to 3ccdffa Compare November 14, 2026 06:37

Copy link
Copy Markdown
Collaborator Author

Reviewed commit 3ccdffa9b669ab2f7ea27ee605a62fad1bd6f021. Changes are needed before enabling this by default: I found two paths that lose EoRA statistics and a numerical mismatch between the fused and unfused schedules.

  1. [P1] Run the inline hook before the producer's early-stop exception.
    stage_subset.py:1069–1076 registers EoRA as an ordinary PyTorch forward hook. However, GPTQ sets forward_hook_last=True on the last hooked module in each subset, and HookedLinear.forward() raises StopForward inside forward(), before ordinary post-forward hooks execute. Thus EoRA never captures that module's inputs. Its inline process() subsequently raises EoRA statistics for module '...' were not collected before processing. This affects the normal early-stop path, including single-module subsets. A focused reproduction using the actual HookedLinear, _inline_forward_hook, and EoRA hook produced one producer callback and zero EoRA segments, on both CPU and CUDA. Compose the consumer callback into the hook that runs before the stop, preserving the existing MoE hook semantics, and add a regression with early stopping enabled.

  2. [P1] Preserve captured statistics when replacing the quantization source module.
    stage_subset.py:1479–1485 calls inline.preprocess() after _prepare_named_module_for_quantization() replaces the module. Contrary to the comment, this point is after the calibration forward and hook removal. EoraProcessor.preprocess() resets _segment_accumulators[module.name] = {}, discarding the statistics just collected. AUTO_NF12 restoration is a concrete replacement path through shell_module_materialize(role="quant_source"). Even after fixing finding 1, this path still fails with missing EoRA statistics. A focused lifecycle probe collected one segment, replaced the wrapped module, and invoked the new preprocess step: the segment count became zero and finalization raised on CPU and CUDA. Refresh placement/module references without reinitializing the accumulated statistics.

  3. [P2] Preserve EoRA's corrected calibration trajectory before claiming fused/unfused parity.
    eora_processor.py:353–360 intentionally omits installing wq + B @ A. In the unfused schedule, the preceding EoRA subset does install that correction (lines 362–375), so the next EoRA subset observes corrected upstream activations. The fused hook instead observes GPTQ's uncorrected upstream weights. Removing EoRA's separate stage also removes its corrected layer-output replay. Reading the same dataset object therefore does not make the activation statistics or adapters identical. A two-subset FP16 probe using actual EoraProcessor.process() and eora_compute_lora(), with fixed reconstructed weights, measured a 0.27246 relative covariance difference and 0.08496 maximum absolute difference in the second adapter's B @ A on CUDA. Preserve the separate corrected trajectory, or keep this fusion disabled until a validated numerical contract supports the changed algorithm; simply installing corrections into GPTQ's pass would change GPTQ's trajectory instead.

Validation: PYTHON_GIL=0 /opt/venvs/cu130t/bin/python -m pytest tests/test_processor_fusion.py tests/test_eora_weight_lifecycle.py -q — 13 passed. The focused probes above also ran on CPU and CUDA with Python 3.14.10 and Torch 2.16.0.dev20261102+cu130. These are isolated hook/lifecycle/numerical reproductions, not a full-model quantize/save/reload or concurrent multi-GPU qualification.

Separately, the new GPTQMODEL_DISABLE_PROCESSOR_FUSION environment switch in module_looper.py conflicts with the repository's explicit no environment-variable behavior switches rule; expose any needed control through config or an explicit API argument.

@Qubitium
Qubitium force-pushed the feat/processor-fusion branch 2 times, most recently from 56e4f44 to 6a43f6f Compare November 14, 2026 06:52
Add an inline continuation contract so a downstream processor can run inside
the upstream processor's execution frame instead of receiving staged tensors
through NamedModule.state.

Ownership is explicit: a processor publishes only data it owns. GPTQ publishes
wq, w and (for AUTO_NF12) w_packed_source at its POST_QUANTIZE stage; it no
longer computes or stages w - wq. EoRA derives the residual itself through the
new module_weight_residual() helper, which keeps the fused widening decode.

Fusion is opt-in via QuantizeConfig.processor_fusion and off by default: the
fused schedule does not replay the corrected upstream weights that the separate
EoRA pass installs between its subsets, so the calibration trajectory differs.

Consumer forward hooks are composed into the producer's hook, because
HookedLinear raises the early-stop exception from inside forward() before
ordinary post-forward hooks run. When the producer replaces the wrapped module
after the calibration forward, consumers get on_inline_source_replaced() instead
of preprocess(), which would discard the segments just collected.

Naming: ProcessorStages (not ProcessorLifecycle, which collides with
ProcessorLifecycleConfig), ExecutionStage for the plan element, InlineConfig
for the fusion declaration.
@Qubitium
Qubitium force-pushed the feat/processor-fusion branch from 6a43f6f to 968b1d1 Compare November 14, 2026 06:56
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Thanks — all four points are addressed in 968b1d1. Note this environment has
no torch, so I could not re-run your GPU probes; the reasoning below is against
the code paths you cited.

1. P1 — inline hook vs. the early stop. Fixed by composing, not registering.
compose_forward_hooks() in processor_fusion.py chains each consumer's
pre_process_fwd_hook into the producer's own hook, which is the hook that
HookedLinear.forward() invokes before it raises STOP_FORWARD_EXCEPTION.
stage_subset.py no longer calls register_forward_hook for consumers, so the
forward_hook / forward_hook_last and MoE pre-hook paths are unchanged.
Consumer hooks still receive the producer's batch index. Regression:
test_composed_hook_captures_before_the_early_stop models
forward_hook(...) → raise StopForward and asserts both callbacks fired.

2. P1 — statistics lost on source replacement. Fixed. The post-forward call
in stage_subset.py is now on_inline_source_replaced() (new no-op on
LoopProcessor). EoRA overrides it to refresh _module_target_devices only;
_segment_accumulators is untouched. The initial preprocess() still runs in
create_named_modules, before the forward, which is the correct point.

3. P2 — parity claim. You are right, and I have withdrawn the claim rather
than papering over it. Fusion is now off by default and opt-in via
QuantizeConfig(processor_fusion=True). The PR body replaces the parity claim
with an explicit "Numerical contract" section stating that the unfused EoRA pass
installs wq + B @ A between its own subsets and the fused path does not, so
statistics and adapters differ, and that a validated contract is a prerequisite
for making it a default. I did not attempt the "install into GPTQ's pass"
variant for the reason you gave.

4. Env-var switch. GPTQMODEL_DISABLE_PROCESSOR_FUSION is deleted. The
control is QuantizeConfig.processor_fusion (new field, default False),
passed to ModuleLooper(processor_fusion=...). disk_write_expected still
suppresses fusion for checkpoint/offload runs, since those expect staged
secondary artifacts.

Also fixed the two ruff-check failures (import ordering).

Verified here: ruff check gptqmodel tests clean, py_compile on every changed
file, and the torch-free planner/scope/hook-composition tests. test_auto_dtype_cast.py
was retargeted to module_weight_residual / EoRA._resolve_residual but needs
CI to execute.

# Conflicts:
#	gptqmodel/looper/eora_processor.py
#	gptqmodel/looper/gptq_processor.py
#	gptqmodel/looper/loop_processor.py
#	gptqmodel/looper/module_looper.py
#	gptqmodel/looper/stage_subset.py
#	tests/test_auto_dtype_cast.py

Conflict resolution:
- Kept the processor-fusion inline contract (ArtifactScope/InlineConfig/plan) and main's owns_quant_log dedupe.
- Kept main's MoE root capture hook; removed GPTQ._w_wq_diff because EoRA derives the residual via module_weight_residual().
- Kept main's AUTO_NF12 NamedModule inventory behavior and added fused-consumer hook composition / on_inline_source_replaced().
- Kept main's layer_modules_for_prefix and threaded inline_processors through subset planning.
main's #4679 replaced the declared-last early stop with a per-subset
"members still unseen" countdown, wrapping the producer's pre-hook. This
branch composes fused consumers into one `compose_forward_hooks` result
before either hook branch, so apply the marker to that composed hook: a
fused consumer must also count as captured, and the stop must still fire
only after every member ran.

tests/module_tree/test_subset.py, tests/test_subset_declared_order_4679.py
and tests/test_processor_fusion.py -> 31 passed. ruff clean.
main added `active_padding_mask` to the same import list this branch extended
with `ProcessorStages`. Union them; no logic overlap.
gptqmodel/models/base.py: keep main's #4862 try/except around the quantize body
(release_failed_run_processors) and pass the branch's processor_fusion kwarg to
ModuleLooper inside it.
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Rebased/merged origin/main (5a13ec241) into feat/processor-fusion as 6be853871, so the PR is mergeable again.

One conflict, gptqmodel/models/base.py: kept main's #4862 try:/except BaseException: release_failed_run_processors(processors); raise wrapper (and its extra indentation) and passed the branch's processor_fusion= kwarg to ModuleLooper inside it.

Verified after the merge:

  • tests/test_processor_fusion.py + tests/test_cancelled_quantize_disk_offload_4807.py → 17 passed
  • tests/test_failed_run_device_smi_cleanup_4813.py + test_looper_helpers.py + test_gptq_workspace_release.py + test_fallback_hessian_release.py → 32 passed, 1 failed
  • The one failure, test_shared_input_fallback_releases_adopted_source_before_clone, fails identically on unmodified origin/main (5a13ec241), so it is not from this merge.
  • ruff check clean on models/base.py.

@Qubitium
Qubitium marked this pull request as ready for review November 19, 2026 03:20
@Qubitium
Qubitium marked this pull request as draft November 19, 2026 11:35
@Qubitium
Qubitium marked this pull request as ready for review November 20, 2026 01:06
# Conflicts:
#	gptqmodel/looper/eora_processor.py
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