Repository navigation
refactor(looper): optional processor hooks become no-op LoopProcessor methods - #6467
Merged
Merged
Conversation
… methods The shared looper stages probed 19 optional processor hooks with getattr(processor, name, None) plus callable(...) at about 20 sites in stage_subset.py, stage_layer.py, forward_executor.py, module_looper.py and loop_processor.py. Three more hooks (install_moe_affinity_hooks, prepare_layer_post_quantize, calibration_keep_mask) already had LoopProcessor defaults and were probed anyway. Only EXL3 (capture/replay and zero-route recovery hooks), Paro and G2PTQ (grouped optimization) and GPTQ (NVFP4 activation-scale probe) implement them. Each hook is now a LoopProcessor method whose default returns what the stage used when the hook was absent: - restore_subset_capture_frontier -> False, restore_subset_capture_batches -> frozenset() (the EXL3 return type; the stage ignores it) - subset_forward_capture_context -> nullcontext() - plan_subset_zero_route_recovery -> (); finish_subset_zero_route_recovery keeps the stage's "lost its completion validator" RuntimeError, since it only runs after a non-empty plan - forward_committed_batch_indices -> frozenset(), the identity of the union both executor call sites build (both pass only layer_index=) - prepare_runtime_weight_for_forward -> None (module unchanged) - capture_layer_forward_context_during_subset -> True - begin_activation_scale_probe -> False - uses_grouped_optimization -> False; needs_pristine_layer_clone -> uses_grouped_optimization(), the fallback of the deleted _processor_needs_pristine_group_clone helper - clean_group_layer_inputs -> the given layer_inputs - the rest are no-ops The call sites call the hooks directly. resolve_calibration_keep_mask and _processor_needs_pristine_group_clone are gone, and the scale-probe, capture and zero-route recovery forwards in run_subset_stage share one functools.partial of their 13 common _run_forward_batches arguments. Test processor doubles that relied on missing attributes now subclass LoopProcessor through tests/module_tree/looper_doubles.ProcessorDouble, which skips __init__ and takes its attributes as keywords like the SimpleNamespace doubles it replaces. The MagicMock processor in test_moe_expert_batching returns False from restore_subset_capture_frontier instead of having the hook set to None. No assertion changes. Not in scope: release_run_workspace/release_failed_run probes in the run teardown (shared-teardown refactor), and the R1 capability attributes, which the stages still read with getattr(..., False). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qubitium
marked this pull request as ready for review
November 30, 2026 02:25
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Qubitium
added a commit
that referenced
this pull request
Nov 30, 2026
…d teardown Rebased fix/6148-issue onto origin/main 94ceaf7 (after #6464, #6465, #6467, #6469, #6470). Three conflicts: - gptqmodel/looper/forward_executor.py: import block. Main dropped the unused resolve_calibration_keep_mask import; kept only the PR's replay_records import. - gptqmodel/looper/module_looper.py: #6465 moved the failed-run teardown into InflightLayerTracker (inflight_layer.py). Kept main's structure and re-applied the PR's release_looped_capture() as a ModuleLooper override of _release_failed_run_processors that calls super() first. - gptqmodel/models/definitions/inkling2_loop.py: #6464 reduced pre_quantize_generate_hook_start to the batch-index/bank reset plus super(); the PR removes that reset, so the override is deleted. Earlier rebase (onto 81ac176): Rebased fix/6148-issue onto origin/main 81ac176. Two conflicts: - gptqmodel/models/definitions/inkling2_loop.py: import block. Kept the PR's replay_records imports; dropped the PR's get_op_name import because main removed its last use and the rebased file does not use it. - tests/module_tree/test_inkling2_loop_plan.py: main added the AWQ declaration block where the PR deletes _capture_inkling2_forward. Kept all of main's AWQ tests, removed only the helper the PR replaced with record-owned head banks. Tests: 135 passed, 1 skipped on CPU (main baseline for the pre-existing files: 124 passed). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Nov 30, 2026
Merged
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
…d teardown Rebased fix/6148-issue onto origin/main 94ceaf7 (after #6464, #6465, #6467, #6469, #6470). Three conflicts: - gptqmodel/looper/forward_executor.py: import block. Main dropped the unused resolve_calibration_keep_mask import; kept only the PR's replay_records import. - gptqmodel/looper/module_looper.py: #6465 moved the failed-run teardown into InflightLayerTracker (inflight_layer.py). Kept main's structure and re-applied the PR's release_looped_capture() as a ModuleLooper override of _release_failed_run_processors that calls super() first. - gptqmodel/models/definitions/inkling2_loop.py: #6464 reduced pre_quantize_generate_hook_start to the batch-index/bank reset plus super(); the PR removes that reset, so the override is deleted. Earlier rebase (onto 81ac176): Rebased fix/6148-issue onto origin/main 81ac176. Two conflicts: - gptqmodel/models/definitions/inkling2_loop.py: import block. Kept the PR's replay_records imports; dropped the PR's get_op_name import because main removed its last use and the rebased file does not use it. - tests/module_tree/test_inkling2_loop_plan.py: main added the AWQ declaration block where the PR deletes _capture_inkling2_forward. Kept all of main's AWQ tests, removed only the helper the PR replaced with record-owned head banks. Tests: 135 passed, 1 skipped on CPU (main baseline for the pre-existing files: 124 passed). Co-Authored-By: Claude Opus 5.5 <[email protected]>
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
The shared looper stages probed optional processor hooks with
getattr(processor, name, None)pluscallable(...). This PR turns each hook into aLoopProcessormethod whose default returns what the stage used when a processor lacked the hook. The stages now call the hooks directly. Behaviour is unchanged on purpose: no numerics, checkpoint-format or public-API change.The inventory was re-derived from current
main(1c51b32a7), after #6399, #6408, #6413, #6423, #6435 and R1 (#6406). It covers 19 optional hooks plus 3 hooks that already had base defaults but were still probed (install_moe_affinity_hooks,prepare_layer_post_quantize,calibration_keep_mask). They were probed at 26 sites instage_subset.py,stage_layer.py,forward_executor.py,module_looper.py,loop_processor.pyandutils/looper_helpers.py.Diff:
gptqmodel/6 files, +143/-222 (net -79). Including the new unit tests (+97), the converted test doubles and the docs section (+27), the whole PR is 25 files, +351/-276 (net +75). The production code shrinks; the growth is the required new tests, the shared test double and the docs.What Changed
LoopProcessorgains 19 hook defaults. Each matches the signature of its EXL3/Paro/G2PTQ/GPTQ implementation (a new test asserts parameter names and kinds) and returns the value the stage used when the hook was absent:restore_subset_capture_frontierFalse(forward runs)restore_subset_capture_batchesfrozenset()(EXL3 return type; the stage ignores it)commit_subset_capture_frontier,validate_subset_capture_readinesssubset_forward_capture_contextnullcontext()plan_subset_zero_route_recovery()(no recovery forward)finish_subset_zero_route_recoveryRuntimeError("EXL3 route-coverage top-up lost its completion validator"). It only runs after a non-empty planforward_committed_batch_indicesfrozenset()(identity of the union both executor sites build)forward_batch_completed,bind_moe_quant_devicesprepare_runtime_weight_for_forwardNone(module unchanged; both callerscontinue)uses_grouped_optimizationFalseneeds_pristine_layer_cloneself.uses_grouped_optimization()(the fallback of the removed_processor_needs_pristine_group_clone)clean_group_layer_inputslayer_inputs(same object)receive_pristine_layer_module,receive_clean_layer_inputscapture_layer_forward_context_during_subsetTrue(keepsforward.capture_layer_context)begin_activation_scale_probe/end_activation_scale_probeFalse/ no-opThe call sites call the hooks directly.
_processor_needs_pristine_group_clone(stage_layer.py) andresolve_calibration_keep_mask(loop_processor.py, 2 callers) are deleted.The
forward_committed_batch_indicessignature outlier noted in the debloat map is gone on currentmain: bothforward_executor.pysites (run_single,run_parallel) call it withlayer_index=only, matching EXL3. The default returnsfrozenset(), sooutputs.committed_indices.union(...)is unchanged.In
run_subset_stage, the NVFP4 scale-probe, capture and zero-route recovery forwards share onefunctools.partialof their 13 common_run_forward_batchesarguments. Each call keeps its owncurrent_subset,shared_kv_cache_dict,need_outputs,reuse_kv, progress,force_serialandapply_moe_configarguments. The partial is built inside the guardedtry, so the [BUG] Failed quantization retains capture hooks and releases offload storage before finalizers finish #4470 hook release still covers it.Tests: processor doubles that relied on missing attributes now subclass
LoopProcessorthroughtests/module_tree/looper_doubles.ProcessorDouble. It skips__init__and takes keyword attributes like theSimpleNamespacedoubles it replaces.forwardis a plain class attribute (None), so a double may assign it, and an unset one still reads as missing. Converted: 16 processor classes intests/test_stage_modules.py, plus doubles in 12 other files. TheMagicMockprocessor intests/test_moe_expert_batching.pynow returnsFalsefromrestore_subset_capture_frontierinstead of setting the hook toNone. The twotests/test_stage_modules.pyassertions on the deleted_processor_needs_pristine_group_clonenow assertprocessor.needs_pristine_layer_clone()against the same expected values. No assertion was weakened or removed.Docs:
docs/quantization-lifecycle-contracts.mdgains an "Optional stage hooks" section and a before/after row.Out of scope, on purpose:
release_run_workspace/release_failed_runprobes in run teardown (weight_only_looper.py,release_failed_run_processors) belong to the concurrent shared-teardown refactor.heavy_finalize,native_capture, ...) are still read withgetattr(..., False).tasks,qcfg,_mask_tls,name) are unchanged.Tests
New tests in
tests/test_looper_processor_capabilities.py:test_optional_hook_overridden_exactly_where_it_was_defined[hook-cls](19 hooks x 13 processor classes): a class overrides a hook exactly when it, or a parent, defined the hook before this change.test_optional_hook_override_keeps_the_default_signature[...]: every override has the same parameter names and kinds as the base default.test_optional_hook_defaults_return_the_old_absent_hook_values: every default returns the old absent-hook value, andfinish_subset_zero_route_recoveryraises.test_pristine_clone_default_follows_grouped_optimization: theneeds_pristine_layer_clonefallback.Commands (both trees:
origin/mainworktree at1c51b32a7and this branch;PYTHONPATH=<tree> python -P,gptqmodel.__file__printed from each tree;HF_HUB_OFFLINE=1):origin/mainThese runs include the converted tests, among them
tests/test_stage_modules.py(54 passed),tests/test_moe_expert_batching.py,tests/test_calibration_data_device.py,tests/test_subset_plan.py,tests/test_looper_helpers.py,tests/test_replay_input_release_5735.py,tests/module_tree/test_forward_executor_parallel.pyandtests/module_tree/test_forward_executor_shared_kv.py. Before the doubles were converted, at least 80 of these nodes failed on this branch withAttributeError: ... has no attribute '<hook>'(60 in the other files, 20 intest_stage_modules.py).Failures, identical on both trees and unrelated to this change:
tests/test_looper_processor_capabilities.py::test_gptq_never_inherits_previous_calibration:verify_calibration_datasetnow readsself.calibration_dataset_owner, which the test'sSimpleNamespacelacks.tests/test_dynamic.py::TestDynamic::test_skip_module(GPU):RuntimeError: Expected all tensors to be on the same device ... index is on cpu ... cuda:0in the in-session reference forward after quantize. Not investigated here.Skips, and what they leave unverified:
compressed_tensors. The GPU job re-runs the CUDA-only files.run_parallelforwards are covered only by the CPU-double tests intests/module_tree/test_forward_executor_parallel.py. One node needs MPS and one needscompressed_tensors.Measured Impact
Not applicable: this refactor does not claim a performance, VRAM or accuracy change. The A/B below shows bit-identical checkpoints.
Structural and end-to-end A/B
hook_ab.pyruns beforequantize()builds any processor. It wraps every hook listed above onLoopProcessorand on every processor subclass at class level. Each call records (hook, defining class, processor, kwargs summary with tensor shape/dtype/sum checksums, return summary), andModuleLooper._run_forward_batcheskwargs are recorded too. The same model, config, seed and calibration (16 rows, batch 2) are then quantized onorigin/mainand on this branch, and the run is saved. The compare step asserts:LoopProcessordefault returns the old absent-hook value;_run_forward_batchescall has identical kwargs (this covers thefunctools.partial);opt_scope=moduleopt_scope=layeropt_scope=compute_blockHooks that ran through their real implementations:
bind_moe_quant_devices1;restore_subset_capture_frontier,restore_subset_capture_batches,subset_forward_capture_context,plan_subset_zero_route_recovery,commit_subset_capture_frontierandvalidate_subset_capture_readiness96 each;forward_committed_batch_indices119;forward_batch_completed952;prepare_runtime_weight_for_forward1001;prepare_layer_post_quantize24.uses_grouped_optimization,needs_pristine_layer_clone,clean_group_layer_inputs,receive_pristine_layer_moduleandreceive_clean_layer_inputs. Paro'scapture_layer_forward_context_during_subsetran in the layer and compute_block scopes.install_moe_affinity_hooks.The
_run_forward_batchescalls (29 to 119 per run) have identical kwargs in every run, which covers thefunctools.partial.Not run end-to-end:
finish_subset_zero_route_recoveryand a non-empty zero-route plan. They need an EXL3 route-evidence run, and none of these models triggers one. That call site changed fromgetattrplus raise to a direct call whose default raises the same error.tests/test_stage_modules.py::test_subset_pass_finishes_zero_route_recovery_before_quant_fanoutpasses on both trees.The W4A NVFP4 scale-probe call site needs NVFP4 tensor cores (sm_121). No GPU here has them (RTX 4090: "W4ANVFP4Linear needs a CUDA device with NVFP4 tensor cores (compute capability 12.1+)"), so
probe_ab.pydrivesrun_subset_stagethrough the existingtest_moe_expert_batchingMagicMock harness withqcfg.activation_mode="w4a_nvfp4"on both trees:_run_forward_batchescalls (kwargs)None)w4a_nvfp4, probe returnsTrueNVFP4 scale probe,Forward), identicalinstall_moe_affinity_hooks,subset_forward_capture_context,begin_activation_scale_probe,end_activation_scale_probe,plan_subset_zero_route_recovery,commit_subset_capture_frontier,validate_subset_capture_readinessw4a_nvfp4, probe returnsFalseForward), identicalend_activation_scale_probew4afp8Forward), identicaltests/models/test_non_w4a_lifecycle.pyfails if ordinary quantization enters a W4A path, includingbegin/end_activation_scale_probe. It passes on both trees.Model Support / Module Plan
Not applicable: no model, alias, definition or module plan changes.
AWQ onboarding safety
Not applicable: AWQ grouping, search, replay and folding are untouched.
AWQProcessorimplements none of these hooks and inherits the defaults, which return its old absent-hook values.Logic Flow Documentation
file:lineevidence.docs/repeats the diagrams, titled for the mechanism, and is linked fromREADME.md(viadocs/README.md).The hook dispatch mechanism changes from duck-typed probing to base-class defaults. The control flow at every site stays the same.
flowchart LR S["stage call site"] --> H["processor.hook(...)"] H --> O{"overridden?"} O -- "EXL3 / Paro / G2PTQ / GPTQ" --> I["processor implementation"] O -- "no" --> D["LoopProcessor default<br/>old absent-hook value"] D -. "finish_subset_zero_route_recovery<br/>without plan override" .-> X["RuntimeError (unchanged)"] style X fill:#fde2e11c51b32a7)stage_subset.py:932-961getattr(processor, "restore_subset_capture_frontier"/"restore_subset_capture_batches", None)+callableFalse/frozenset()stage_subset.py:1197-1201capture_layer_forward_context_during_subsetprobeTruestage_subset.py:1209-1211install_moe_affinity_hooksprobe (base default already existed)stage_subset.py:1258-1269subset_forward_capture_contextprobe, elsenullcontext()nullcontext()stage_subset.py:1277-1283,:1310begin/end_activation_scale_probeprobesFalse/ no-opstage_subset.py:1351-1358,:1425-1435(); finish probe, elseRuntimeError()/ sameRuntimeErrorstage_subset.py:1515-1531stage_subset.py:1286,1312,1401_run_forward_batchescalls repeating 13 kwargsfunctools.partialstage_layer.py:226-232,:814-820_processor_needs_pristine_group_clone+uses_grouped_optimizationprobesprocessor.needs_pristine_layer_clone()/uses_grouped_optimization()stage_layer.py:507-571_capture_pristine_group_contextstage_layer.py:1399-1409prepare_layer_post_quantizeprobe (base default existed)forward_executor.py:434-440,:702-708forward_committed_batch_indicesprobe.union(processor.forward_committed_batch_indices(layer_index=...))forward_executor.py:620-622,:934-941forward_batch_completedprobeforward_executor.py:527,utils/looper_helpers.py:870vialoop_processor.py:521resolve_calibration_keep_maskprobe helperprocessor.calibration_keep_mask(...)module_looper.py:421-425,:1383-1388;loop_processor.py:229-234bind_moe_quant_devices/prepare_runtime_weight_for_forwardprobesReview Requirements
Kernel Accuracy Requirements
Not applicable: no kernel, dispatch, packing or fusion change.
Notes
LoopProcessorsubclass now receives these calls. A non-LoopProcessorduck-typed processor would now raiseAttributeErrorwhere it used to be skipped. Every in-tree processor subclassesLoopProcessor. Only test doubles relied on the old behaviour, and they were converted.run_subset_stagepassesprocessor=getattr(processor, "name", type(processor).__name__)to the subset callback for theforward_start,forward_end,quant_start,quant_completeandzero_route_recovery_*events.nameis a method, so a registeredsubset_callbackreceives a bound method there, while the other events receive theprocessor.name()string. This PR does not change that.main:tests/test_looper_processor_capabilities.py::test_gptq_never_inherits_previous_calibrationfails on both trees.verify_calibration_datasetnow readsself.calibration_dataset_owner, which the test'sSimpleNamespacelacks.🤖 Generated with Claude Code