Skip to content

refactor(looper): declare processor capabilities instead of isinstance branches - #6406

Merged
Qubitium merged 1 commit into
mainfrom
refactor/looper-processor-capabilities
Nov 29, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/looper-processor-capabilities

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

module_looper.py and stage_layer.py imported six processor classes (AWQProcessor, DequantizeProcessor, EoraProcessor, GPTQProcessor, NativeProcessor, ParoProcessor, plus QQQProcessor in stage_layer) and used 17 isinstance checks to steer shared stage code. Each decision is now declared on the processor, either as a LoopProcessor class attribute or as a no-op LoopProcessor hook. The shared stages no longer import any processor class.

The unreachable GPTQ + GPTAQ/FOEM arm of the calibration-inheritance branch is deleted. Behaviour is otherwise unchanged; the GPU A/B checkpoints are bit-identical.

Diff: 16 files changed, 131 insertions(+), 65 deletions(-) plus a new 141-line test file. Production code alone (gptqmodel/) is +80/-60. Production code grows by 20 net lines. This PR decouples the stages from the processor classes; it does not shrink the code. See Notes.

No issue is resolved by this PR.

What Changed

  • LoopProcessor declares six capabilities. Each defaults to False, and subclasses inherit them, so G2PTQ inherits GPTQ's values:

    Capability True on Replaces (origin/main)
    heavy_finalize Paro stage_layer.py:187, :214 isinstance(process, ParoProcessor)
    offloads_finalized_modules GPTQ, QQQ, AWQ, Paro stage_layer.py:1515
    native_capture Native stage_layer.py:1039 (W4A replay toggle), module_looper.py:2155
    reuses_native_capture GPTQ module_looper.py:2157 (the gptaq/foem qcfg check after it is unchanged)
    uses_awq_layer_modules AWQ, Paro module_looper.py:2315, :2616 (is_awq_quantize), stage_layer.py:1201 (DEBUG log format)
    preprocess_receives_loop_fallback GPTQ module_looper.py:2720

    The stages read them with getattr(processor, "<flag>", False), the same convention record_quant_log uses for owns_quant_log. A duck-typed test double therefore gets the same answer the isinstance check gave it.

  • LoopProcessor gains three no-op hooks:

    • adopt_previous_calibration(previous): EoRA takes the previous processor's dataset and input cache, and Dequantize takes empty ones. This replaces module_looper.py:2245-2257.
    • on_named_module_created(named_module): EoRA's state["wq"] line, moved verbatim. This replaces module_looper.py:2699-2702.
    • prewarm_runtime(): Paro already defined it. This replaces module_looper.py:2309.
  • EoRA now declares ForwardConfig(allow_auto_dtype_cast=False). The existing generic branch (module_looper.py:2729) already sets auto_dtype_cast_forward_disabled, and BaseQModel._maybe_auto_dtype_cast_forward_module returns the source module unchanged when that flag is set. The EoRA continue at module_looper.py:2748-2750 was redundant and is removed.

  • The two is_awq_quantize / include_capture_only scans now go through one ModuleLooper._layer_module_flags() helper.

  • Deleted: the GPTQ + GPTAQ/FOEM calibration-inheritance arm (module_looper.py:2247-2248). It was unreachable:

    • _loop_impl only enters the branch when verify_calibration_dataset(p_index) is falsy.
    • GPTQProcessor.verify_calibration_dataset (gptq_processor.py:1412) raises ValueError when the dataset is None and returns True otherwise. G2PTQProcessor inherits it, and no other GPTQ subclass exists.
    • GPTQProcessor.set_calibration_dataset (gptq_processor.py:384) raises NotImplementedError, so the arm would have failed even if it had been reached.
    • test_gptq_never_inherits_previous_calibration pins all of this.
  • Behaviour kept exactly as on origin/main:

    • The loop's fallback still reaches only GPTQ. Only GPTQProcessor and its subclass G2PTQ get preprocess(module, fallback=fallback, region_timer=region_timer). QQQ, VPTQ, MACaQ, EXL3, Paro and AWQ accept fallback= but still get preprocess(module), as before. Passing it to all of them is probably equivalent, because production fallback is quantize_config.fallback, the same object as processor.qcfg. That is a behaviour change, though, so it is left for a separate PR.
    • The AWQ/Paro DEBUG subset-log format is unchanged; it is now keyed on uses_awq_layer_modules.
    • awq_processor.py only gains two attribute lines (offloads_finalized_modules = True, uses_awq_layer_modules = True).
  • Docs: a "Processor capabilities" section and a before/after row in docs/quantization-lifecycle-contracts.md, and a one-line fix in docs/fp8-save-offload.md (EoRA now also uses allow_auto_dtype_cast=False).

  • Tests:

    • New tests/test_looper_processor_capabilities.py.
    • Five create-named-modules test doubles gain the new on_named_module_created no-op: two in test_auto_dtype_cast.py, plus one each in module_tree/test_subset.py, module_tree/test_jamba_model_tree_consumption.py and module_tree/test_inkling2_loop_plan.py.
  • Out of scope / follow-ups:

    • Pass fallback to every processor (see above).
    • Merge the two DEBUG subset-log formats.
    • EoRA's own inheritance arm is also unreachable through the public constructors (see Notes).

Tests

  • Unit tests have been executed and passed, or the reason they are not applicable is documented.
  • I added a new simple/fast unit test for this change, or documented why that is not applicable.

tests/test_looper_processor_capabilities.py (133 cases, about 8 s on CPU):

  • test_capability_matches_old_isinstance_predicate: for each of the 13 processor classes and each of the 6 capabilities, the declared attribute equals issubclass(cls, <old isinstance tuple>).
  • test_hook_overridden_exactly_where_old_branch_fired: each of the 3 hooks is overridden exactly on the classes its old branch named.
  • test_auto_dtype_cast_disabled_only_for_native_and_eora.
  • test_eora_adopts_previous_dataset_and_cache and test_dequantize_adopts_an_empty_dataset_and_cache.
  • test_gptq_never_inherits_previous_calibration.

Red check: flipping QQQProcessor.offloads_finalized_modules to False fails test_capability_matches_old_isinstance_predicate[offloads_finalized_modules-QQQProcessor], and only that case.

The affected-family run used all 123 non-tests/models/ test files that reference ModuleLooper, module_looper, stage_layer, run_layer_stage, the touched processor classes, prewarm_runtime, is_awq_quantize, _reusable_initial_capture, set_w4a_replay_enabled or auto_dtype_cast_forward_disabled, plus every tests/test_eora*.py. Both revisions ran identically (CUDA_VISIBLE_DEVICES=4, one RTX 4090 48 GB):

PYTHONPATH=<clone> CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=4 \
  python -P -m pytest -c tests/pytest.ini -o addopts="" -q -rs -n 6 -p no:cacheprovider <123 files> \
  [tests/test_looper_processor_capabilities.py]
# origin/main 1615accf9: 18 failed, 2664 passed, 62 skipped
# this branch:           18 failed, 2797 passed, 62 skipped   (+133 = the new test file)
  • The failed set and the skip set are identical on both revisions.
  • The 18 failures also fail on origin/main:
    • test_gptaq_foem_first_capture_5831.py (6) and test_gptaq_shuffle_pairing_4869.py (3): the tiny fixture tokenizer is rejected at GPTQModel.load ("cannot encode ordinary text"), before the looper runs.
    • test_weight_only_failed_run_device_5011.py (4), test_processor_finalize_4747.py (2), module_tree/test_registered_module_plans.py[gemma4, gemma4_text] (2) and test_inkling2_loop_plan.py::test_inkling2_loop_public_loader_uses_local_code_and_checkpoint_keys (1).
    • What this leaves unverified: the [Audit][GPTAQ/FOEM] Native and GPTQ processors repeat the same first-layer capture #5831 reuse tests never reach _reusable_initial_capture on either revision. The GPU A/B below exercises that path instead (reused_initial_capture: 1 for GPTAQ and FOEM on both sides).
  • Skips (62, identical on both):
    • Multi-GPU tests need 2 CUDA devices (test_checkpoint_devices, test_calibration_data_device, test_gptaq_foem_multigpu). Unverified: the multi-device finalize-drain path with real processors; it is covered structurally by heavy_finalize.
    • NPU (33), MLX/macOS (1) and compressed_tensors not installed (1).
    • test_native_processor_resolution model-type skip (1) and test_processor_continuation CUDA-unavailable skip (1).
  • The W4A replay toggle (native_capture at stage_layer.py:1034) needs a W4A (NVFP4/FP8 activation) GPU run. It is not executed here. The truth table and the structural A/B cover it.

bash format/check.sh: All checks passed! (ruff 0.14.2).

Measured Impact

Not applicable: a behaviour-preserving refactor with no claimed issue. The GPU A/B peak allocated memory matches within run-to-run async-finalize jitter: GPTAQ, FOEM and AWQ are identical to the byte, and GPTQ and GPTQ+EoRA vary by under 2% in both directions.

GPU A/B (bit-identical saved tensors)

Setup:

  • Model: Qwen/Qwen2.5-0.5B-Instruct, seed 1234, bits=4, group_size=128, desc_act=False, device="cuda:0", single GPU.
  • Calibration: 32 rows of 1,200 characters of fixed repo docs text, batch_size=4.
  • Defaults otherwise, including offload_to_disk=True, so the offloads_finalized_modules path runs.

The driver records the number of _reusable_initial_capture hits and stage_layer.offload_to_disk calls on both revisions, without changing them.

run_side.sh main   <origin/main worktree> gptq gptq_eora gptaq foem awq eora_generate
run_side.sh branch <this clone>           gptq gptq_eora gptaq foem awq eora_generate
python -P ab_compare.py ab/main/<mode> ab/branch/<mode>   # every safetensors tensor bitwise + every json
Mode Processor chain Spies (main = branch) Result
GPTQ GPTQ reuse 0, offload 168 BIT-IDENTICAL: 794 tensors, all json byte-identical
GPTQ + EoRA adapter GPTQ → EoRA reuse 0, offload 168 BIT-IDENTICAL: 1130 tensors (model + adapter) (1)
GPTAQ Native → GPTQ reuse 1, offload 168 BIT-IDENTICAL: 794 tensors, all json byte-identical
FOEM Native → GPTQ reuse 1, offload 168 BIT-IDENTICAL: 794 tensors, all json byte-identical
AWQ (GEMM) AWQ reuse 0, offload 168 BIT-IDENTICAL: 626 tensors, all json byte-identical
EoRA generate (GPTQModel.adapter.generate) Dequantize → EoRA reuse 0, offload 0 BIT-IDENTICAL: 336 adapter tensors (1); input is each side's (identical) GPTQ checkpoint

(1) adapter_config.json differs in only two ways. base_model_name_or_path is the output dir (GPTQ + EoRA only). target_modules order comes from list(set) at models/writer.py:2551, which follows the per-process string hash, so the order changes from run to run on origin/main too. The two files are equal once both of those are normalized. On every mode, quant_log.csv differs only in row order and the time column, which come from async finalize. Its rows are equal once sorted and with time dropped.

Structural A/B (ab_struct.py, CPU):

  • On origin/main it evaluates the 12 old isinstance decisions for all 13 processor classes. On the branch it reads the declared capabilities and hook overrides.
  • The two JSON tables are identical.

Model Support / Module Plan

Not applicable: no model, alias, definition or module-plan change.

AWQ onboarding safety

Not applicable: no AWQ grouping, search, replay or fold change.

  • awq_processor.py gains only two class attributes.
  • AWQ's isinstance checks became uses_awq_layer_modules and offloads_finalized_modules, with identical values (truth table and structural A/B).
  • The AWQ GPU A/B is above.

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams and docs page are included below.
  • New-flow Mermaid diagram(s) describe the shipped code using real symbol names.
  • The removed/replaced mechanism is shown or tabulated with file:line evidence.
  • Failure and ambiguity paths are marked and visually distinct from success.
  • A reference page under docs/ repeats the diagrams, titled for the mechanism, and is linked from README.md. It is the existing docs/quantization-lifecycle-contracts.md, listed in the docs/README.md index that README.md links to.

The decision source changes from class identity to declared capabilities. The old-vs-new table is under "What Changed".

flowchart TD
    L["_loop_impl: each processor"] --> V{"verify_calibration_dataset"}
    V -- "falsy" --> A["adopt_previous_calibration(previous)<br/>EoRA: previous dataset + cache<br/>Dequantize: empty"]
    V -- "raises (GPTQ, AWQ, ... without data)" --> X["ValueError"]
    V -- "True" --> R{"previous.native_capture and<br/>reuses_native_capture and gptaq/foem"}
    R -- yes --> C["deep-copy Native first-layer capture"]
    R -- no --> F["cache_inputs forward"]
    style X fill:#fde2e1
Loading
flowchart LR
    CN["create_named_modules"] --> H["on_named_module_created<br/>(EoRA only)"]
    H --> P{"preprocess_receives_loop_fallback"}
    P -- GPTQ --> P1["preprocess(m, fallback=, region_timer=)"]
    P -- others --> P2["preprocess(m)"]
    P1 --> D{"forward.allow_auto_dtype_cast"}
    P2 --> D
    D -- "False (Native, EoRA)" --> K["auto_dtype_cast_forward_disabled<br/>tree module kept"]
    D -- True --> N["_maybe_auto_dtype_cast_forward_module"]
    FZ["finalize worker"] --> O{"offloads_finalized_modules"}
    O -- "GPTQ, QQQ, AWQ, Paro" --> OD["offload_to_disk"]
    FZ --> HF{"heavy_finalize (Paro)"}
    HF -- yes --> SY["drain + empty_cache"]
Loading

Review Requirements

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

  • Not applicable: no kernel change.
  • Not applicable: no fusion change.
  • Not applicable: no kernel inventory change.

Notes

  • Net lines. Most of the old branches were single-line isinstance checks. Replacing them still needs a declaration on the processor plus a read in the stage, so production code is +20 net.
    • The R1 map estimated about -95/+45. That estimate assumed the AWQ/Paro DEBUG log line would be merged.
    • The DEBUG format is kept here so AWQ behaviour stays identical while the AWQ lifecycle is being rewritten elsewhere.
    • The gain is that the shared stages import no processor classes, and new processors opt in by declaring attributes.
  • getattr(..., False) for flags vs strict hooks. Flags use getattr to match the existing owns_quant_log convention and to keep the old isinstance answer for duck-typed doubles. Hooks are called directly, as R2 of the debloat map intends. That is why the five minimal create_named_modules doubles gained a no-op.
  • EoraProcessor.quantized_weights does not exist. The attribute is defined nowhere in the repository, and has not been since it was added in Eora #1302. So the on_named_module_created body (moved verbatim) would raise AttributeError if it ever ran. On the chains checked, EoRA always finds the NamedModule that the previous processor stored in full, so the line does not run. I did not prove it unreachable for every chain; one example not proven is an lm_head endpoint re-resolved between processors. So it is preserved, not fixed or deleted.
  • EoRA's own inheritance arm is probably unreachable too. LoopProcessor.__init__ stores [] when there is no dataset, and EoraProcessor.verify_calibration_dataset only returns False for None. It is kept because only the GPTQ arm was in scope. It could be removed in a follow-up.

🤖 Generated with Claude Code

…e branches

module_looper.py and stage_layer.py imported six processor classes to steer
shared stage code with 17 isinstance checks. Each decision is now declared on
the processor:

- LoopProcessor class attributes (default False): native_capture (Native),
  reuses_native_capture (GPTQ), heavy_finalize (Paro),
  offloads_finalized_modules (GPTQ, QQQ, AWQ, Paro), uses_awq_layer_modules
  (AWQ, Paro) and preprocess_receives_loop_fallback (GPTQ). Subclasses
  inherit them, so G2PTQ keeps GPTQ's behaviour. The stages read them with
  getattr(..., False), so a duck-typed processor gets the same answer an
  isinstance check gave it.
- LoopProcessor no-op hooks: adopt_previous_calibration (EoRA reuses the
  previous dataset and cache; Dequantize takes empty ones),
  on_named_module_created (EoRA) and prewarm_runtime (Paro already had it).
- EoRA declares ForwardConfig(allow_auto_dtype_cast=False). The generic
  branch already sets auto_dtype_cast_forward_disabled, and
  _maybe_auto_dtype_cast_forward_module returns the source module when that
  flag is set, so the EoRA-specific `continue` is gone.
- The two is_awq_quantize / include_capture_only scans are now one
  _layer_module_flags() helper.

The GPTQ + GPTAQ/FOEM arm of the calibration-inheritance branch was
unreachable and is gone. _loop_impl only takes that branch when
verify_calibration_dataset is falsy, and GPTQProcessor's version (which
G2PTQ inherits) either raises or returns True. GPTQ's
set_calibration_dataset also raises NotImplementedError.

Behaviour is unchanged on purpose. Only GPTQ receives preprocess(fallback=,
region_timer=). The AWQ/Paro DEBUG subset-log format stays, keyed on
uses_awq_layer_modules. awq_processor.py only gains its two attribute lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review November 29, 2026 14:08
@Qubitium
Qubitium merged commit 6b25d2c into main Nov 29, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/looper-processor-capabilities branch November 29, 2026 14:08
Qubitium pushed a commit that referenced this pull request Nov 29, 2026
Re-merges current main (6b25d2c, including the #6406 capability
refactor) into the processor-fusion branch.

Conflict: gptqmodel/looper/module_looper.py, imports only. #6406 removed
the `isinstance(..., ParoProcessor)` branches that used the symbol, so
the merged file keeps only `plan_processor_fusion`; importing
ParoProcessor would be an unused import (ruff F401).

Integration fixes required by the merge (the branch predates #6406):

* stage_layer.py: `looper.execution_stages` was a hard attribute read.
  #6406 deliberately made the shared stages work with duck-typed
  processors, and eight looper test doubles model only `processors`.
  Fall back to one stage per processor when no fusion plan is published,
  which is exactly the pre-fusion schedule.

* stage_subset.py: pass `inline_processors` to `create_named_modules`
  only when a consumer is actually fused. The default (unfused) call
  keeps its old shape, so duck-typed loopers that predate the parameter
  still work.

Both fixes are no-ops on a real ModuleLooper with fusion active.
Qubitium added a commit that referenced this pull request Nov 30, 2026
…6406/#6422 follow-up) (#6466)

#6422 moved verify_calibration_dataset to LoopProcessor, where it reads
calibration_dataset_owner; the #6406 test still called it on a bare
SimpleNamespace and failed with AttributeError on main.

Co-authored-by: Claude Opus 5.5 <[email protected]>
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