Repository navigation
Description
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.
NF12 short-M multi-block dispatch leaves accepted output tail columns unwritten
Severity: HIGH: silent incorrect/unwritten output on supported shapes; no measured Metal contents
Contract and impact
Every accepted NF12 output column (N divisible by 16) is written exactly once for every supported row band.
At M=1,N=1040 the final 16 columns receive no stores; at M=1,N=2096 the final 48 receive no stores. This is an unwritten-output control-flow defect, not a measured allocator leak or quality/performance claim.
To reproduce / evidence
Valid NF12 packed linear: K divisible by64, N divisible by16; short-M path selects 2 or4 blocks while N/16 is not divisible by that block count. E.g. K64,N1040,M1..12 or K64,N2096,M1..4. Holder/constructor do not reject these widths; M13 is a fully-covered control.
Execution scope: shipped host dispatch with fake arrays and a launch recorder; no Metal execution or emulated kernel arithmetic. Minimal stand-alone HEAD launch proof (run at the pinned checkout, with Torch installed):
import importlib.util, sys
from pathlib import Path
from types import ModuleType
root = Path.cwd()
mx = ModuleType('mlx.core')
mx.float16, mx.bfloat16, mx.float32 = object(), object(), object()
nn = ModuleType('mlx.nn'); nn.Module = type('Module', (), {})
mlx = ModuleType('mlx'); mlx.core, mlx.nn = mx, nn
sys.modules.update({'mlx': mlx, 'mlx.core': mx, 'mlx.nn': nn})
p = root / 'gptqmodel/nn_modules/qlinear/mlx_nf12.py'
spec = importlib.util.spec_from_file_location('audit_nf12', p)
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
class A:
def __init__(self, shape):
self.shape, self.dtype = shape, mx.bfloat16
self.size = shape[0] * shape[1]
def reshape(self, *shape):
return A(shape[0] if len(shape) == 1 and isinstance(shape[0], tuple) else shape)
def factory(rows, blocks, dtype):
def launch(**kw):
n = dict(kw['template'])['N']
written = kw['grid'][1] * 16 * blocks
print(rows, n, blocks, kw['grid'][1], n-written)
return [A(kw['output_shapes'][0])]
return launch
m._rows_kernel = factory
for rows, n in [(1,1040), (1,2096), (13,1040)]:
layer = m.MlxNF12Linear.__new__(m.MlxNF12Linear)
layer.in_features, layer.out_features = 64, n
layer.packed = layer.escapes = layer.exp_base = layer.bias = None
m.MlxNF12Linear.__call__(layer, A((rows,64)))Output: 1 1040 2 32 16; 1 2096 4 32 48; 13 1040 1 65 0. Completeness follows from the separately read generated kernel indexing, not from a fabricated numeric output.
Observed and expected behavior
Independent recorded dispatch: 48 shapes each across M=(1,4,8,12,13,16), N=(512,528,1024,1040,2048,2064,2080,2096). Before #4133:0 undercovered; at #4133:14; at HEAD:14. M1,N1040 selects blocks2/grid_y32=>1024 columns,16 missing; M1,N2096 selects blocks4/grid_y32=>2048,48 missing. Expected all N columns covered. Numerical tail values were not observed.
Public source and history
Acceptance:
GPTQModel/gptqmodel/nn_modules/qlinear/mlx_nf12.py
Lines 461 to 485 in 0b94d79
| """Multiply activations by the packed NF12 weight without dense expansion.""" | |
| def __init__( | |
| self, | |
| *, | |
| in_features, | |
| out_features, | |
| num_escapes=0, | |
| threads=_THREADS, | |
| ): | |
| super().__init__() | |
| in_features = int(in_features) | |
| out_features = int(out_features) | |
| if in_features % 64 or out_features % 16: | |
| raise ValueError("NF12 MLX inference needs in_features % 64 and out_features % 16") | |
| self.in_features = in_features | |
| self.out_features = out_features | |
| self.threads = int(threads) | |
| self.packed = mx.zeros((out_features, in_features * 3 // 2), dtype=mx.uint8) | |
| self.escapes = mx.zeros((max(int(num_escapes), 1), 8), dtype=mx.int16) | |
| self.exp_base = mx.zeros((1,), dtype=mx.uint8) | |
| # A zero bias keeps one fused kernel for biased and unbiased layers. | |
| self.bias = mx.zeros((out_features,), dtype=mx.float32) | |
| # A single row uses the GEMV: it reads the packed bytes once and needs | |
| # no second dispatch, which is the whole cost at that size. |
GPTQModel/gptqmodel/nn_modules/qlinear/mlx_nf12.py
Lines 45 to 52 in 0b94d79
| def _row_blocks(rows, out_features): | |
| """Adjacent 16-column blocks per threadgroup for the dot-product path. | |
| Every output column needs the same activation values, so decoding several | |
| blocks per threadgroup divides the per-step activation loads. The price is | |
| ``rows * blocks`` accumulator pairs per thread, so the wide token counts | |
| keep fewer blocks and stay out of a register spill, and a short output grid | |
| keeps one block so the GPU still has a full wave of threadgroups. |
GPTQModel/gptqmodel/nn_modules/qlinear/mlx_nf12.py
Lines 558 to 576 in 0b94d79
| save. | |
| """ | |
| threads = 128 | |
| blocks = _row_blocks(rows, self.out_features) | |
| return _rows_kernel(rows, blocks, x.dtype)( | |
| inputs=[x.reshape(rows, self.in_features), self.packed, self.escapes, | |
| self.exp_base, self.bias], | |
| template=[ | |
| ("K", self.in_features), ("N", self.out_features), | |
| ("ROWS", rows), ("SA_ROW", self.in_features // 64), | |
| # Words per 16-row block: 16 rows of 1.5 bytes per weight. | |
| ("SA_BYTES", self.in_features * 6), | |
| ("BLOCKS", blocks), | |
| ], | |
| grid=(threads, self.out_features // (16 * blocks), 1), | |
| threadgroup=(threads, 1, 1), | |
| output_shapes=[(rows, self.out_features)], | |
| output_dtypes=[x.dtype], | |
| )[0] |
GPTQModel/gptqmodel/nn_modules/qlinear/mlx_nf12.py
Lines 278 to 399 in 0b94d79
| def _rows_body(rows, blocks): | |
| """Unrolled slot decode plus one FMA per token row, over ``blocks`` columns. | |
| The decode builds each BF16 word from its meta nibble and low byte with the | |
| fewest integer ops that fit: the exponent byte is shifted straight to the | |
| top of the word, the low byte is masked into place, and the loop prefetches | |
| the next super-atom so the load latency overlaps the current step's ALU. | |
| A threadgroup owns ``blocks`` adjacent 16-column blocks and decodes them | |
| from the same activation values, because ``x`` does not depend on the output | |
| column. That is what makes the wide token counts fast: at eight rows the | |
| per-step activation loads outnumber the packed loads, and sharing them | |
| across blocks removes most of that traffic without touching the weight | |
| stream. | |
| """ | |
| def slots(escaped, pad, block): | |
| out = [] | |
| for s in range(8): | |
| ch, rh, p = s >> 2, (s >> 1) & 1, s & 1 | |
| low = f"{'low0' if s < 4 else 'low1'}_{block}" | |
| byte = s & 3 | |
| k = f"k_j + {8 * ch + p}u" | |
| # (byte << 16) written as a masked shift of the source word. | |
| shift = {0: "<< 16u", 1: "<< 8u", 2: "", 3: ">> 8u"}[byte] | |
| if escaped: | |
| # The escape table is indexed by the group's first low word. | |
| bits = f"uint(uint16_t(escapes[low0_{block} * 8u + {s}u])) << 16u" | |
| else: | |
| meta = f"m{s >> 1}" | |
| high = (f"({meta} & 0x87u)" if p == 0 | |
| else f"((({meta} << 1u) & 0x80u) | (({meta} >> 3u) & 0x07u))") | |
| bits = ( | |
| f"((({high} + exp_base_value) << 24u)" | |
| f" | (({low} {shift}) & 0x00FF0000u))" | |
| ) | |
| out.append(f"{pad}weight = as_type<float>({bits});") | |
| for r in range(rows): | |
| out.append( | |
| f"{pad}sum_{block}_{r}_{rh} = metal::fma(" | |
| f"float(x[{r} * K + {k}]), weight, sum_{block}_{r}_{rh});" | |
| ) | |
| return "\n".join(out) | |
| decls = "\n".join( | |
| f" float sum_{b}_{r}_{rh} = 0.0f;" | |
| for b in range(blocks) for r in range(rows) for rh in (0, 1) | |
| ) | |
| pre = "" | |
| prefetch = "" | |
| advance = "" | |
| for b in range(blocks): | |
| off = "" if b == 0 else f" + {b}u * SA_BYTES" | |
| pre += f""" | |
| uint meta_{b} = base[meta_word{off}]; | |
| uint low0_{b} = base[low_word{off}]; | |
| uint low1_{b} = base[low_word + 1u{off}];""" | |
| prefetch += f""" | |
| uint next_meta_{b} = next[meta_word{off}]; | |
| uint next_low0_{b} = next[low_word{off}]; | |
| uint next_low1_{b} = next[low_word + 1u{off}];""" | |
| advance += f""" | |
| meta_{b} = next_meta_{b}; | |
| low0_{b} = next_low0_{b}; | |
| low1_{b} = next_low1_{b};""" | |
| decode = "" | |
| for b in range(blocks): | |
| decode += f""" | |
| {{ | |
| uint meta = meta_{b}; | |
| // A group whose four meta bytes are all zero carries its | |
| // eight BF16 words in the escape table. | |
| if (meta == 0u) {{ | |
| {slots(True, " ", b)} | |
| }} else {{ | |
| uint m0 = meta & 0xFFu; | |
| uint m1 = (meta >> 8u) & 0xFFu; | |
| uint m2 = (meta >> 16u) & 0xFFu; | |
| uint m3 = (meta >> 24u) & 0xFFu; | |
| {slots(False, " ", b)} | |
| }} | |
| }}""" | |
| loop = f""" | |
| {decls} | |
| // Double-buffer the super-atom stream: the next step's words are in | |
| // flight while this step decodes and accumulates. | |
| const device uint *base = (const device uint *)packed;{pre} | |
| for (uint step = 0; step < SA_ROW; ++step) {{ | |
| const device uint *next = base + min(step + 1u, SA_ROW - 1u) * 384u;{prefetch} | |
| uint k_j = step * 64u + 16u * j + 2u * (lane & 3u);{decode}{advance} | |
| }} | |
| """ | |
| tail = "" | |
| for b in range(blocks): | |
| for r in range(rows): | |
| tail += f""" | |
| // A butterfly over the 16 threads that share a column halves the | |
| // tail four times, then the surviving lane writes both weight rows. | |
| float v0_{b}_{r} = sum_{b}_{r}_0; | |
| float v1_{b}_{r} = sum_{b}_{r}_1; | |
| v0_{b}_{r} += simd_shuffle_xor(v0_{b}_{r}, 8u); | |
| v0_{b}_{r} += simd_shuffle_xor(v0_{b}_{r}, 4u); | |
| v0_{b}_{r} += simd_shuffle_xor(v0_{b}_{r}, 2u); | |
| v0_{b}_{r} += simd_shuffle_xor(v0_{b}_{r}, 1u); | |
| v1_{b}_{r} += simd_shuffle_xor(v1_{b}_{r}, 8u); | |
| v1_{b}_{r} += simd_shuffle_xor(v1_{b}_{r}, 4u); | |
| v1_{b}_{r} += simd_shuffle_xor(v1_{b}_{r}, 2u); | |
| v1_{b}_{r} += simd_shuffle_xor(v1_{b}_{r}, 1u); | |
| if ((physical & 15u) == 0u) {{ | |
| uint column = (column_block + {b}u) * 16u + (physical >> 4); | |
| output[{r} * N + column] = OUTPUT_TYPE(v0_{b}_{r} + bias[column]); | |
| output[{r} * N + column + 8u] = OUTPUT_TYPE(v1_{b}_{r} + bias[column + 8u]); | |
| }} | |
| """ | |
| return loop + tail | |
| _ROWS_SOURCE_HEAD = """ uint physical = thread_position_in_threadgroup.x; | |
| uint column_block = threadgroup_position_in_grid.y * BLOCKS; | |
| uint lane = physical >> 2; | |
| uint j = physical & 3u; |
GPTQModel/gptqmodel/utils/mlx.py
Lines 143 to 240 in 0b94d79
| def _packed_mlx_weights(model, config, lm_head_name, *, stock_compatible: bool = False): | |
| """Transfer exact packed layers or decoded weight-only layers to MLX. | |
| ``stock_compatible`` keeps only layers that map onto stock | |
| ``mlx.nn.QuantizedLinear`` and returns ``None`` when a layer needs | |
| GPT-QModel's custom MLX runtime. The export path uses it so the written | |
| checkpoint loads with stock ``mlx_lm.load`` on any OS (#4091 item 10). | |
| """ | |
| quantized = [(name, module) for name, module in model.named_modules() | |
| if isinstance(module, (TorchLinear, GPTQBitBLASMlxQuantLinear, | |
| AWQBitBLASMlxQuantLinear, | |
| AwqTorchLinear, QQQTorchLinear, | |
| GGUFTorchLinear, TorchFP8Linear, BitsAndBytesLinear, | |
| ExllamaV3TorchLinear, AwqGEMVLinear, | |
| AwqGEMVFastLinear, MacaqLinear, NF12Linear))] | |
| if not quantized: | |
| return None | |
| layer_params = {} | |
| group16 = set() | |
| gptq_group16 = set() | |
| awq_group16 = set() | |
| gguf_dtype = set() | |
| gguf_q6_k = set() | |
| bitsandbytes_native = {} | |
| exl3_native = {} | |
| gptq_dtype = set() | |
| awq_dtype = set() | |
| paro = {} | |
| qqq = {} | |
| fp8_native = {} | |
| fp8_packed = {} | |
| macaq_native = {} | |
| nf12_native = {} | |
| for name, module in quantized: | |
| if isinstance(module, ExllamaV3TorchLinear): | |
| if module.in_features <= 0 or module.out_features <= 0 or getattr(module, "trellis", None) is None: | |
| raise ValueError(f"EXL3 layer {name} cannot be transferred to MLX") | |
| exl3_native[name] = module | |
| continue | |
| mlx_linear = _mlx_holder_class(module) | |
| if not mlx_linear.source_compatible(module): | |
| if isinstance(module, (ParoLinear, QQQTorchLinear, GGUFTorchLinear, | |
| TorchFP8Linear, BitsAndBytesLinear, AwqGEMVLinear, | |
| AwqGEMVFastLinear, MacaqLinear, NF12Linear)): | |
| raise ValueError(f"{type(module).__name__} layer {name} cannot be transferred to MLX") | |
| return None | |
| if isinstance(module, TorchFP8Linear) and mlx_linear.native_compatible(module): | |
| fp8_native[name] = module | |
| elif isinstance(module, TorchFP8Linear): | |
| fp8_packed[name] = mlx_linear.packed_payload(module) | |
| continue | |
| elif isinstance(module, BitsAndBytesLinear): | |
| bitsandbytes_native[name] = BitsAndBytesMlxQuantLinear.native_payload(module) | |
| continue | |
| elif isinstance(module, MacaqLinear) and not MacaqMlxQuantLinear.stock_compatible(module): | |
| macaq_native[name] = MacaqMlxQuantLinear.native_payload(module) | |
| continue | |
| elif isinstance(module, NF12Linear): | |
| nf12_native[name] = NF12MlxQuantLinear.native_payload(module) | |
| continue | |
| layer_params[name] = mlx_linear.mlx_params(module) | |
| if isinstance(module, ParoLinear): | |
| paro[name] = module | |
| if isinstance(module, QQQTorchLinear): | |
| qqq[name] = module | |
| if (isinstance(module, GGUFTorchLinear) and module.gguf_tensor_qtype == "Q6_K") or ( | |
| not isinstance(module, (QQQTorchLinear, GGUFTorchLinear, TorchFP8Linear, MacaqLinear)) | |
| and module.group_size == 16): | |
| group16.add(name) | |
| if isinstance(module, GGUFTorchLinear) and module.gguf_tensor_qtype == "Q6_K": | |
| gguf_q6_k.add(name) | |
| elif mlx_linear in (MlxQuantLinear, GPTQMarlinMlxQuantLinear): | |
| gptq_group16.add(name) | |
| elif mlx_linear in (AwqMlxQuantLinear, AWQMarlinMlxQuantLinear): | |
| awq_group16.add(name) | |
| elif isinstance(module, (GPTQBitBLASMlxQuantLinear, TorchLinear)): | |
| if not stock_compatible: | |
| gptq_dtype.add(name) | |
| elif (isinstance(module, (AwqTorchLinear, AWQBitBLASMlxQuantLinear, | |
| AwqGEMVLinear, AwqGEMVFastLinear, LLMAwqLinear)) | |
| and not isinstance(module, ParoLinear)): | |
| if not stock_compatible: | |
| awq_dtype.add(name) | |
| elif isinstance(module, GGUFTorchLinear): | |
| gguf_dtype.add(name) | |
| if stock_compatible: | |
| custom_layers = ( | |
| set(group16) | set(paro) | set(qqq) | set(fp8_native) | |
| | set(fp8_packed) | set(bitsandbytes_native) | set(exl3_native) | |
| | set(gguf_dtype) | set(macaq_native) | set(nf12_native) | |
| ) | |
| if custom_layers: | |
| log.info( | |
| "MLX: %d layer(s) need GPT-QModel's custom MLX runtime; using " | |
| "the stock-compatible requantization path instead.", | |
| len(custom_layers), |
6f9fc71 (#4133), 2026-11-15T11:18:39Z. Its immediate first-parent a8c7675 has a single 16-column block per grid group and covers these same widths. Later #4136 retains the defective launch.
Existing reports
OPEN/CLOSED searches for NF12/MLX/tail/columns/row_blocks found no matching report. #3971 concerns malformed native tensor indexing, not valid-width launch coverage. #4130 concerns Machete/test audit inventory, not this defect. Search is not exhaustive.
Software / device info and validation limits
Airtight host-launch/index contract proof and executed shipped Python dispatch only. No Apple Metal kernel, shader compiler, packed-byte numerical comparison, full model, allocator observation or performance measurement.
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
Qubitium commentedon Nov 17, 2026
Claimed. This issue is now owned by a dedicated worker; a fix PR referencing it will follow. Please avoid duplicating work on it in the meantime.
fix(mlx): cover NF12 short-row output tails in dot-product dispatch (#…