Repository navigation
Description
Observed behavior
GPTAQ and FOEM with native correction each run the model's initial calibration forward twice over the same prepared batches. Both passes run before the first decoder block is quantized. The native and quantized streams need their own mutable replay caches as they advance, but they can start from one deterministic captured frontier.
At 078e7f51cfc30ffe8503fad91fd41d293af9ef29, BaseQModel._quantize_with_calibration prepares the main dataset once and hands it to both the native and GPTQ processors. Both processors' dataset verification methods allow first-layer capture. ModuleLooper._loop_impl calls cache_inputs separately for both using the same dataset object, layers, and capture options. Shared preparation, Native verification, GPTQ verification, Capture loop, Per-batch model forward.
On a local two-layer FP16 Llama with 16 variable-length shuffled calibration examples, PyTorch 2.15.0+cpu and one Torch thread, the production path called run_input_capture 32 times for GPTAQ and 32 times for FOEM with alpha=0.25. Reusing a private copy of the first completed capture cut each count to 16 and preserved all 77 packed state-dict tensors and forward logits bit for bit. One measured capture phase, including the replacement clone, took 10.41 → 6.08 ms for GPTAQ and 10.15 → 6.01 ms for FOEM. Those timings are illustrative single-run CPU measurements. The forward counts are deterministic.
#4869 addressed preparing the dataset in a consistent order for both processors. In fact its Llama regression already asserts equal initial layer-0 inputs for the two streams. This report addresses repeating the model-level forward on those prepared batches. Existing alignment regression.
Reproduce
Run from the repository root with PYTHONPATH=. on the CPU build. The check continues into quantization and compares the resulting packed tensors.
import copy
import random
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
import torch
from tokenizers import Tokenizer
from tokenizers.models import WordLevel
from transformers import LlamaConfig, LlamaForCausalLM, PreTrainedTokenizerFast
from gptqmodel import BACKEND, CalibrationConfig, GPTQModel
from gptqmodel.looper.module_looper import ModuleLooper
from gptqmodel.quantization import FOEMConfig, GPTAQConfig, GPTQConfig
from gptqmodel.utils.importer import get_auto_backend_kernel_mapping
torch.set_num_threads(1)
torch.manual_seed(836)
assert get_auto_backend_kernel_mapping()
backend = BACKEND.GPTQ_TORCH
with TemporaryDirectory() as temp:
source = Path(temp)
config = LlamaConfig(
vocab_size=128, hidden_size=64, intermediate_size=128, num_hidden_layers=2,
num_attention_heads=4, num_key_value_heads=4, max_position_embeddings=192,
pad_token_id=0, bos_token_id=1, eos_token_id=2,
)
LlamaForCausalLM(config).half().save_pretrained(source)
tok = Tokenizer(WordLevel({"[PAD]": 0, "[BOS]": 1, "[EOS]": 2, "[UNK]": 3},
unk_token="[UNK]"))
PreTrainedTokenizerFast(
tokenizer_object=tok, pad_token="[PAD]", bos_token="[BOS]",
eos_token="[EOS]", unk_token="[UNK]",
).save_pretrained(source)
ids = [torch.randint(4, 128, (88 + 2 * i,)) for i in range(16)]
rows = [{"input_ids": x, "attention_mask": torch.ones_like(x)} for x in ids]
capture = ModuleLooper.cache_inputs
def run(extra, reuse):
random.seed(645)
qcfg = GPTQConfig(bits=4, group_size=32, device="cpu", offload_to_disk=False, **extra)
model = GPTQModel.load(str(source), quantize_config=qcfg, backend=backend)
forward = model.run_input_capture
forwards = 0
first = None
def count(*args, **kwargs):
nonlocal forwards
forwards += 1
return forward(*args, **kwargs)
def cache(looper, *args, **kwargs):
nonlocal first
batch_source = kwargs["calibration_data"]
if first is not None:
previous_source, previous_cache = first
assert previous_source is batch_source
first = None
return copy.deepcopy(previous_cache)
result = capture(looper, *args, **kwargs)
if reuse:
first = batch_source, result
return result
with (patch.object(model, "run_input_capture", count),
patch.object(ModuleLooper, "cache_inputs", cache)):
model.quantize(CalibrationConfig(dataset=rows, sort="shuffle", min_length=1),
backend=backend)
assert first is None
return forwards, model.model.state_dict()
for extra in ({"gptaq": GPTAQConfig(device="cpu")},
{"foem": FOEMConfig(alpha=0.25, device="cpu")}):
before_count, before = run(extra, False)
after_count, after = run(extra, True)
assert (before_count, after_count) == (32, 16)
assert before.keys() == after.keys()
for name in before:
a = before[name].contiguous().reshape(-1).view(torch.uint8)
b = after[name].contiguous().reshape(-1).view(torch.uint8)
assert torch.equal(a, b), nameSuggested fix
Reuse the completed initial capture when the processors receive the same prepared input object and the model's initial capture is eligible for reuse. Give each processor private replay state because per-layer kwargs and hidden frontiers can change as the native and quantized passes diverge. Preserve a separate capture for any distinct adapter dataset. This first-capture optimization has been checked on deterministic CPU Llama. Other models may use model-specific capture hooks and need qualification before enabling reuse.
if (
previous_processor_is_native
and isinstance(processor, GPTQProcessor)
and processor.calibration_dataset is previous_processor.calibration_dataset
and model_capture_can_be_reused
):
processor.receive_input_cache(copy.deepcopy(previous_processor.inputs_cache.unwrap()))
continueThe snippet illustrates the ownership and eligibility checks. The local A/B tested the private-copy approach and did not change the later native and quantized forwards.
Activity
Qubitium commentedon Nov 20, 2026
Agent claim released:
agent-24e6fcac08d0finished this issue.Pull request: #5890
Reproducing duplicate first-layer capture for GPTAQ/FOEM on CPU and reusing one captured frontier
perf(looper): drop the reused capture local after handoff (#5831)
perf(looper): reuse the native first-layer capture for GPTAQ/FOEM (#5831
refactor(definitions): read raw example inputs from the base capture …