Skip to content

[BUG] Portable inference paths still narrow intermediates before finite reductions and bias epilogues #4471

Closed

Description

@devin-ai-integration

Describe the bug

At 0b94d79c67, the cases below violate the stated supported contract. The validation scope for each case is explicit; source/dispatch proofs are not device numerical qualification.

ParoQuant CPU ATen child loses the wide accumulator before the outer bias epilogue

Severity: P2 / medium

Contract and impact

A finite final FP16 result must not overflow before a cancelling bias is applied.

A supported CPU FP16 ParoLinear with group_size=32, K=32, N=16 returns inf instead of 65024 when its native CPU packed path is available.

To reproduce / evidence

Evaluation/no-grad CPU FP16 forward, identity rotation, packed code one, zero point zero, scale eight, activation 258 and bias -1024. K=32 and N=16 satisfy ATen geometry; CPU AVX512 branch is BF16-only, so this FP16 route reaches ATen.

Executed in reproduce.py with the exact command recorded in limitations. This invokes the real native CPU int4pack op via the shipped helper, then reproduces the source-traced outer epilogue. Output: out_dtype=None -> product=inf/final=inf; out_dtype=float32 -> product=66048/final=65024; independent FP64 oracle=65024. Standalone excerpt:

import ast
from pathlib import Path
import torch
ROOT=Path(".")
torch.set_num_threads(1)
path=ROOT/'gptqmodel/nn_modules/qlinear/torch_fused.py'
nodes=[n for n in ast.parse(path.read_text()).body if isinstance(n,ast.FunctionDef) and n.name in ('pack_scales_and_zeros','_cpu_int4pack_mm')]
scope={'torch':torch}
exec(compile(ast.fix_missing_locations(ast.Module(body=nodes,type_ignores=[])),str(path),'exec'),scope)
packed=torch.ops.aten._convert_weight_to_int4pack_for_cpu(torch.ones((16,32),dtype=torch.int32),1)
metadata=scope['pack_scales_and_zeros'](torch.full((1,16),8.,dtype=torch.float16),torch.full((1,16),64.,dtype=torch.float16))
x=torch.full((1,32),258.,dtype=torch.float16); bias=torch.full((16,),-1024.,dtype=torch.float16)
oracle=(x.double()@torch.full((32,16),8.,dtype=torch.float64)+bias.double()).half()
assert oracle[0,0].item()==65024.
for dtype in (None,torch.float32):
    p=scope['_cpu_int4pack_mm'](x,packed,32,metadata,out_dtype=dtype)
    actual=(p.float()+bias.float()).half()
    print('Paro ATen out_dtype',dtype,'product',p[0,0].item(),'final',actual[0,0].item(),'FP64 oracle',oracle[0,0].item())
    assert bool(torch.isfinite(actual).all()) == (dtype is not None)

Observed and expected behavior

Observed inf despite representable 65024 output. Expected retain wide product across the parent/child boundary and cast once after outer bias.

Public source and history

def _forward_cpu_aten(self, x_flat: torch.Tensor) -> Optional[torch.Tensor]:
"""Use ATen's native CPU int4pack GEMM for FP16/BF16 activations."""
if (
x_flat.device.type != "cpu"
or self.training
or x_flat.requires_grad
or x_flat.dtype not in (torch.float16, torch.bfloat16)
or self.bits != 4
or getattr(self, "requested_group_size", self.group_size) == -1
or self.group_size not in (32, 64, 128, 256)
):
return None
from .torch_aten_kernel import _has_local_int4pack_cpu_ops
if not _has_local_int4pack_cpu_ops():
return None
key = (
tensor_cache_key(self.qweight),
tensor_cache_key(self.qzeros),
tensor_cache_key(self.scales),
self.bits,
self.group_size,
self.in_features,
self.out_features,
x_flat.dtype,
)
if self._cpu_aten_failed_key == key:
return None
layer = self._cpu_aten_layer
if layer is None or self._cpu_aten_key != key:
from .torch_aten_kernel_awq import TorchAtenAwqLinear
ok, _ = TorchAtenAwqLinear.cached_validate_once()
if not ok:
return None
try:
layer = TorchAtenAwqLinear(
bits=self.bits,
group_size=self.group_size,
sym=self.sym,
desc_act=self.desc_act,
in_features=self.in_features,
out_features=self.out_features,
bias=False,
pack_dtype=self.pack_dtype,
adapter=None,
register_buffers=False,
name=f"{self.name}.cpu_aten",
backend=BACKEND.AWQ_TORCH_ATEN,
)
layer.qweight = self.qweight
layer.qzeros = self.qzeros
layer.scales = self.scales
layer.bias = None
layer.eval()
layer.transform_cpu(dtype=x_flat.dtype)
except Exception as exc:
if not self._cpu_aten_warning_logged:
log.warning(
"ParoQuant ATen CPU int4pack unavailable for `%s`; using dense fallback: %s",
self.name,
exc,
)
self._cpu_aten_warning_logged = True
self._cpu_aten_layer = None
self._cpu_aten_key = None
self._cpu_aten_failed_key = key
return None
self._cpu_aten_layer = layer
self._cpu_aten_key = key
self._cpu_aten_failed_key = None
try:
out = layer._fused_op_forward(x_flat)
except Exception as exc:
if not self._cpu_aten_warning_logged:
log.warning(
"ParoQuant ATen CPU int4pack failed for `%s`; using dense fallback: %s",
self.name,
exc,
)
self._cpu_aten_warning_logged = True
self._cpu_aten_layer = None
self._cpu_aten_key = None
self._cpu_aten_failed_key = key
return None
if self.bias is not None:
# Accumulate the bias in FP32 before the visible dtype cast. ATen
# returns a BF16/FP16 result, and a same-dtype add would round both
# the bias and the sum again.
out = (out.float() + self.bias.float()).to(dtype=x_flat.dtype)
if out.dtype != x_flat.dtype:
out = out.to(dtype=x_flat.dtype)
admits CPU FP16 eval/group32, builds bias=False child, explicitly clears child.bias, calls _fused_op_forward, then adds the parent bias after return;
def _fused_op_forward(self, x):
self._refresh_fused_state()
if x.device.type != "cpu":
raise NotImplementedError
if not self._fused_input_dtype(x):
raise RuntimeError(
f"{self.__class__.__name__} fused ATen int4pack requires activation dtype "
f"{self.scales_and_zeros.dtype}, got {x.dtype}."
)
return _cpu_int4pack_mm(
x,
self.qweight,
self.group_size,
self.scales_and_zeros,
out_dtype=(
torch.float32
if self.bias is not None and x.dtype in (torch.float16, torch.bfloat16)
else None
),
)
only asks for FP32 output if its own bias exists;
def _cpu_int4pack_mm(x, qweight, group_size, scales_and_zeros, out_dtype=None):
"""Run int4pack with FP32 operands without expanding stored weights.
BF16 inputs, and FP16 inputs whose caller requests an FP32 product,
accumulate in FP32. ``out_dtype`` lets a biased layer keep that product
until the bias has been added, so the epilogue rounds once instead of
overflowing or rounding the pre-bias sum.
Inductor fuses the operand casts into a Pointwise node and then cannot
lower ``aten::_weight_int4pack_mm_for_cpu`` on it (#4068). Disabling
tracing here keeps the op and its casts eager inside an otherwise
compiled model, which is a deliberate graph break rather than a silent
fallback to a different kernel.
"""
otherwise narrows native product to x.dtype. https://github.com/ModelCloud/GPTQModel/blob/0b94d79c670709113d27a96ac5bc9ea920363d77/gptqmodel/nn_modules/qlinear/paroquant.py#L587-L617 selects CPU ATen before dense fallback for this FP16 case (the AVX512 branch is BF16-only).

6c4d3b6, 2026-10-22T10:48:18Z, #3412 introduced this child/outer-epilogue split, confirmed by blame. Later a53b53e (#3893) fixed dense and CUDA bias cancellation but did not touch CPU ATen.

Existing reports

Uncovered CPU variant of closed #3866 (dense group16 bias-cancellation report, whose body assumed CPU ATen safe) and related #3977. #3893 fixes dense/CUDA only; #4001 gives biased standalone ATen a wide result but ParoQuant deliberately uses a biasless child. No exact CPU-child follow-up found in performed open/closed searches; do not republish this as an unrelated newly recurring bug.

Software / device info and validation limits

Linux x86_64, CPython 3.14.6 free-threading build, Torch 2.15.0+cpu, CUDA unavailable. No native CUDA/ROCm/Metal kernel execution, full-model runs, UI tests, large downloads or benchmarks. Real native CPU helper plus independent FP64 oracle executed. Full ParoLinear/child construction/packing was source-traced rather than imported; actual packed operand is valid native geometry K=32,N=16. No CUDA or AVX512-BF16 arithmetic claim.

MLX QQQ narrows scaled output through FP16 before bias and visible dtype conversion

Severity: HIGH: finite supported outputs can become infinity

Contract and impact

Keep scaled reduction and bias wide until exactly one visible output cast; do not destroy BF16 range or overflow a finite final FP16 linear+bias result.

Two manifestations share one epilogue ownership root: (a) finite BF16 output65536 becomes inf through FP16; (b) FP16 pre-bias67200 plus bias-2000 should produce finite65216 but overflows before cancellation. These are two separate invariants/chains, not a third independent bug.

To reproduce / evidence

Supported whole-row QQQ INT4 holder with K=N=64. (a) BF16 activations1024, effective represented weight1 => dot65536. BF16 runtime acceptance is explicit in current tests although holder checkpoint metadata advertises FP16. (b) FP16 activations12.5, signedQ4code7, channel_scale.75 => effective weight84, dot67200, bias-2000 => final65200. M1 uses fused finalizer; M2+ uses Python epilogue.

Executed portable CPU IEEE/Torch proof, NOT MLX forward. The inline reproduction independently constructs the activation quantizer and a FP64 linear oracle. Minimal cast/order proof:

import torch
torch.set_num_threads(1)
for dtype, x, signed_code, channel, bias in [
    (torch.bfloat16,1024.,1,.0625,0.),
    (torch.float16,12.5,7,.75,-2000.),
]:
    a = torch.full((2,64), x, dtype=dtype)
    s = a.float().abs().amax(-1,keepdim=True)/127
    q = (a.float()/s).round().clamp(-128,127)
    raw = q @ torch.full((64,64), signed_code*16., dtype=torch.float32)
    scaled = raw*s*channel
    exact = a.double() @ torch.full((64,64),signed_code*16*channel,dtype=torch.float64)+bias
    expected = exact.to(dtype)
    narrowed = (scaled.half().float()+bias).to(dtype)
    print(float(scaled[0,0]),float(exact[0,0]),float(expected[0,0]),bool(torch.isinf(narrowed).all()))

Executed output: 65536.0 65536.0 65536.0 True; 67200.0 65200.0 65216.0 True. Supported MLX fixture mapping: N=K=64, group_size=64 (=whole row), bits=4, uint32 words 0x99999999 / 0xffffffff, affine scales=16, affine biases=-128; channel scales=.0625 / .75; optional output bias=-2000. These are the shipped QQQ holder's whole-row representation. Run M=1 and M=2 on Apple to cover both finalizers; this audit did not run that device test.

Observed and expected behavior

Independent CPU oracle: BF16 expected65536 finite versus premature-FP16 inf; FP16 bias-cancellation expected65200 exact=>65216 visible versus premature-FP16 inf. Shipped source encodes that cast order in both row bands. No actual MLX output was obtained. Existing tests encode historical FP16 intermediate as their expected policy, so their passing would not refute the mathematical range/order defect.

Public source and history

Fused half conversion before bias/store:

def _finalize_kernel(output_dtype):
"""Apply QQQ output scales, FP16 rounding, bias, and dtype storage."""
output_types = {
mx.float16: ("fp16", "half"),
mx.bfloat16: ("bf16", "bfloat16_t"),
mx.float32: ("fp32", "float"),
}
try:
output_suffix, output_type = output_types[output_dtype]
except KeyError as exc:
raise ValueError(f"Unsupported QQQ activation dtype: {output_dtype}") from exc
return mx.fast.metal_kernel(
name=f"gptqmodel_qqq_finalize_{output_suffix}",
input_names=["raw", "input_scale", "channel_scale", "bias"],
output_names=["output"],
source="""
uint index = thread_position_in_grid.x;
uint column = index % N;
uint row = index / N;
half value = half(
float(raw[index]) * input_scale[row] * channel_scale[column]
);
if (HAS_BIAS) value = half(value + half(bias[column]));
output[index] = OUTPUT_TYPE(value);
""".replace("OUTPUT_TYPE", output_type),
)
. Multi-row output.astype(mx.float16) before bias and original_dtype:
def __call__(self, x):
original_dtype = x.dtype
if x.size == 0:
return mx.zeros((*x.shape[:-1], self.linear.weight.shape[0]), dtype=original_dtype)
x = x.astype(_quantization_dtype(x.dtype))
quantized, input_scale = _dynamic_quant(x)
raw = self.linear(quantized)
rows = x.size // x.shape[-1]
if rows == 1:
output_dims = self.linear.weight.shape[0]
return _finalize_kernel(original_dtype)(
inputs=[
raw,
input_scale,
self.channel_scale,
self.bias if "bias" in self else self.zero_bias[0],
],
template=[("N", output_dims), ("HAS_BIAS", "bias" in self)],
grid=(rows * output_dims, 1, 1),
threadgroup=(256, 1, 1),
output_shapes=[(*x.shape[:-1], output_dims)],
output_dtypes=[original_dtype],
)[0]
output = raw * input_scale * self.channel_scale
output = output.astype(mx.float16)
if "bias" in self:
output = output + self.bias
return output.astype(original_dtype)
. BF16 input repair only:
def _quantization_dtype(dtype):
"""Operand dtype for the dynamic quantizer.
The Metal quantizer reads each element as FP32, so it does not need an FP16
operand. Narrowing BF16 to FP16 first turns any ``|x| > 65504`` into inf,
which then makes the row scale inf and the output NaN. Keep BF16 wide and
preserve the historical FP16 operand for every other input dtype.
"""
return dtype if dtype == mx.bfloat16 else mx.float16
. Supported holder dimensions and exact signed-nibble*16 representation:
class QQQMlxQuantLinear(_MlxLinearContract, QQQTorchLinear):
"""QQQ holder for exact INT8 weights and dynamic input quantization on MLX."""
SUPPORTS_BACKENDS = [BACKEND.MLX]
SUPPORTS_METHODS = [METHOD.QQQ]
SUPPORTS_FORMATS = {FORMAT.QQQ: 0}
SUPPORTS_BITS = [4]
SUPPORTS_GROUP_SIZE = [-1, 128]
SUPPORTS_DESC_ACT = [True, False]
SUPPORTS_SYM = [True]
SUPPORTS_SHARDS = True
SUPPORTS_TRAINING = False
SUPPORTS_AUTO_PADDING = False
SUPPORTS_IN_FEATURES_DIVISIBLE_BY = [64]
SUPPORTS_OUT_FEATURES_DIVISIBLE_BY = [64]
SUPPORTS_DEVICES = [DEVICE.MPS]
SUPPORTS_PLATFORM = [PLATFORM.DARWIN]
SUPPORTS_PACK_DTYPES = [torch.int32]
SUPPORTS_ADAPTERS = []
SUPPORTS_DTYPES = [torch.float16]
REQUIRES_FORMAT_V2 = False
SOURCE_LINEAR = QQQTorchLinear
@classmethod
def source_compatible(cls, module):
if not isinstance(module, QQQTorchLinear):
return False
ok, _ = cls._validate_source(
bits=module.bits, group_size=-1 if module.group_size == module.in_features else module.group_size,
desc_act=module.desc_act, sym=module.sym,
in_features=module.in_features, out_features=module.out_features,
pack_dtype=torch.int32, dtype=torch.float16,
device=DEVICE.MPS, adapter=module.adapter,
)
return ok and cls._source_layout_compatible(module)
@staticmethod
def _source_layout_compatible(module):
return (tuple(module.B.shape) == (module.in_features // 16, module.out_features * 2)
and tuple(module.s_channel.shape) == (1, module.out_features)
and tuple(module.s_group.shape) ==
((module.in_features // module.group_size, module.out_features)
if module.group_size != module.in_features else (0,)))
@classmethod
def mlx_params(cls, module):
# Whole-row QQQ codes are signed nibbles scaled by 16. Grouped QQQ
# rounds each group's scaled nibbles to INT8 and needs the 8-bit path.
bits = 4 if module.group_size == module.in_features else 8
return {"group_size": 64 if module.in_features == 64 else 128, "bits": bits, "mode": "affine"}
@classmethod
def pack_source(cls, module):
import numpy as np
if not cls.source_compatible(module):
raise ValueError("QQQ layer cannot be transferred to MLX")
if module.group_size == module.in_features:
# XOR the sign bit so MLX's unsigned affine codes decode to
# QQQ's signed two's-complement nibbles without rounding.
codes = module._unpack_weight_codes().to("cpu", torch.uint8).numpy().T
codes = np.ascontiguousarray(codes ^ np.uint8(8))
lanes = codes.reshape(module.out_features, module.in_features // 8, 8)
packed = np.zeros((module.out_features, module.in_features // 8), dtype=np.uint32)
for lane in range(8):
packed |= lanes[:, :, lane].astype(np.uint32) << (4 * lane)
group_size = cls.mlx_params(module)["group_size"]
shape = (module.out_features, module.in_features // group_size)
scales = np.full(shape, 16, dtype=np.float32)
biases = np.full(shape, -128, dtype=np.float32)
return packed, scales, biases, cls.mlx_params(module)
weight, _ = module._dequantize_weight_for_torch()
weight = weight.detach().to("cpu", torch.int16).numpy().T
if np.any((weight < -128) | (weight > 127)):
raise ValueError("QQQ weights exceed the signed INT8 range")
codes = (weight + 128).astype(np.uint8)
packed = np.ascontiguousarray(codes).view(np.uint32).reshape(module.out_features, -1)
group_size = cls.mlx_params(module)["group_size"]
groups = module.in_features // group_size
scales = np.ones((module.out_features, groups), dtype=np.float32)
biases = np.full_like(scales, -128)
return packed, scales, biases, cls.mlx_params(module)
. BF16 runtime tests explicitly parametrize activations:
mx.eval(quantized, scales)
np.testing.assert_array_equal(np.asarray(scales), expected_scales.numpy())
np.testing.assert_array_equal(np.asarray(quantized).astype(np.int8), expected_codes.numpy())
@pytest.mark.parametrize("group_size", [-1, 128])
@pytest.mark.parametrize("rows", [1, 16], ids=["decode", "prefill"])
@pytest.mark.parametrize("dtype", [mx.float16, mx.bfloat16], ids=["fp16", "bf16"])
def test_qqq_qwen_down_wide_reduction_matches_previous_and_torch(
group_size, rows, dtype, record_property,
):
from gptqmodel.nn_modules.qlinear.mlx_qqq import _dynamic_quant
layer, row_weight, channel_scale = _qqq_qwen_down_fixture(group_size)
positions = np.arange(17408, dtype=np.float32)
source = np.stack([
np.sin(positions * (0.013 + row * 0.0001)) * 0.05
+ np.cos(positions * (0.007 + row * 0.0001)) * 0.025
for row in range(rows)
])
x = mx.array(source).astype(dtype)
half = x.astype(mx.float16)
quantized, input_scale = _dynamic_quant(half)
previous_quantized, previous_scale = _qqq_dynamic_quant_256(half)
internal = layer.linear(quantized) * input_scale * layer.channel_scale
previous = (
layer.linear(previous_quantized) * previous_scale * layer.channel_scale
).astype(mx.float16).astype(dtype)
actual = layer(x)
mx.eval(
quantized, input_scale, previous_quantized, previous_scale,
internal, previous, actual,
)
torch_input = torch.from_numpy(np.asarray(half)).double()
torch_scale = (torch_input.float().abs().amax(dim=-1, keepdim=True) / 127).double()
torch_codes = (torch_input / torch_scale).round().clamp(-128, 127)
raw_row = (
torch_codes @ torch.from_numpy(row_weight.astype(np.float64))
)[:, None] * torch_scale
raw = raw_row.numpy() * channel_scale.astype(np.float64)
rounded = torch.from_numpy(raw).to(torch.float16)
if dtype == mx.bfloat16:
rounded = rounded.to(torch.bfloat16)
rounded = rounded.float().numpy()
visible = np.asarray(actual.astype(mx.float32))
previous_visible = np.asarray(previous.astype(mx.float32))
record_property(
"max_abs_internal_fp32_vs_fp64",
float(np.max(np.abs(np.asarray(internal) - raw))),
)
record_property(
"max_abs_visible_vs_rounded_torch",
float(np.max(np.abs(visible - rounded))),
)
record_property(
"changed_vs_previous_256_threads",
.

Original wrapper bf2de46 (bf2de46, #3134) already casts multi-row result toFP16 before bias. badeed3 (badeed3, #3233) copies this policy into fused finalization. c45c1b0 (#4264) fixes input narrowing only; not a reintroduction of an output fix.

Existing reports

#4221 item3 and merged #4264 address MLX BF16 INPUT narrowing; the remaining OUTPUT stage is separate. #3977 and #4001 cover related non-MLX QQQ/bias paths; #4001 does not touch mlx_qqq.py and is not an effective MLX output fix. All-state QQQ/MLX/bias/overflow searches found no exact residual MLX epilogue duplicate; search is not exhaustive.

Software / device info and validation limits

Static proof of both narrowing sites plus portable Torch/IEEE arithmetic, not measured MLX/Metal numerics or checkpoint-through-forward validation. FP16 case avoids the BF16 metadata ambiguity. Apple M1/M2 row-band reproduction and independent packed-weight oracle remain acceptance gates.

Bias-free FP8 fallback narrows decoded weights before a finite cancelling reduction

Severity: P2

Contract and impact

Temporary decode must preserve the stored weight range until the reduction and final output cast; zero bias and absent bias must have the same arithmetic contract.

Finite FP8 checkpoint weights and finite FP16 activations return NaN for an exactly zero dot product. Adding an identically zero bias changes the same computation to the correct result.

To reproduce / evidence

TorchFP8Linear(bias=False), row-scaled FP8 payload decoding to two values 65536, FP16 activation [1,-1], CPU/dequantized fallback. No malformed checkpoint or target-device mock is needed.

import torch; from gptqmodel.nn_modules.qlinear.fp8 import TorchFP8Linear; s=torch.nn.Linear(2,1,bias=False,dtype=torch.float32); s.weight.data.fill_(65536.); m=TorchFP8Linear(bits=8,group_size=-1,sym=True,desc_act=False,in_features=2,out_features=1,bias=False); m.pack_original(s,None,None); x=torch.tensor([[1.,-1.]],dtype=torch.float16); decoded=m.weight.float()/m.weight_scale_inv.float().view(-1,1); expected=(x.double()@decoded.double().T).half(); print(m(x),expected). Observed nan vs zero. Repeat, self state_dict reload under inference_mode, and m.to(dtype=bfloat16) preserve the packed bytes and the failure. Control: bias=True with bias zero produces zero in all four states.

Observed and expected behavior

Actual tensor([[nan]], dtype=torch.float16); independent FP64 dot over exact FP32-decoded stored payload gives tensor([[0.]], dtype=torch.float16). Packed bytes unchanged.

Public source and history

def _forward_dequant_matmul(
self, x_flat: torch.Tensor, bias: torch.Tensor | None = None
) -> torch.Tensor:
if (
bias is not None
and x_flat.dtype in (torch.float16, torch.bfloat16)
and (
x_flat.device.type != "cuda"
or bias.dtype != x_flat.dtype
or autocast_active(x_flat.device.type)
)
):
# The bias and the reduction can cancel outside the activation
# range. Decode into temporary FP32 storage and round only after
# their sum; autocast must not narrow this matmul again.
with torch.autocast(device_type=x_flat.device.type, enabled=False):
weight = self.dequantize_weight(device=x_flat.device, dtype=torch.float32)
output = torch.matmul(x_flat.float(), weight)
return (output + bias.to(device=x_flat.device, dtype=torch.float32)).to(x_flat.dtype)
weight = self.dequantize_weight(device=x_flat.device, dtype=x_flat.dtype)
return matmul_fp32_reduce(x_flat, weight, bias=bias)
guards the wide decode behind bias is not None; otherwise weight is decoded to x.dtype before matmul_fp32_reduce can widen it.

Present in the original file addition 96ff08b #2456 (2026-03-22, before the audit window). The same early target-dtype decode persists through 97eac85 #3520 and 671ba82 #3737. The latter adds a bias-dependent wide branch but never corrects this bias-free case. Independently executed full historical modules on real CPU tensors: bias=False is NaN versus oracle0 at 96ff08b,97eac852,671ba828 and HEAD. Zero-bias control is NaN at the first two and0 at 671ba82/HEAD. Current dependencies were shared across replays.

Existing reports

Open/closed FP8 range/bias searches found related #3976 and #4003 scale/serialization reports, but no exact bias-free fallback report. #3863 shows the analogous block-float contract and its separate fix; do not call this its recurrence. Duplicate-search scope was the bounded public all-state queries and the cited issue threads; absence is not proof no report exists.

Software / device info and validation limits

Real shipped CPU arithmetic on Torch 2.15.0+cpu; explicit independent decoded-payload/FP64 oracle. GPU fallback is source-reachable but not executed. No claim about the separate scaled-mm path. Historical whole-module CPU replays were also performed in this session; these are not old GPU-environment reconstructions.

Local Mamba incremental state update overflows FP16 temporaries while equivalent prefill stays finite

Severity: P2

Contract and impact

For supported half activations with FP32 recurrent state, decode and prefill must implement the same selective recurrence without narrowing its products/readout before accumulation; finite representable final values must not become infinity solely through an internal half intermediate.

Incremental execution returns infinity and contaminates the FP32 recurrent state with infinity for a one-element recurrence whose exact state is65536 and visible FP16 output is32768. The unchanged shipped chunk-scan/prefill path returns both finite values for exactly the same data. Subsequent decode consumes the contaminated state; actual model incidence/likelihood was not measured.

To reproduce / evidence

state=zeros(1,1,1,float32), x=[[32768]] float16, dt=[[1]] float16, A=zeros(1,1,float32), B=[[2]] float16, C=[[0.5]] float16. No special indices, bias, D, gate or softplus required.

Independently executed command: python reproduce.py. Both shipped Python functions execute unchanged on actual CPU PyTorch/einops. Expected state and output come from independent FP64 scalar arithmetic, not the sibling path. Complete script (adapt ROOT/fixture paths to your checkout):

import importlib.util
import pathlib
import sys
import types

import torch

path = pathlib.Path('./gptqmodel/hf_kernels/mamba_ssm/ops/triton/selective_state_update.py')
spec = importlib.util.spec_from_file_location('local_state_update', path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)

state = torch.zeros(1, 1, 1, dtype=torch.float32)
x = torch.tensor([[32768.]], dtype=torch.float16)
dt = torch.ones_like(x)
A = torch.zeros(1, 1, dtype=torch.float32)
B = torch.tensor([[2.]], dtype=torch.float16)
C = torch.tensor([[.5]], dtype=torch.float16)
out = mod.selective_state_update(state, x, dt, A, B, C)
expected_state = x.double() * dt.double() * B.double()
expected_out = (expected_state * C.double()).to(x.dtype)
print({'out':out.item(), 'expected_out':expected_out.item(), 'state':state.item(), 'expected_state':expected_state.item()})

root = pathlib.Path('./gptqmodel')
for name, directory in [('gptqmodel', root), ('gptqmodel.hf_kernels', root/'hf_kernels')]:
    package = types.ModuleType(name)
    package.__path__ = [str(directory)]
    sys.modules[name] = package
spec = importlib.util.spec_from_file_location('local_chunk_scan', path.with_name('ssd_combined.py'))
scan = importlib.util.module_from_spec(spec)
spec.loader.exec_module(scan)
prefill, final_state = scan.mamba_chunk_scan_combined(
    x.reshape(1, 1, 1, 1), dt.reshape(1, 1, 1), A.reshape(1),
    B.reshape(1, 1, 1, 1), C.reshape(1, 1, 1, 1), chunk_size=1,
    return_final_states=True,
)
print({'prefill_out':prefill.item(), 'prefill_state':final_state.item(), 'incremental_out':out.item(), 'incremental_state':state.item()})
assert prefill.item() == expected_out.item() == 32768
assert final_state.item() == expected_state.item() == 65536
assert torch.isinf(out).all() and torch.isinf(state).all()

Observed and expected behavior

Observed {'out': inf, 'expected_out': 32768.0, 'state': inf, 'expected_state': 65536.0}; shipped prefill comparison {'prefill_out':32768.0,'prefill_state':65536.0,'incremental_out':inf,'incremental_state':inf}. Expected finite FP32 state=65536 and returned FP16 output=32768 in both lifecycle phases.

Public source and history

batch, nheads, dim, dstate = selected_state.shape
if dt_bias is not None:
dt = dt + dt_bias
dt = F.softplus(dt) if dt_softplus else dt
if x.shape != (batch, nheads, dim):
raise AssertionError("x shape mismatch for selective_state_update")
if dt.shape != x.shape:
raise AssertionError("dt shape mismatch for selective_state_update")
if A.shape != (nheads, dim, dstate):
raise AssertionError("A shape mismatch for selective_state_update")
ngroups = B.shape[1]
if nheads % ngroups != 0:
raise AssertionError("nheads must be divisible by ngroups")
if B.shape != (batch, ngroups, dstate) or C.shape != B.shape:
raise AssertionError("B/C shape mismatch for selective_state_update")
if D is not None and D.shape != (nheads, dim):
raise AssertionError("D shape mismatch for selective_state_update")
if z is not None and z.shape != x.shape:
raise AssertionError("z shape mismatch for selective_state_update")
dA = torch.exp(rearrange(dt, "b h d -> b h d 1") * A)
B = repeat(B, "b g n -> b (g h) n", h=nheads // ngroups)
C = repeat(C, "b g n -> b (g h) n", h=nheads // ngroups)
dB = rearrange(dt, "b h d -> b h d 1") * rearrange(B, "b h n -> b h 1 n")
updated_state = selected_state * dA + dB * rearrange(x, "b h d -> b h d 1")
if state_index is None:
state.copy_(updated_state)
else:
state.index_copy_(0, state_index, updated_state)
out = torch.einsum("bhdn,bhn->bhd", updated_state.to(C.dtype), C)
if D is not None:
out += (x * D).to(out.dtype)
out = (out if z is None else out * F.silu(z)).to(x.dtype)
: dt/B/x remain half, dB*x overflows before addition to FP32 state at 75-76; updated_state is narrowed to C.dtype again at 83. Contrast FP32 work/state/B/C handling in
state_dtype = torch.float32 if x.dtype in (torch.float16, torch.bfloat16) else x.dtype
state = (
initial_states.to(dtype=state_dtype).clone()
if initial_states is not None
else torch.zeros(batch, nheads, headdim, dstate, device=x.device, dtype=state_dtype)
)
A_expanded = _expand_A(A.to(dtype=state_dtype), nheads, headdim, dstate)
dt = _apply_dt_limit(dt, dt_bias=dt_bias, dt_softplus=dt_softplus, dt_limit=dt_limit)
D_work = None if D is None else (D.view(nheads, 1) if D.dim() == 1 else D).to(dtype=state_dtype, device=x.device)
outputs = []
for idx in range(seqlen):
if seq_idx is not None and idx > 0:
reset_mask = seq_idx[:, idx] != seq_idx[:, idx - 1]
if reset_mask.any():
state[reset_mask] = 0
B_t = _repeat_groups(B[:, idx].to(dtype=state_dtype), nheads).unsqueeze(2)
C_t = _repeat_groups(C[:, idx].to(dtype=state_dtype), nheads)
x_t = x[:, idx].to(dtype=state_dtype)
dt_t = dt[:, idx]
if dt_t.dim() == 2:
dt_factor = dt_t.unsqueeze(-1).unsqueeze(-1)
else:
dt_factor = dt_t.unsqueeze(-1)
dA = torch.exp(dt_factor * A_expanded)
state = state * dA + (dt_factor * B_t * x_t.unsqueeze(-1))
out_t = (state.to(C_t.dtype) * C_t.unsqueeze(2)).sum(dim=-1)
if D_work is not None:
out_t = out_t + x_t * D_work.unsqueeze(0)
if z is not None:
out_t = out_t * F.silu(z[:, idx].to(dtype=out_t.dtype))
outputs.append(out_t.to(dtype=x.dtype))
out = torch.stack(outputs, dim=1)
return (out, state) if return_final_states else out
def mamba_split_conv1d_scan_combined(
. Local exports are exposed by mamba_ssm/init.py; package hub-kernel fallback resolves gptqmodel.hf_kernels.<kernel_name> in
def _resolve_local_kernel_module(kernel_name):
module_name = kernel_name.replace("-", "_")
namespaced_module = f"gptqmodel.hf_kernels.{module_name}"
if (project_root / "gptqmodel" / "hf_kernels" / module_name / "__init__.py").exists() or (
project_root / "gptqmodel" / "hf_kernels" / f"{module_name}.py"
).exists():
return importlib.import_module(namespaced_module)
package_path = project_root / module_name / "__init__.py"
module_path = project_root / f"{module_name}.py"
if not package_path.exists() and not module_path.exists():
return None
return importlib.import_module(module_name)
def _lazy_load_kernel_with_local_causal_conv1d(kernel_name, mapping=hub_kernels._KERNEL_MODULE_MAPPING):
local_kernel = _resolve_local_kernel_module(kernel_name)
if local_kernel is not None:
mapping[kernel_name] = local_kernel
return local_kernel
return original_lazy_load_kernel(kernel_name, mapping)
.

6ed955c (PR #2783, 2026-04-20): initial local Mamba port contains these products/readout. Path-scoped first-parent history shows no later change to selective_state_update.py, hence no arithmetic fix/reintroduction in the requested window. The sibling chunk-scan file later changed its causal-convolution import at aaa7411 (#2864). This is an old latent bug, not a demonstrated recurrence.

Existing reports

Public OPEN+CLOSED searches selective_state_update, mamba precision and selective state overflow returned no matching issues. No exact retrieved duplicate. Existing tests/test_causal_conv1d_port.py tests only a tiny FP32 chunk-scan case, not half incremental/prefill parity.

Software / device info and validation limits

Portable actual Torch arithmetic, not AST/mocked arithmetic. CPU-only result establishes the Python dtype/recurrence defect; no claim about external mamba_ssm native kernels, CUDA/HIP numerics, full model likelihood or ordinary-model frequency. Inputs satisfy every shipped shape/dtype assertion and FP32-state/half-input execution is explicitly supported by the sibling prefill path.

Model / datasets

The evidence uses tiny synthetic tensors or local fixtures derived from the public tests; no private model or dataset is required. Device execution that remains untested is stated above.

Activity

  1. added
    bug
    on Nov 16, 2026
  2. Qubitium commented on Nov 17, 2026

    @Qubitium
    Collaborator

    Claimed. This issue is now owned by a dedicated worker; a fix PR referencing it will follow.

  3. Qubitium commented on Nov 17, 2026

    @Qubitium
    Collaborator

    Claimed by an AI agent. Will reproduce on CPU where possible, fix, add a focused regression test, and open a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions