Skip to content

refactor(gptq): use SharedInputCaptureMixin instead of GPTQProcessor's private copy - #6428

Merged
Qubitium merged 1 commit into
mainfrom
refactor/gptq-shared-input-mixin
Nov 29, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/gptq-shared-input-mixin

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Behavior-preserving debloat. GPTQProcessor carried a private copy of the shared-input Hessian leader election: _resolve_shared_input_plan, begin_shared_input_capture, end_shared_input_capture, shared_input_leader and the election loop inside begin. When #4514 added SharedInputCaptureMixin with the same algorithm for QQQ, VPTQ, MACaQ and EXL3, it left that copy in place. GPTQProcessor now derives from SharedInputCaptureProcessor, like the other calibrated processors, and keeps only its GPTQ-specific behavior as four mixin hooks.

Net diff: 6 files changed, 73 insertions(+), 173 deletions(-) (-100 lines). The gptqmodel/ part is 3 files changed, 33 insertions(+), 163 deletions(-) (-130).

No issue is claimed. This is one of the maintainer-requested debloat refactors.

What Changed

File Change
gptqmodel/looper/gptq_processor.py Base class LoopProcessor → SharedInputCaptureProcessor. Deleted the private state init, _resolve_shared_input_plan, begin_shared_input_capture, end_shared_input_capture and shared_input_leader (about 150 lines). _hessian_capture_signature is renamed to the mixin hook _shared_input_task_signature, with the same body. Added _shared_input_task_enabled, _shared_input_begin_cohort and _shared_input_task_adopt.
gptqmodel/looper/shared_input.py _shared_input_begin_cohort(tasks) now also receives subset_names, because GPTQ clears factor caches only for tasks in the subset. No other processor overrides this hook. begin_shared_input_capture materializes subset_names once, so the hook and the election see the same names. Module docstring updated.
gptqmodel/looper/g2ptq_processor.py Docstring now names the renamed hook.
docs/gptq-hessian-accumulation.md The shared-input section and table now say that GPTQ uses the mixin, and the stale line pointers are refreshed.
tests/test_shared_input_hessian_dedup_methods.py test_shared_input_capture_methods_resolve_to_single_shared_base now also runs for GPTQProcessor.
tests/test_shared_input_hessian_dedup.py New test_factor_cache_is_one_per_leader_and_fresh_per_cohort.

The GPTQ hooks:

def _shared_input_task_enabled(self, task): return bool(task.qcfg.hessian.dedup_shared_inputs)
def _shared_input_begin_cohort(self, tasks, subset_names):   # clear plain-GPTQ factor caches in the subset
def _shared_input_task_adopt(self, follower, leader):
    follower.adopt_hessian_from(leader)
    if type(leader) is GPTQ and type(follower) is GPTQ:
        cache = leader._shared_hessian_cache            # None: cleared when this cohort began
        if cache is None:
            cache = SharedHessianFactorCache(self._shared_input_capture_generation, leader.name, leader=leader.name)
            leader.attach_shared_hessian_cache(cache)
        follower.attach_shared_hessian_cache(cache)
  • Factor-cache ownership. The old end kept a call-local caches dict keyed by the leader's name. The debloat map suggested a processor-level _factor_caches dict that would be reset at the next cohort. That dict would keep every leader's cached Cholesky factors alive between passes, so I did not use it. The leader task's own cache slot serves as that dict instead. begin clears it, the first follower fills it, and later followers join it. Only the tasks reference a cache, as before. leader.name equals the old dict key because GPTQProcessor.tasks is keyed by module.name, which is GPTQ.name. Peak torch.cuda.max_memory_allocated is unchanged (see the GPU A/B).
  • API. Nothing public changes. The private _hessian_capture_signature is renamed, and nothing outside gptq_processor.py called it.
  • Observable differences. There are two, and neither affects numerics:
    1. The mismatch warning text changes from "mixes Hessian capture settings" to the mixin's "mixes Hessian accumulation settings". No test or doc matches on that text.
    2. _shared_input_capture_generation now also advances when the model has no shared-input groups. No factor cache exists in that case. Every factor cache that is created gets the same generation as on origin/main, as the structural A/B shows. The generation is used only inside one cache's key.
  • Early-return check. The mixin tests dedup_shared_inputs_enabled(self.qcfg) where the old code tested self.qcfg.hessian.dedup_shared_inputs. These are the same here: _normalize_hessian always gives GPTQ configs a HessianConfig.
  • Out of scope. No other part of the lifecycle changes.

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.

New and extended tests:

  • tests/test_shared_input_hessian_dedup.py::TestProcessorLeaderElection::test_factor_cache_is_one_per_leader_and_fresh_per_cohort runs two leaders (q→k,v and g→u) in one subset, twice. It checks one cache per leader shared by its followers, the cohort and leader strings, and a fresh cache with a higher generation in the second cohort. It passes on origin/main and on this branch. Red evidence on this branch, with each mutant applied separately:
    • Dropping clear_shared_hessian_cache() from _shared_input_begin_cohort makes it fail at caches[1][0] is not caches[0][0] (a stale cache is reused).
    • Always creating a new cache in _shared_input_task_adopt makes it fail at tasks["self_attn.k"]._shared_hessian_cache is attn (followers stop sharing).
  • tests/test_shared_input_hessian_dedup_methods.py::test_shared_input_capture_methods_resolve_to_single_shared_base[GPTQProcessor-qcfg0] is new. On origin/main it fails at issubclass(GPTQProcessor, SharedInputCaptureProcessor).

Commands and results:

# Core files from the debloat map, CPU (CUDA_VISIBLE_DEVICES="")
PYTHONPATH=$PWD python -P -m pytest -q -rs -p no:cacheprovider \
  tests/test_shared_input_hessian_dedup_methods.py tests/test_shared_input_hessian_dedup.py \
  tests/test_gptq_shared_hessian.py tests/test_gptq_hessian_pipeline.py
# branch: 84 passed, 4 skipped (CUDA-only nodes, run on GPU below)

# On one GPU (CUDA_VISIBLE_DEVICES=<gpu>), origin/main vs branch, same invocation:
# CUDA-only nodes of the core files (skipped on CPU above):
#   test_gptq_shared_hessian.py::test_prepare_exl3_hessian_releases_deferred_capture_partials,
#   test_gptq_hessian_pipeline.py::{test_cuda_hessian_chunk_does_not_call_device_synchronize,
#   test_cuda_workspace_reuse_across_streams, test_cuda_embedding_hessian_materialization_waits_for_prior_stream}
#   origin/main: 4 passed   branch: 4 passed
# CUDA-gated families, one pytest per file on one GPU:
#   tests/test_g2ptq_processor.py tests/test_gptq.py tests/test_admmq.py tests/test_fallback.py
#   tests/test_shared_input_hessian_dedup_real_model_e2e.py tests/test_shared_input_hessian_dedup_e2e.py
#   origin/main: 398 passed, 1 skipped   branch: 398 passed, 1 skipped   (0 per-node outcome differences)
#   skip: test_admmq::test_admmq_solve_device_hosts_npu ("this Torch build has no NPU device type")
#   tests/test_dynamic.py (quantizes Qwen2.5-0.5B-Instruct with dynamic overrides; too slow on CPU):
#   origin/main: 4 passed, 1 failed   branch: 4 passed, 1 failed (same node, same error)
#   The failure is test_dynamic.py::TestDynamic::test_skip_module, at test_dynamic.py:261. The reloaded
#   CUDA model gets CPU input_ids from the test's direct model(**inputs) call: "Expected all tensors to be
#   on the same device ... index is on cpu". This happens after quantize/save/reload and is unrelated to
#   the shared-input election, whose dedup telemetry is all `verified` in that run.

# Affected-family sweep: the 64 files under tests/ (not tests/models/) that mention GPTQProcessor,
# G2PTQProcessor, shared_input, SharedHessianFactorCache, gptq_processor or dedup_shared_inputs.
# Same invocation on origin/main and on the branch, CUDA_VISIBLE_DEVICES="".
#   origin/main: 2476 nodes: 2291 passed, 169 skipped, 16 failed
#   branch:      2478 nodes: 2293 passed, 169 skipped, 16 failed
#   Per-node outcome differences on common nodes: none. The node-id differences are only the
#   parametrize ids shifted by the added GPTQProcessor case, plus the two new nodes.
#   The 16 failures are identical on both sides, and all 16 are the tiny-tokenizer rejection added in
#   #6386 ("The tokenizer in ... is unusable"): test_gptaq_foem_first_capture_5831.py (6),
#   test_gptaq_shuffle_pairing_4869.py (3), test_gptq_processor_hessian_release_5026.py (5) and
#   test_processor_finalize_4747.py (2).
#   The 169 skips need CUDA, an NPU or Tenstorrent, or FP8 tensor cores. The CUDA skips in
#   test_g2ptq_processor, test_gptq, test_admmq, test_fallback and the dedup e2e files were rerun on
#   GPU above. Not rerun: test_auto_dtype_cast (NF12), test_benchmark_submodule_finalize,
#   test_serialization, test_awq_gptq_lifecycle, the multi-GPU test_fp8_minimax2_test node, the
#   Tenstorrent and NPU suites, and the FP8 kernel tests. None of them targets the shared-input election, but those nodes are unverified on this branch.
#   tests/test_dynamic.py hit the 900 s per-file cap on CPU on both sides and was run on GPU instead.

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

Structural A/B: election, adoption and factor caches (CPU)

struct_ab.py is attached in the collapsed block below. It drives GPTQProcessor.begin/preprocess/hook/end_shared_input_capture and then quantize() on CPU. The fixture is a two-group tree (self_attn q,k,v in=x; mlp g,u in=y) with correlated, non-diagonal activations. The scenarios are the product of:

  • 9 configs: GPTQ, GPTQ desc_act, dedup off, dedup off for k only through dynamic, a k staging-dtype mismatch, GPTAQ, FOEM, JointQ and ADMM-Q;
  • 3 subset layouts: per-layer subsets, everything in one subset (with a width-mismatched v for GPTQ), and a group split across subsets;
  • 5 variants on the per-layer layout: normal, is_lm_head_module, no plan, a leader pruned before end, and two capture passes over the same tasks.

For each scenario it records the elected leaders, the end telemetry, every capture counter and nsamples, sha256 of H, dXXT and the quantized weight, the factor-cache identity graph (which tasks share one cache object, with its cohort, leader and generation), and the warnings.

python -P struct_ab.py dump old.json   # PYTHONPATH=origin/main checkout
python -P struct_ab.py dump new.json   # PYTHONPATH=branch checkout
python -P struct_ab.py compare old.json new.json
scenarios: 63; tasks: 425; follower elections: 123; factor caches: 38
strict mismatches (leaders, telemetry, counters, H/dXXT/wq checksums, cache graph, errors): 0 []
generation-only differences: 8          # all 8 are the `no_plan` variant: 0 -> 4, no cache exists there
warning-text differences: 6             # "capture settings" -> "accumulation settings", same values

GPU A/B: bit-identical checkpoints

One GPU. Each model was quantized on origin/main (6b25d2c) and on this branch with the same config, seed and calibration (64 fixed synthetic texts, batch_size=1, 4-bit g128). The script compares every saved tensor byte-for-byte, every *.json, the sorted quant_log rows with time, fwd_time and (v)ram dropped, and every end_shared_input_capture telemetry record. (v)ram is Device-SMI's device-wide usage, which includes other tenants on the shared GPU, so allocator peak is compared separately. Each log shows that gptqmodel.__file__ came from the intended checkout.

Model Method Tensors (mismatched) JSON differing quant_log rows equal (distinct samples) Dedup passes / adopted followers (equal) Peak alloc old / new Result
Qwen/Qwen2.5-0.5B-Instruct (q/k/v and gate/up share input) GPTQ 794 (0) 0 of 5 168 = 168 (7553) 96 / 72, equal, all verified not recorded bit-identical
Qwen/Qwen2.5-0.5B-Instruct GPTAQ 794 (0) 0 of 5 168 = 168 (7553) 96 / 72, equal, all verified not recorded bit-identical
tiny random Mixtral (mixtral is a shared-input verified MoE: q/k/v plus per-expert gate/up; 2 layers, 4 experts, top-2, hidden 256) GPTQ 137 (0) 0 of 5 32 = 32 (9 distinct per-expert counts) 8 / 12, equal, all verified 384.9 / 384.9 MiB bit-identical
same tiny Mixtral GPTAQ 137 (0) 0 of 5 32 = 32 (9 distinct) 8 / 12, equal, all verified 384.8 / 384.8 MiB bit-identical
trl-internal-testing/tiny-Qwen3_5MoeForConditionalGeneration-3.6 GPTQ 200 (0) 0 of 6 37 = 37 (9 distinct) 9 / 0 not recorded bit-identical, but dedup is not exercised

The tiny Qwen3.5-MoE checkpoint has model_type qwen3_5_moe. That type is not in Qwen3_5_MoeQModel.shared_input_verified_model_types; only qwen3_5_moe_text is listed there. Its plan therefore has no explicit groups and no module shares a Hessian, which is intended. That is why I added the tiny Mixtral, built by make_tiny_mixtral.py with transformers.MixtralForCausalLM, torch.manual_seed(0) and the Qwen2.5 tokenizer, as the MoE case that does dedup. OLMoE-1B-7B is cached, but its module_tree has no :in= tags, so it would not exercise dedup either.

quant_ab.py / struct_ab.py / make_tiny_mixtral.py

quant_ab.py

"""Quantize one model with a fixed config/seed/calibration, save it, and record
the quant log plus every shared-input dedup telemetry record.

    PYTHONPATH=<checkout> python -P quant_ab.py quant <model_id> <gptq|gptaq|foem> <out_dir>
    python -P quant_ab.py compare <dir_a> <dir_b>
"""

import json
import os
import random
import sys

VOLATILE = {"time", "fwd_time", "used_memory", "process_used_memory"}


def _calibration():
    words = (
        "the model quantization layer weight scale group token sequence attention expert router "
        "norm residual projection calibration sample output input hidden state matrix vector value"
    ).split()
    rng = random.Random(1234)
    return [" ".join(rng.choice(words) for _ in range(rng.randint(48, 160))) for _ in range(64)]


def quant(model_id, method, out_dir):
    import numpy as np
    import torch

    import gptqmodel
    from gptqmodel import GPTQModel
    from gptqmodel.looper.gptq_processor import GPTQProcessor
    from gptqmodel.quantization.config import CalibrationConfig, FOEMConfig, GPTAQConfig, QuantizeConfig

    print("gptqmodel.__file__ =", gptqmodel.__file__, flush=True)
    random.seed(0)
    np.random.seed(0)
    torch.manual_seed(0)
    group_size = -1 if method.endswith("_pc") else 128
    extra = {}
    if method.startswith("gptaq"):
        extra["gptaq"] = GPTAQConfig()
    elif method.startswith("foem"):
        extra["foem"] = FOEMConfig(alpha=0.25)
    qcfg = QuantizeConfig(bits=4, group_size=group_size, **extra)

    telemetry = []
    end = GPTQProcessor.end_shared_input_capture

    def spy_end(self, subset_names):
        tel = end(self, subset_names)
        telemetry.append({"subset": list(subset_names), **(tel or {})})
        return tel

    GPTQProcessor.end_shared_input_capture = spy_end
    model = GPTQModel.load(model_id, qcfg)
    model.quantize(CalibrationConfig(dataset=_calibration(), batch_size=1))
    model.save(out_dir)
    rows = []
    for row in model.quant_log or []:
        rows.append({k: str(v) for k, v in row.items() if k not in VOLATILE})
    peak = torch.cuda.max_memory_allocated() if torch.cuda.is_available() else 0
    json.dump({"quant_log": rows, "dedup_telemetry": telemetry, "peak_alloc_bytes": peak},
              open(os.path.join(out_dir, "ab_quant_log.json.txt"), "w"), indent=1, sort_keys=True, default=str)
    print(f"quant_log rows: {len(rows)}; dedup passes: {len(telemetry)}; "
          f"adopted followers: {sum(t.get('adopted_followers', 0) for t in telemetry)}", flush=True)


def compare(a, b):
    import torch
    from safetensors import safe_open

    def tensors(root):
        out = {}
        for name in sorted(os.listdir(root)):
            if name.endswith(".safetensors"):
                with safe_open(os.path.join(root, name), framework="pt") as fh:
                    for key in fh.keys():
                        out[key] = fh.get_tensor(key)
        return out

    def raw(t):
        return t.view(torch.uint8) if t.dtype.is_floating_point else t

    ta, tb = tensors(a), tensors(b)
    assert ta, f"no tensors in {a}"
    mismatched = [k for k in sorted(set(ta) | set(tb)) if k not in ta or k not in tb
                  or ta[k].dtype != tb[k].dtype or ta[k].shape != tb[k].shape
                  or not torch.equal(raw(ta[k]), raw(tb[k]))]
    print(f"tensors: {len(ta)} vs {len(tb)}; mismatched: {len(mismatched)} {mismatched[:10]}")
    json_diffs = []
    names = sorted(n for n in set(os.listdir(a)) | set(os.listdir(b)) if n.endswith(".json"))
    for name in names:
        pa, pb = os.path.join(a, name), os.path.join(b, name)
        if not (os.path.exists(pa) and os.path.exists(pb)):
            json_diffs.append((name, "missing on one side"))
        elif json.load(open(pa)) != json.load(open(pb)):
            json_diffs.append((name, "differs"))
    print(f"json files compared: {len(names)}; differing: {json_diffs}")

    la = json.load(open(os.path.join(a, "ab_quant_log.json.txt")))
    lb = json.load(open(os.path.join(b, "ab_quant_log.json.txt")))

    def rows(log):
        # "(v)ram" is Device-SMI's device-wide used memory, which includes other
        # tenants' processes on the shared GPU; peak allocator bytes are compared below.
        return sorted(json.dumps({k: v for k, v in r.items() if k != "(v)ram"}, sort_keys=True)
                      for r in log["quant_log"])

    def tel(log):
        return sorted(json.dumps(t, sort_keys=True) for t in log["dedup_telemetry"])

    ra, rb = rows(la), rows(lb)
    samples = sorted({json.loads(r).get("samples") for r in ra})
    print(f"quant_log rows (time/memory dropped, sorted): {len(ra)} vs {len(rb)}; equal: {ra == rb}; "
          f"distinct sample counts: {samples}")
    tela, telb = tel(la), tel(lb)
    adopted = sum(t.get("adopted_followers", 0) for t in la["dedup_telemetry"])
    statuses = sorted({t.get("status") for t in la["dedup_telemetry"]} - {None})
    print(f"dedup telemetry passes: {len(tela)} vs {len(telb)}; equal: {tela == telb}; "
          f"adopted followers: {adopted}; statuses: {statuses}")
    if "peak_alloc_bytes" in la and "peak_alloc_bytes" in lb:
        print(f"peak torch.cuda.max_memory_allocated: {la['peak_alloc_bytes'] / 2**20:.1f} MiB vs "
              f"{lb['peak_alloc_bytes'] / 2**20:.1f} MiB")
    ok = not mismatched and not json_diffs and ra == rb and tela == telb
    print("RESULT:", "bit-identical" if ok else "DIFF")
    return 0 if ok else 1


if __name__ == "__main__":
    if sys.argv[1] == "quant":
        quant(*sys.argv[2:5])
    else:
        sys.exit(compare(sys.argv[2], sys.argv[3]))

struct_ab.py

"""Structural A/B of GPTQProcessor shared-input election/adoption.

    PYTHONPATH=<checkout> python -P struct_ab.py dump <out.json>
    python -P struct_ab.py compare <old.json> <new.json>

For every scenario it records the elected leaders, the end telemetry, every
log.warn message, each task's capture counters and Hessian/dXXT checksums,
the factor-cache identity graph (which tasks share one cache object, plus its
cohort/leader/generation), and the checksum of every task's quantize() output.
"""

import hashlib
import json
import sys
from types import SimpleNamespace


def _sha(t):
    import torch

    if t is None:
        return None
    t = t.detach().contiguous().cpu()
    if t.dtype.is_floating_point:
        t = t.view(torch.uint8) if t.element_size() == 1 else t.view(getattr(torch, f"int{8 * t.element_size()}"))
    return hashlib.sha256(t.numpy().tobytes()).hexdigest()[:16] + f":{tuple(t.shape)}"


def dump(out):
    import torch
    from torch import nn

    import gptqmodel
    from gptqmodel.looper import gptq_processor as gp_mod
    from gptqmodel.looper.gptq_processor import GPTQProcessor
    from gptqmodel.looper.named_module import NamedModule
    from gptqmodel.looper.native_processor import NATIVE_INPUTS_STATE_KEY
    from gptqmodel.models.shared_input import build_shared_input_plan
    from gptqmodel.quantization.config import (
        ADMMQConfig, CalibrationConfig, FOEMConfig, GPTAQConfig, HessianConfig, JointQConfig, QuantizeConfig,
    )

    print("gptqmodel.__file__ =", gptqmodel.__file__)
    import gptqmodel.looper.shared_input as si_mod

    warns = []

    class _Log:
        def __init__(self, real):
            self.real = real

        def warn(self, msg, *a, **k):
            warns.append(str(msg))

        def __getattr__(self, name):
            return getattr(self.real, name)

    gp_mod.log = _Log(gp_mod.log)
    si_mod.log = _Log(si_mod.log)

    tree = ["model", "layers", "#", {"self_attn": ("q:0:in=x", "k:0:in=x", "v:0:in=x", "o:1"),
                                      "mlp": ("g:0:in=y", "u:0:in=y", "d:1")}]
    layer_modules = [["self_attn.q", "self_attn.k", "self_attn.v"], ["self_attn.o"], ["mlp.g", "mlp.u"], ["mlp.d"]]
    plan = build_shared_input_plan(tree, layer_modules)
    QKV = ["self_attn.q", "self_attn.k", "self_attn.v"]
    O = ["self_attn.o"]
    GU = ["mlp.g", "mlp.u"]
    D = ["mlp.d"]

    def fake_model(qcfg, with_plan=True):
        ns = SimpleNamespace(model=SimpleNamespace(config=SimpleNamespace(num_hidden_layers=1)), quantize_config=qcfg)
        if with_plan:
            ns.shared_input_plan = lambda model_config=None, quantize_config=None, is_awq_quantize=False: plan
        return ns

    width = 32
    gen = torch.Generator().manual_seed(1)
    # correlated, non-diagonal activations
    mix = torch.randn(width, width, generator=gen)
    batches = [torch.randn(2, 8, width, generator=gen) @ mix for _ in range(4)]

    def named(name, seed, in_features=width):
        torch.manual_seed(seed)
        return NamedModule(nn.Linear(in_features, 48, bias=False), name=name,
                           full_name=f"model.layers.0.{name}", layer_index=0)

    base = dict(bits=4, group_size=8, desc_act=False)
    configs = {
        "gptq": QuantizeConfig(**base),
        "gptq_desc_act": QuantizeConfig(bits=4, group_size=8, desc_act=True),
        "gptq_dedup_off": QuantizeConfig(**base, hessian=HessianConfig(dedup_shared_inputs=False)),
        "gptq_k_dedup_off": QuantizeConfig(**base, dynamic={r".*\.self_attn\.k$": {"hessian": {"dedup_shared_inputs": False}}}),
        "gptq_k_staging_mismatch": QuantizeConfig(**base, hessian=HessianConfig(staging_dtype="bfloat16"),
                                                  dynamic={r".*\.self_attn\.k$": {"hessian": {"staging_dtype": "float32"}}}),
        "gptaq": QuantizeConfig(**base, gptaq=GPTAQConfig()),
        "foem": QuantizeConfig(**base, foem=FOEMConfig(alpha=0.25)),
        "jointq": QuantizeConfig(**base, jointq=JointQConfig()),
        "admmq": ADMMQConfig(**base),
    }
    subset_plans = {
        "layer_subsets": [QKV, O, GU, D],
        "one_subset": [QKV + O + GU + D],
        "split_group": [["self_attn.q", "self_attn.o"], ["self_attn.k", "self_attn.v"], GU, D],
    }
    results = {}
    for cname, qcfg in configs.items():
        for sname, subsets in subset_plans.items():
            for variant in ("normal", "lm_head", "no_plan", "pruned_leader", "two_passes"):
                if variant != "normal" and sname != "layer_subsets":
                    continue
                key = f"{cname}/{sname}/{variant}"
                warns.clear()
                rec = {"passes": []}
                try:
                    proc = GPTQProcessor(tokenizer=None, qcfg=qcfg, calibration=CalibrationConfig())
                    model = fake_model(qcfg, with_plan=(variant != "no_plan"))
                    modules = {}
                    all_names = [n for s in subsets for n in s]
                    for i, n in enumerate(all_names):
                        m = named(n, seed=10 + i, in_features=(width * 2 if (cname == "gptq" and n == "self_attn.v" and sname == "one_subset") else width))
                        m.state[NATIVE_INPUTS_STATE_KEY] = [(bi, x) for bi, x in enumerate(batches)]
                        proc.preprocess(m)
                        modules[n] = m
                    passes = 2 if variant == "two_passes" else 1
                    cache_ids = {}
                    for p in range(passes):
                        for subset in subsets:
                            leaders = proc.begin_shared_input_capture(model, subset, is_lm_head_module=(variant == "lm_head"))
                            hooks = {n: proc.pre_process_fwd_hook(n) for n in subset}
                            if p == 0:
                                for bi, x in enumerate(batches):
                                    proc._set_current_batch_index(bi)
                                    for n in subset:
                                        mod = modules[n].module
                                        xin = x if mod.in_features == width else torch.cat([x, x], dim=-1)
                                        hooks[n](mod, (xin,), mod(xin))
                                proc._set_current_batch_index(None)
                            if variant == "pruned_leader" and leaders:
                                proc.tasks.pop(sorted(set(leaders.values()))[0], None)
                            tel = proc.end_shared_input_capture(subset)
                            graph = {}
                            for n in subset:
                                t = proc.tasks.get(n)
                                c = getattr(t, "_shared_hessian_cache", None) if t is not None else None
                                if c is None:
                                    graph[n] = None
                                else:
                                    idx = cache_ids.setdefault(id(c), len(cache_ids))
                                    graph[n] = {"cache": idx, "cohort": c.cohort, "leader": c.leader, "generation": c.generation}
                            rec["passes"].append({"subset": subset, "leaders": leaders, "telemetry": tel, "cache_graph": graph})
                    rec["generation_final"] = proc._shared_input_capture_generation
                    rec["dedup_count"] = proc.shared_input_dedup_count
                    tasks = {}
                    for n in sorted(proc.tasks):
                        t = proc.tasks[n]
                        tasks[n] = {"type": type(t).__name__, "fwd_counter": t.fwd_counter, "nsamples": t.nsamples,
                                    "H": _sha(t.H), "dXXT": _sha(getattr(t, "dXXT", None))}
                    for n in sorted(proc.tasks):
                        t = proc.tasks[n]
                        try:
                            t.quantizer.configure(perchannel=True)
                            qout = t.quantize()
                            tasks[n]["wq"] = _sha(qout[0])
                            tasks[n]["post_H"] = _sha(t.H)
                        except Exception as exc:  # recorded, compared like any value
                            tasks[n]["wq"] = f"ERR {type(exc).__name__}: {exc}"[:200]
                    rec["tasks"] = tasks
                except Exception as exc:
                    rec["error"] = f"{type(exc).__name__}: {exc}"[:300]
                rec["warns"] = list(warns)
                results[key] = rec
    json.dump(results, open(out, "w"), indent=1, sort_keys=True, default=str)
    print(f"scenarios: {len(results)}; errors: {sum('error' in r for r in results.values())}")


def compare(a, b):
    A, B = json.load(open(a)), json.load(open(b))
    assert set(A) == set(B)
    strict_diffs, gen_diffs, warn_diffs = [], [], []
    n_followers = n_caches = n_tasks = 0

    def strip(rec):
        rec = json.loads(json.dumps(rec))
        gens = []
        for p in rec.get("passes", []):
            for v in p["cache_graph"].values():
                if v:
                    gens.append(v.pop("generation"))
        gens.append(rec.pop("generation_final", None))
        warns = rec.pop("warns")
        return rec, gens, warns

    for k in sorted(A):
        ra, ga, wa = strip(A[k])
        rb, gb, wb = strip(B[k])
        if ra != rb:
            strict_diffs.append(k)
        if ga != gb:
            gen_diffs.append((k, ga, gb))
        if wa != wb:
            warn_diffs.append((k, wa, wb))
        for p in ra.get("passes", []):
            n_followers += len(p["leaders"])
            n_caches += len({v["cache"] for v in p["cache_graph"].values() if v})
        n_tasks += len(ra.get("tasks", {}))
    print(f"scenarios: {len(A)}; tasks: {n_tasks}; follower elections: {n_followers}; factor caches: {n_caches}")
    print(f"strict mismatches (leaders, telemetry, counters, H/dXXT/wq checksums, cache graph, errors): {len(strict_diffs)} {strict_diffs[:5]}")
    print(f"generation-only differences: {len(gen_diffs)}")
    for k, ga, gb in gen_diffs[:3]:
        print("  ", k, ga, "->", gb)
    print(f"warning-text differences: {len(warn_diffs)}")
    for k, wa, wb in warn_diffs[:2]:
        print("  ", k, "\n     old:", wa, "\n     new:", wb)
    return 1 if strict_diffs else 0


if __name__ == "__main__":
    if sys.argv[1] == "dump":
        dump(sys.argv[2])
    else:
        sys.exit(compare(sys.argv[2], sys.argv[3]))

make_tiny_mixtral.py

"""Build a deterministic tiny Mixtral (model_type `mixtral`, a shared-input
verified MoE definition) with the Qwen2.5-0.5B-Instruct tokenizer.

    python -P make_tiny_mixtral.py <out_dir>
"""
import sys

import torch
from transformers import AutoTokenizer, MixtralConfig, MixtralForCausalLM

out = sys.argv[1]
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
cfg = MixtralConfig(
    vocab_size=len(tok), hidden_size=256, intermediate_size=512, num_hidden_layers=2,
    num_attention_heads=4, num_key_value_heads=2, head_dim=64, num_local_experts=4, num_experts_per_tok=2,
    max_position_embeddings=2048, bos_token_id=tok.bos_token_id, eos_token_id=tok.eos_token_id,
    pad_token_id=tok.pad_token_id, tie_word_embeddings=False, torch_dtype="bfloat16",
)
torch.manual_seed(0)
model = MixtralForCausalLM(cfg).to(torch.bfloat16)
model.save_pretrained(out)
tok.save_pretrained(out)
print("saved", out, sum(p.numel() for p in model.parameters()))

Measured Impact

Not applicable: no claimed issue and no runtime change. Peak torch.cuda.max_memory_allocated matches on the tiny Mixtral (table above).

Model Support / Module Plan

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

Model test node IDs and results (or "not applicable"): not applicable.

AWQ onboarding safety

Not applicable: AWQ is not touched.

AWQ evidence and per-variant policy (or "not applicable" with a reason): not applicable.

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.

Diagram summary: the election itself does not change, but GPTQ's copy is replaced by the shared mechanism. The existing page docs/gptq-hessian-accumulation.md ("Shared-input dedup for calibrated quantizers") already has this flow diagram. Its text and table are updated here to say that GPTQ uses the mixin.

flowchart TD
    A["stage_subset: subset_names"] --> B["SharedInputCaptureMixin.begin_shared_input_capture"]
    B --> C["GPTQProcessor._shared_input_begin_cohort<br/>clear plain-GPTQ factor caches in subset"]
    C --> D{"is_lm_head_module or dedup off?"}
    D -- Yes --> Z["return empty: every module captures"]
    D -- No --> E["_resolve_shared_input_plan(model)"]
    E --> F["elect_shared_input_leaders<br/>enabled_for = _shared_input_task_enabled<br/>signature_for = _shared_input_task_signature"]
    F --> G{"signatures equal?"}
    G -- No --> W["log.warn; follower captures independently"]
    G -- Yes --> H["_shared_input_leaders = follower to leader"]
    H --> I["pre_process_fwd_hook: follower hook skips"]
    I --> J["SharedInputCaptureMixin.end_shared_input_capture"]
    J --> K{"leader and follower tasks present?"}
    K -- No --> M["skip; telemetry status = mismatch"]
    K -- Yes --> L["GPTQProcessor._shared_input_task_adopt<br/>adopt_hessian_from, then one SharedHessianFactorCache per plain-GPTQ leader"]
    classDef fail fill:#fdd,stroke:#c33
    classDef ok fill:#dfd,stroke:#060
    class W,M fail
    class L ok
Loading
Step Before (origin/main 6b25d2c) After
State init gptq_processor.py:251-259, inline copy SharedInputCaptureMixin._init_shared_input_capture (shared_input.py:105), called at gptq_processor.py:249
Plan resolution GPTQProcessor._resolve_shared_input_plan (gptq_processor.py:511) SharedInputCaptureMixin._resolve_shared_input_plan (shared_input.py:136), same body
Factor-cache reset inline in begin (gptq_processor.py:596-599) GPTQProcessor._shared_input_begin_cohort (gptq_processor.py:545)
Early return self.qcfg.hessian.dedup_shared_inputs (gptq_processor.py:601) dedup_shared_inputs_enabled(self.qcfg) (shared_input.py:169), the same for GPTQ configs
Election loop inline (gptq_processor.py:612-636) elect_shared_input_leaders (shared_input.py:42)
Per-task enable task.qcfg.hessian.dedup_shared_inputs (gptq_processor.py:619) GPTQProcessor._shared_input_task_enabled (gptq_processor.py:542)
Capture signature _hessian_capture_signature (gptq_processor.py:552) _shared_input_task_signature (gptq_processor.py:517), same body
Adoption and factor cache inline in end, call-local caches dict (gptq_processor.py:642-667) SharedInputCaptureMixin.end_shared_input_capture (shared_input.py:187) and GPTQProcessor._shared_input_task_adopt (gptq_processor.py:553)
Telemetry inline (gptq_processor.py:672-685) mixin (shared_input.py:204-217), same keys and values
shared_input_leader gptq_processor.py:687 shared_input.py:219, same body

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. The GPU A/B above gives bit-identical checkpoints.

Notes

  • _shared_input_task_adopt reads the private GPTQ._shared_hessian_cache slot from the processor. That avoids keeping a processor-level cache dict alive. A public getter on GPTQ would be a separate, purely cosmetic change.
  • G2PTQProcessor still overrides begin_shared_input_capture and calls super(), which now resolves to the mixin. Its tasks still get a None signature.

🤖 Generated with Claude Code

@Qubitium
Qubitium marked this pull request as ready for review November 29, 2026 20:13
…s private copy

GPTQProcessor carried its own copy of the shared-input leader election
(_resolve_shared_input_plan, begin/end_shared_input_capture,
shared_input_leader and the inline election loop). #4514 introduced
SharedInputCaptureMixin with the same algorithm for QQQ, VPTQ, MACaQ and EXL3
but left the GPTQ copy in place.

GPTQProcessor now derives from SharedInputCaptureProcessor and keeps only
its GPTQ-specific parts as mixin hooks:

- _shared_input_task_enabled: the per-task hessian.dedup_shared_inputs check.
- _shared_input_task_signature: the former _hessian_capture_signature
  (GPTQ/ADMM-Q, GPTAQ, FOEM and JointQ cohorts), renamed.
- _shared_input_begin_cohort: clears the plain-GPTQ factor caches of the
  subset. The mixin hook now also receives subset_names, because GPTQ only
  clears tasks in the subset.
- _shared_input_task_adopt: adopts the Hessian, then attaches one
  SharedHessianFactorCache per plain-GPTQ leader. The leader's cache was
  cleared when the cohort began, so its first follower creates the cache
  and the rest join it. That matches the old per-call dict without the
  processor holding a reference to cached factors after the pass ends.

Shared-input dedup decides which modules share a Hessian, so the leaders,
telemetry, per-task H/dXXT/quantized weights and factor-cache identity
graph were compared against origin/main on CPU fixtures. GPTQ and GPTAQ
quantization of Qwen2.5-0.5B-Instruct and of a tiny random Mixtral (a
shared-input verified MoE, so expert gate/up share a Hessian) were also
compared on GPU, together with the sorted quant-log rows and dedup
telemetry. All of them are bit-identical.

Two observable differences remain. The generation counter now also advances
when a model has no shared-input plan; no factor cache exists then, and every
cache that is created keeps the same generation as before. The mismatch
warning says "accumulation settings" instead of "capture settings".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium force-pushed the refactor/gptq-shared-input-mixin branch from 0ed0386 to 044903f Compare November 29, 2026 20:43
@Qubitium
Qubitium merged commit 3c5020d into main Nov 29, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/gptq-shared-input-mixin branch November 29, 2026 21:25
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