Repository navigation
refactor(looper): declare processor capabilities instead of isinstance branches - #6406
Merged
Merged
Conversation
…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
marked this pull request as ready for review
November 29, 2026 14:08
10 of 15 tasks
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.
This was referenced Nov 29, 2026
Merged
Merged
12 tasks done
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.
Summary
module_looper.pyandstage_layer.pyimported six processor classes (AWQProcessor,DequantizeProcessor,EoraProcessor,GPTQProcessor,NativeProcessor,ParoProcessor, plusQQQProcessorinstage_layer) and used 17isinstancechecks to steer shared stage code. Each decision is now declared on the processor, either as aLoopProcessorclass attribute or as a no-opLoopProcessorhook. 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
LoopProcessordeclares six capabilities. Each defaults toFalse, and subclasses inherit them, so G2PTQ inherits GPTQ's values:heavy_finalizestage_layer.py:187,:214isinstance(process, ParoProcessor)offloads_finalized_modulesstage_layer.py:1515native_capturestage_layer.py:1039(W4A replay toggle),module_looper.py:2155reuses_native_capturemodule_looper.py:2157(thegptaq/foemqcfg check after it is unchanged)uses_awq_layer_modulesmodule_looper.py:2315,:2616(is_awq_quantize),stage_layer.py:1201(DEBUG log format)preprocess_receives_loop_fallbackmodule_looper.py:2720The stages read them with
getattr(processor, "<flag>", False), the same conventionrecord_quant_loguses forowns_quant_log. A duck-typed test double therefore gets the same answer theisinstancecheck gave it.LoopProcessorgains three no-op hooks:adopt_previous_calibration(previous): EoRA takes the previous processor's dataset and input cache, and Dequantize takes empty ones. This replacesmodule_looper.py:2245-2257.on_named_module_created(named_module): EoRA'sstate["wq"]line, moved verbatim. This replacesmodule_looper.py:2699-2702.prewarm_runtime(): Paro already defined it. This replacesmodule_looper.py:2309.EoRA now declares
ForwardConfig(allow_auto_dtype_cast=False). The existing generic branch (module_looper.py:2729) already setsauto_dtype_cast_forward_disabled, andBaseQModel._maybe_auto_dtype_cast_forward_modulereturns the source module unchanged when that flag is set. The EoRAcontinueatmodule_looper.py:2748-2750was redundant and is removed.The two
is_awq_quantize/include_capture_onlyscans now go through oneModuleLooper._layer_module_flags()helper.Deleted: the GPTQ + GPTAQ/FOEM calibration-inheritance arm (
module_looper.py:2247-2248). It was unreachable:_loop_implonly enters the branch whenverify_calibration_dataset(p_index)is falsy.GPTQProcessor.verify_calibration_dataset(gptq_processor.py:1412) raisesValueErrorwhen the dataset isNoneand returnsTrueotherwise.G2PTQProcessorinherits it, and no other GPTQ subclass exists.GPTQProcessor.set_calibration_dataset(gptq_processor.py:384) raisesNotImplementedError, so the arm would have failed even if it had been reached.test_gptq_never_inherits_previous_calibrationpins all of this.Behaviour kept exactly as on origin/main:
fallbackstill reaches only GPTQ. OnlyGPTQProcessorand its subclass G2PTQ getpreprocess(module, fallback=fallback, region_timer=region_timer). QQQ, VPTQ, MACaQ, EXL3, Paro and AWQ acceptfallback=but still getpreprocess(module), as before. Passing it to all of them is probably equivalent, because productionfallbackisquantize_config.fallback, the same object asprocessor.qcfg. That is a behaviour change, though, so it is left for a separate PR.uses_awq_layer_modules.awq_processor.pyonly 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 indocs/fp8-save-offload.md(EoRA now also usesallow_auto_dtype_cast=False).Tests:
tests/test_looper_processor_capabilities.py.on_named_module_createdno-op: two intest_auto_dtype_cast.py, plus one each inmodule_tree/test_subset.py,module_tree/test_jamba_model_tree_consumption.pyandmodule_tree/test_inkling2_loop_plan.py.Out of scope / follow-ups:
fallbackto every processor (see above).Tests
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 equalsissubclass(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_cacheandtest_dequantize_adopts_an_empty_dataset_and_cache.test_gptq_never_inherits_previous_calibration.Red check: flipping
QQQProcessor.offloads_finalized_modulestoFalsefailstest_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 referenceModuleLooper,module_looper,stage_layer,run_layer_stage, the touched processor classes,prewarm_runtime,is_awq_quantize,_reusable_initial_capture,set_w4a_replay_enabledorauto_dtype_cast_forward_disabled, plus everytests/test_eora*.py. Both revisions ran identically (CUDA_VISIBLE_DEVICES=4, one RTX 4090 48 GB):test_gptaq_foem_first_capture_5831.py(6) andtest_gptaq_shuffle_pairing_4869.py(3): the tiny fixture tokenizer is rejected atGPTQModel.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) andtest_inkling2_loop_plan.py::test_inkling2_loop_public_loader_uses_local_code_and_checkpoint_keys(1)._reusable_initial_captureon either revision. The GPU A/B below exercises that path instead (reused_initial_capture: 1for GPTAQ and FOEM on both sides).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 byheavy_finalize.compressed_tensorsnot installed (1).test_native_processor_resolutionmodel-type skip (1) andtest_processor_continuationCUDA-unavailable skip (1).native_captureatstage_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:
bits=4, group_size=128, desc_act=False, device="cuda:0", single GPU.batch_size=4.offload_to_disk=True, so theoffloads_finalized_modulespath runs.The driver records the number of
_reusable_initial_capturehits andstage_layer.offload_to_diskcalls on both revisions, without changing them.GPTQModel.adapter.generate)(1)
adapter_config.jsondiffers in only two ways.base_model_name_or_pathis the output dir (GPTQ + EoRA only).target_modulesorder comes fromlist(set)atmodels/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.csvdiffers only in row order and thetimecolumn, which come from async finalize. Its rows are equal once sorted and withtimedropped.Structural A/B (
ab_struct.py, CPU):isinstancedecisions for all 13 processor classes. On the branch it reads the declared capabilities and hook overrides.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.pygains only two class attributes.isinstancechecks becameuses_awq_layer_modulesandoffloads_finalized_modules, with identical values (truth table and structural A/B).Logic Flow Documentation
file:lineevidence.docs/repeats the diagrams, titled for the mechanism, and is linked fromREADME.md. It is the existingdocs/quantization-lifecycle-contracts.md, listed in thedocs/README.mdindex thatREADME.mdlinks 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:#fde2e1flowchart 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"]Review Requirements
Kernel Accuracy Requirements
Notes
isinstancechecks. Replacing them still needs a declaration on the processor plus a read in the stage, so production code is +20 net.getattr(..., False)for flags vs strict hooks. Flags usegetattrto match the existingowns_quant_logconvention and to keep the oldisinstanceanswer for duck-typed doubles. Hooks are called directly, as R2 of the debloat map intends. That is why the five minimalcreate_named_modulesdoubles gained a no-op.EoraProcessor.quantized_weightsdoes not exist. The attribute is defined nowhere in the repository, and has not been since it was added in Eora #1302. So theon_named_module_createdbody (moved verbatim) would raiseAttributeErrorif it ever ran. On the chains checked, EoRA always finds theNamedModulethat the previous processor stored infull, so the line does not run. I did not prove it unreachable for every chain; one example not proven is anlm_headendpoint re-resolved between processors. So it is preserved, not fixed or deleted.LoopProcessor.__init__stores[]when there is no dataset, andEoraProcessor.verify_calibration_datasetonly returnsFalseforNone. It is kept because only the GPTQ arm was in scope. It could be removed in a follow-up.🤖 Generated with Claude Code