Skip to content

[BUG] Block-float checkpoint loading loses source architecture and bias precision #3821

Closed

Description

@devin-ai-integration

Describe the bug

Two block-float checkpoint fidelity defects affect supported inputs: the generated Transformers entry point always constructs Llama, and packed linear bias buffers always narrow to FP16. Native loading works around the first defect but still exhibits the second.

Priority: P2 — a supported configuration produces incorrect behavior. Specific triggers and validation boundaries are below.

Reviewed at 35987dfb7, within the merged-change window 2026-09-25 07:00 UTC–2026-11-13 07:00 UTC. The changes through 8ea76c395 were checked before filing; these causes remain.

GPU / software / model information

These are focused correctness reproductions using small generic fixtures and public model classes; no external model or dataset download is required. Each case states its execution environment and any hardware or mocking limitation. Accelerator execution is not claimed from a CPU dispatch test.

1. Exported non-Llama block-float checkpoints point Transformers at a Llama-only class

A supported OPT block-float model exports successfully and produces finite logits through the native loader, but the advertised self-contained Transformers loading path fails before loading packed weights. Native loading remains a workaround.

Trigger

Create a tiny ordinary OPTForCausalLM, put decoder Linear and input-embedding weights onto the shipped block-float grid, save_blockfloat_model, then AutoModelForCausalLM.from_pretrained(..., trust_remote_code=True). No external checkpoint or malformed state is required.

Introducing change

Merged public PR #3760 ; squash commit 2766051 . GitHub merged_at 2026-11-13T04:38:59Z. Independently verified original source, blame on generated base class/auto_map, and absence of these files at baseline. Relevant subsequent commits through pinned HEAD do not change this base class.

Source evidence

Unconditional generated Llama import/subclass:

_MODELING_SOURCE = """\
# SPDX-FileCopyrightText: 2026 ModelCloud.ai
# SPDX-License-Identifier: Apache-2.0
\"\"\"Modeling entry point for a Tenstorrent block-float checkpoint.
The weights are stored in the standard shards-plus-index layout; the only thing
that differs from a dense checkpoint is that the quantized modules keep packed
mantissa codes instead of a dense ``weight``. This swaps those modules in so a
plain ``AutoModelForCausalLM.from_pretrained`` produces a working model rather
than one with randomly initialised decoder layers.
Requires ``gptqmodel``.
\"\"\"
from transformers import LlamaForCausalLM
from gptqmodel.nn_modules.qlinear.tt_blockfloat import swap_blockfloat_modules
class TTBlockfloatForCausalLM(LlamaForCausalLM):
def __init__(self, config, **kwargs):
super().__init__(config, **kwargs)
quant = dict(getattr(config, "quantization_config", None) or {})
swap_blockfloat_modules(
self,
bits_per_layer=dict(quant.get("bits_per_layer") or {}),
default_bits=int(quant.get("bits", 4)),
embed_bits=int(quant.get("embed_bits", 8)),
block=int(quant.get("block", 16)),
)
. Every exported config receives that auto_map:
# Ship the modeling file so plain ``transformers`` can load this directory.
# Without it, ``from_pretrained`` reports the codes as unexpected, leaves the
# decoder layers at their random initial values, and returns a model that
# generates garbage with no error.
config["auto_map"] = {"AutoModelForCausalLM": f"{MODELING_FILE[:-3]}.TTBlockfloatForCausalLM"}
with open(os.path.join(output_dir, "config.json"), "w") as handle:
json.dump(config, handle, indent=2)
with open(os.path.join(output_dir, MODELING_FILE), "w") as handle:
handle.write(_MODELING_SOURCE)
. Generic prefix discovery accepts OPT decoder linears and embedding:
def _quantized_prefixes(model) -> list:
"""Module paths this checkpoint stores as block-float codes.
Decoder linears plus the input embedding. The embedding is included because
a vocabulary table is the single largest tensor in a small model: as codes at
``bf8_b`` it is 266.16 MiB against 501.00 MiB of dense float16 for
Llama-3.2-1B (250.50 MiB codes + 15.66 MiB exponents).
A model returned by :func:`build_blockfloat_model` has already been swapped,
so its quantized modules are ``TTBlockfloat*`` instances rather than
``nn.Linear``/``nn.Embedding``. They are recognised by the packed buffers
they own, which keeps a re-save from silently finding nothing to write.
"""
import torch.nn as nn
prefixes = []
for name, module in model.named_modules():
if not name:
continue
if isinstance(getattr(module, "codes", None), torch.Tensor):
prefixes.append(name)
elif isinstance(module, nn.Embedding) and name.endswith("embed_tokens"):
prefixes.append(name)
elif isinstance(module, nn.Linear) and ".layers." in name:
prefixes.append(name)
return prefixes
. Native builder instead selects by config.model_type:
# Build through the concrete class rather than ``AutoModelForCausalLM`` so a
# checkpoint's own ``auto_map`` cannot make this path import remote code.
class_name = MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.get(config.model_type)
if class_name is None:
raise ValueError(
f"{checkpoint_dir} has unsupported model_type `{config.model_type}`"
)
# Build through the dtype-aware constructor, then cast per tensor. A blanket
# ``.to(dtype)`` would also narrow Llama's float32 rotary ``inv_freq``, which
# ``from_pretrained`` deliberately leaves alone.
model = getattr(transformers, class_name)._from_config(config)
_cast_model_dtype(model, dtype)
_sync_config_dtype(model.config, dtype)
restored = swap_blockfloat_modules(
model,
bits_per_layer=widths,
default_bits=int(quantization_config.get("bits", 4)),
embed_bits=int(quantization_config.get("embed_bits", 8)),
block=int(quantization_config.get("block", BLOCKFLOAT_BLOCK)),
quantized_prefixes=sorted(widths),
)
missing, unexpected = model.load_state_dict(state, strict=False)
. The project explicitly exercises OPT block-float quantization in a hardware/model-gated test:
@pytest.mark.skipif(
os.environ.get("GPTQMODEL_TEST_TT_MODEL") != "1",
reason="explicit end-to-end model gate",
)
def test_opt125m_native_bf4_matches_int4_quantized_checkpoint():
"""Native bf4_b should be in the same accuracy class as a shipped GPTQ int4 model.
Compares post-quantization quality on the same prompt, using the published
OPT-125M GPTQ int4 checkpoint as the reference point rather than the dense
model, which is the comparison a user actually cares about.
"""
from transformers import AutoModelForCausalLM, AutoTokenizer
from gptqmodel.utils.tt_blockfloat_quant import quantize_model_blockfloat
tok = AutoTokenizer.from_pretrained(OPT_MODEL_ID)
ids = tok("The quick brown fox", return_tensors="pt").input_ids
model = AutoModelForCausalLM.from_pretrained(OPT_MODEL_ID, dtype=torch.float32)
with torch.no_grad():
dense = model(ids).logits[0, -1].float().clone()
quantize_model_blockfloat(
model, tok, bits=4, nsamples=4, text=TT_CALIBRATION_TEXT
)
with torch.no_grad():
bf4_b = model(ids).logits[0, -1].float().clone()
bf4_cos = float(torch.nn.functional.cosine_similarity(dense, bf4_b, dim=0))
assert bf4_cos > 0.99, f"native bf4_b cosine {bf4_cos} below the int4 class"
# --- GSM8K evaluation harness ----------------------------------------------
#
. Existing shipped-modeling-file regression tests only default Llama:
def test_shipped_modeling_file_makes_transformers_load_correctly(tmp_path):
"""Plain ``transformers`` must load the checkpoint correctly, not silently.
Without the shipped modeling file, ``AutoModelForCausalLM.from_pretrained``
reports the codes as unexpected, leaves the decoder layers at their random
initial values, and returns a model that generates garbage -- with no error.
The checkpoint therefore carries an ``auto_map`` plus the class it points at,
and this pins that the result is the same model the library loader builds.
"""
import importlib
bq = importlib.import_module("gptqmodel.utils.tt_blockfloat_quant")
torch.manual_seed(8)
from transformers import LlamaConfig, LlamaForCausalLM
config = LlamaConfig(
vocab_size=64, hidden_size=32, intermediate_size=64,
num_hidden_layers=1, num_attention_heads=4, num_key_value_heads=2,
tie_word_embeddings=True,
)
model = LlamaForCausalLM(config)
with torch.no_grad():
for block in model.model.layers:
for _, module in block.named_modules():
if getattr(module, "weight", None) is not None and module.weight.dim() == 2:
module.weight.copy_(bq.quantize_bf4(module.weight.detach().float()))
embed = model.model.embed_tokens
embed.weight.copy_(bq.quantize_blockfloat(embed.weight.detach().float(), 8)[0])
out = str(tmp_path / "ckpt")
bq.save_blockfloat_model(model, out, bits=4, embed_bits=8)
from transformers import AutoModelForCausalLM
remote = AutoModelForCausalLM.from_pretrained(
out, dtype=torch.float32, trust_remote_code=True
)
assert type(remote).__name__ == "TTBlockfloatForCausalLM"
assert type(remote.model.embed_tokens).__name__ == "TTBlockfloatEmbedding"
from gptqmodel import GPTQModel
ours = GPTQModel.load(out).model
ids = torch.randint(0, 64, (1, 6))
with torch.no_grad():
a = remote(ids).logits
b = ours(ids).logits
assert torch.equal(a, b), float((a - b).abs().max())
. That positive-control test passed independently; OPT failed through the exact same shipped export/AutoModel API.

To reproduce / expected behavior

From a public checkout at 35987df, with project requirements installed (executed Python 3.10.12, torch 2.14.1+cpu, Transformers 5.20.2, safetensors 0.8.0), run from the repository root:

python - <<'PY'
import tempfile
import torch
from transformers import AutoModelForCausalLM, OPTConfig, OPTForCausalLM
from gptqmodel.utils import tt_blockfloat_quant as bq

torch.manual_seed(0)
torch.set_num_threads(1)
model = OPTForCausalLM(OPTConfig(
    vocab_size=64, hidden_size=32, ffn_dim=64, num_hidden_layers=1,
    num_attention_heads=4, word_embed_proj_dim=32, max_position_embeddings=64)).eval()
with torch.no_grad():
    for name, module in model.named_modules():
        if isinstance(module, torch.nn.Linear) and '.layers.' in name:
            module.weight.copy_(bq.quantize_blockfloat(module.weight, 4)[0])
    embedding = model.get_input_embeddings()
    embedding.weight.copy_(bq.quantize_blockfloat(embedding.weight, 8)[0])
with tempfile.TemporaryDirectory() as directory:
    info = bq.save_blockfloat_model(model, directory, bits=4, embed_bits=8)
    native, _, _ = bq.build_blockfloat_model(directory)
    with torch.no_grad():
        logits = native(torch.tensor([[1, 2, 3]])).logits
    print('OPT:', info['layers'], type(native).__name__, tuple(logits.shape),
          bool(logits.isfinite().all()))
    try:
        AutoModelForCausalLM.from_pretrained(
            directory, trust_remote_code=True, dtype=torch.float32)
    except AttributeError as exc:
        print('AUTO ERROR:', str(exc))
        assert 'num_key_value_heads' in str(exc)
    else:
        raise AssertionError('Unexpected successful auto load')
PY

Expected: both loaders construct OPT-compatible models and accept the saved packed state.
Observed relevant output:
OPT: 7 OPTForCausalLM (1, 3, 64) True
AUTO ERROR: 'OPTConfig' object has no attribute 'num_key_value_heads'

Observed result

Actual native model was OPTForCausalLM with seven packed modules and finite logits of shape (1,3,64). Actual AutoModel loader invoked the emitted Llama subclass and raised AttributeError: 'OPTConfig' object has no attribute 'num_key_value_heads'. Expected both loaders to construct the source architecture.

Validation limits

Independently confirmed by actual shipped CPU save/load/forward and AutoModel execution using a tiny random OPT fixture. No AST extraction or mocked loader. Other non-Llama architectures not executed; no accelerator numerical claim.

2. Block-float linear packing and checkpoint loading silently narrow biases to FP16

Unquantized FP32/BF16 bias values lose precision even when the requested load dtype is FP32. Valid finite biases outside FP16 range become infinity, tiny values become zero, and ordinary FP32 values round. The corruption reaches the projection output and breaks a lossless checkpoint round trip.

Trigger

Directly pack an FP32 or BF16 bias-bearing nn.Linear with TTBlockfloatLinear, or save an on-grid LlamaConfig(attention_bias=True, mlp_bias=True) checkpoint and reload with build_blockfloat_model(..., dtype=torch.float32). Generic bias inputs [65536.0, 2**-30, 0.12345678] are valid FP32 values.

Introducing change

Merged public PR #3760 ; squash commit 2766051 , GitHub merged_at 2026-11-13T04:38:59Z. Independently verified original constructor/pack source and pinned blame. Later #3813 , commit 33df888 (merged 2026-11-13T06:12:18Z), fixes dense dtype handling before module replacement, leaving this distinct bias loss present at the pin.

Source evidence

Constructor hardcodes FP16 bias regardless of dtype:

out_features: int,
bias: bool,
backend: BACKEND,
adapter: Optional[Adapter] = None,
name: str = None,
dtype: Optional[torch.dtype] = None,
block: int = BLOCKFLOAT_BLOCK,
pack_dtype: torch.dtype = torch.uint8,
**kwargs,
):
if block != BLOCKFLOAT_BLOCK:
raise NotImplementedError(
f"{type(self).__name__} stores one exponent per {BLOCKFLOAT_BLOCK} "
f"values; block={block} is not a hardware format"
)
super().__init__(
bits=bits,
in_features=in_features,
out_features=out_features,
bias=bias,
backend=backend,
adapter=adapter,
name=name,
register_buffers=False,
dtype=dtype,
validate_kwargs={"pack_dtype": pack_dtype},
)
self.block = block
self.pack_dtype = pack_dtype
self._init_storage(out_features, in_features, bits, block)
if bias:
self.register_buffer("bias", torch.zeros(out_features, dtype=torch.float16))
else:
self.bias = None
. Direct pack separately forces FP16:
def pack(self, linear: nn.Module, scales=None, zeros=None, g_idx=None, **kwargs):
"""Quantise a dense ``linear`` onto the block-float grid."""
from ...utils import tt_blockfloat_hip
from ...utils.tt_blockfloat_quant import quantize_blockfloat
weight = linear.weight.detach().to(torch.float32)
if self.hip_dispatch(weight):
# Quantise on the GPU: the exponent search and packing stay on the
# device instead of round-tripping a dense fp32 copy through torch.
codes, exponents = tt_blockfloat_hip.quantize(weight, self.bits)
self.set_packed_state(codes, exponents)
else:
self.load_codes_from(
quantize_blockfloat(weight, self.bits, block=self.block)[0]
)
if getattr(linear, "bias", None) is not None:
self.bias = linear.bias.detach().to(torch.float16).contiguous()
. Saver preserves the original source bias:
bits_per_layer[prefix] = layer_width
bias = getattr(module, "bias", None)
if not is_embedding and isinstance(bias, torch.Tensor):
tensors[f"{prefix}.bias"] = bias.detach().contiguous()
continue
layer_width = embed_bits if is_embedding else _layer_bits(bits, prefix)
weight = module.weight.detach().to(torch.float32)
try:
codes, exponents = decompose_blockfloat(weight, bits=layer_width)
except ValueError:
# Not on the grid (or not quantized): keep it dense like any other
# float tensor rather than claiming a format it does not have.
tensors[f"{prefix}.weight"] = weight.contiguous()
continue
tensors[f"{prefix}.codes"] = _pack_codes(codes, layer_width).contiguous()
tensors[f"{prefix}.code_shape"] = torch.tensor(
list(codes.shape), dtype=torch.int64
)
tensors[f"{prefix}.exponents"] = exponents.to(torch.int8).contiguous()
bits_per_layer[prefix] = layer_width
if not is_embedding and getattr(module, "bias", None) is not None:
tensors[f"{prefix}.bias"] = module.bias.detach().contiguous()
. Native builder casts the dense model BEFORE swap and then copies state into new buffers:
# Build through the dtype-aware constructor, then cast per tensor. A blanket
# ``.to(dtype)`` would also narrow Llama's float32 rotary ``inv_freq``, which
# ``from_pretrained`` deliberately leaves alone.
model = getattr(transformers, class_name)._from_config(config)
_cast_model_dtype(model, dtype)
_sync_config_dtype(model.config, dtype)
restored = swap_blockfloat_modules(
model,
bits_per_layer=widths,
default_bits=int(quantization_config.get("bits", 4)),
embed_bits=int(quantization_config.get("embed_bits", 8)),
block=int(quantization_config.get("block", BLOCKFLOAT_BLOCK)),
quantized_prefixes=sorted(widths),
)
missing, unexpected = model.load_state_dict(state, strict=False)
. Swap creates new linears without inheriting the source bias dtype:
elif isinstance(module, nn.Linear):
replacement = TTBlockfloatLinear(
bits=bits,
in_features=int(module.in_features),
out_features=int(module.out_features),
bias=module.bias is not None,
backend=BACKEND.TT_BLOCKFLOAT,
adapter=None,
name=prefix,
block=block,
)
. Forward merely widens already-corrupted bias to x.dtype:
def forward(self, x: torch.Tensor) -> torch.Tensor:
if x.numel() == 0:
return self.empty_linear_output(x)
out_dtype = x.dtype
bias = None if self.bias is None else self.bias.to(x.dtype)
out = self._kernel_linear(x, bias)
if out is None:
weight = self.dequantize(dtype=x.dtype)
out = F.linear(x, weight, bias)
# Release the temporary before the activation leaves this scope.
del weight
if self.adapter is not None:
out = self.adapter.apply(x=x, out=out)
return out.to(out_dtype)
. The existing resave fixture sets biased projection to zero:
def test_native_checkpoint_resave_is_bit_identical(tmp_path):
"""checkpoint -> floats -> checkpoint must reproduce the same codes.
Re-saving is how provenance is added to a checkpoint that was written before
the metadata existed. That is only honest if the decode/encode round trip is
exact -- otherwise "re-saving" would quietly re-quantise the model.
"""
import importlib
bq = importlib.import_module("gptqmodel.utils.tt_blockfloat_quant")
torch.manual_seed(11)
block = torch.nn.Module()
block.proj = torch.nn.Linear(64, 32, bias=True)
with torch.no_grad():
block.proj.weight.copy_(bq.quantize_bf4(torch.randn(32, 64) * 0.02))
block.proj.bias.zero_()
. Independently passing dense-precision and pinned-norm tests show #3813 works for those tensors, but the new bias buffer remains outside that conversion lifecycle.

To reproduce / expected behavior

From a public checkout at 35987df, with project requirements installed (executed Python 3.10.12, torch 2.14.1+cpu, Transformers 5.20.2, safetensors 0.8.0), run from the repository root:

python - <<'PY'
import tempfile
import torch
from transformers import LlamaConfig, LlamaForCausalLM
from gptqmodel.utils import tt_blockfloat_quant as bq
from gptqmodel.nn_modules.qlinear.tt_blockfloat import TTBlockfloatLinear
from gptqmodel.utils.backend import BACKEND

torch.manual_seed(0)
torch.set_num_threads(1)
model = LlamaForCausalLM(LlamaConfig(
    vocab_size=64, hidden_size=32, intermediate_size=64, num_hidden_layers=1,
    num_attention_heads=4, num_key_value_heads=2, tie_word_embeddings=True,
    attention_bias=True, mlp_bias=True)).eval()
values = torch.tensor([65536., 2.**-30, 0.12345678])
with torch.no_grad():
    for name, module in model.named_modules():
        if isinstance(module, torch.nn.Linear) and '.layers.' in name:
            module.weight.copy_(bq.quantize_blockfloat(module.weight, 4)[0])
    embedding = model.get_input_embeddings()
    embedding.weight.copy_(bq.quantize_blockfloat(embedding.weight, 8)[0])
    model.model.layers[0].self_attn.q_proj.bias[:3] = values
with tempfile.TemporaryDirectory() as directory:
    bq.save_blockfloat_model(model, directory, bits=4, embed_bits=8)
    saved = bq.load_hf_state_dict(directory)['model.layers.0.self_attn.q_proj.bias']
    native, _, _ = bq.build_blockfloat_model(directory, dtype=torch.float32)
    loaded = native.model.layers[0].self_attn.q_proj.bias
    assert torch.equal(saved[:3], values)
    with torch.no_grad():
        before = model.model.layers[0].self_attn.q_proj(torch.zeros(1, 32))
        after = native.model.layers[0].self_attn.q_proj(torch.zeros(1, 32))
    print('SAVED BIAS:', saved.dtype, saved[:3].tolist())
    print('LOADED BIAS:', loaded.dtype, loaded[:3].tolist())
    print('SOURCE OUTPUT:', before[0,:3].tolist())
    print('LOADED OUTPUT:', after[0,:3].tolist())
    assert torch.isfinite(before).all() and torch.isinf(after).any()
for dtype in (torch.float32, torch.bfloat16):
    source = torch.nn.Linear(16, 1, bias=True, dtype=dtype)
    with torch.no_grad():
        source.weight.zero_()
        source.bias.fill_(65536.)
    packed = TTBlockfloatLinear(
        bits=4, in_features=16, out_features=1, bias=True,
        dtype=dtype, backend=BACKEND.TT_BLOCKFLOAT).pack(source)
    with torch.no_grad():
        result = packed(torch.zeros(1, 16, dtype=dtype))
    print('DIRECT PACK:', dtype, packed.bias.dtype, result.item())
    assert torch.isinf(result).all()
PY

Expected: saved/restored FP32 biases and zero-input projections remain [65536.0, 9.313225746154785e-10, 0.12345678359270096]; both direct packs return finite 65536.
Observed relevant output:
SAVED BIAS: torch.float32 [65536.0, 9.313225746154785e-10, 0.12345678359270096]
LOADED BIAS: torch.float16 [inf, 0.0, 0.12347412109375]
SOURCE OUTPUT: [65536.0, 9.313225746154785e-10, 0.12345678359270096]
LOADED OUTPUT: [inf, 0.0, 0.12347412109375]
DIRECT PACK: torch.float32 torch.float16 inf
DIRECT PACK: torch.bfloat16 torch.float16 inf

Observed result

The real safetensors state retained FP32 [65536.0,9.313225746154785e-10,0.12345678359270096]. Native FP32-request reload created FP16 bias [inf,0.0,0.12347412109375], and zero-input projection returned those same corrupted values. Real direct packing of zero-weight FP32 and BF16 linears with finite 65536 bias each returned infinity.

Validation limits

Actual shipped CPU direct packing, safetensors save/read, native full model reload and projection inference. Both FP32 and BF16 direct-pack overflow executed independently; full checkpoint reproduction used FP32. No production-model prevalence or generation-quality measurement, and no GPU arithmetic claim.

Duplicate check

Independently ran gh issue list --repo ModelCloud/GPTQModel --state all --search QUERY --limit 100 --json number,title,state,url for blockfloat, tt-blockfloat, block-float, Tenstorrent, '"OPT" "Llama"', '"block-float" "Llama"', and '"num_key_value_heads" "OPT"'. No matching open or closed report found. Viewed body and comments of closed #1486 (old GPTQ 2.1.1 / Transformers 4.50 OPT generation/positioning problem with later passing-test reports), and closed #1668 (quantization tensor mismatch). Their formats, triggers and failures differ; this finding is not a claim that those old fixed bugs reopened. Exact old hardware/environment was not rerun.

Independently searched open AND closed issues with gh issue list --state all for blockfloat, tt-blockfloat, block-float, Tenstorrent, '"blockfloat" "bias"', '"block-float" "bias"', '"bias" "float16"' and '"TTBlockfloatLinear"'. No matching report. Broad bias/float16 hits concern older GPTQ/vLLM/import/calibration problems; exact new class searches return none. Viewed closed #2251 returned by block-float search; its INT3 Triton dequantization defect is unrelated. Also examined public #3813 review/fix history to ensure this is not the already-fixed dense/pinned-norm conversion issue.

Activity

  1. added
    bug
    on Nov 13, 2026
  2. added a commit that references this issue on Nov 18, 2026
    36ebdd0
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