Skip to content

[BUG] EXL3 native export rejects safe per-layer shard paths emitted by reshard #3828

Closed

Description

@devin-ai-integration

Describe the bug

EXL3 checkpoint publication aborts when native passthrough reads a valid per-layer source checkpoint, including the default layout emitted by the public reshard() API.

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.

Trigger

Reshard a native safetensors source using reshard(..., ShardConfig(layer_prefixes=['model.layers'])), use the normal LazyTurtle source with active staging unset, and save EXL3 packed modules while preserving native layer norms or other untouched per-layer tensors.

Introducing change

Squash merge 5806645, 2026-11-09T09:32:39Z, feat(writer): compose native checkpoint passthrough and save overlays (#3602): 5806645 and #3602 . The introducing diff and HEAD blame independently attribute the unconditional basename guard to this commit. It remains at pinned HEAD; #3712 adds missing-indexed-tensor checks and leaves this guard unchanged.

Source evidence

The public reshard() contract explicitly emits model.layers.0/layer.safetensors:

def reshard(
from_model,
to_model_path: Union[str, os.PathLike],
config: Optional[ShardConfig] = None,
*,
shard_config: Optional[ShardConfig] = None,
overwrite: bool = False,
trust_remote_code: bool = False,
) -> str:
"""Rewrite an existing checkpoint into a new shard layout.
Args:
from_model: Source checkpoint directory, a specific ``.safetensors``
or ``.safetensors.index.json`` path, or a loaded ``GPTQModel``
whose ``model_local_path`` points at the checkpoint. A standalone
file selects only itself; an indexed shard retains the complete
checkpoint, and a named index selects its own shards.
to_model_path: Destination directory. Weights are copied byte-for-byte;
config, tokenizer, and other non-weight files are copied alongside.
config: :class:`ShardConfig`. Defaults to
``ShardConfig(layout=ShardLayout.PER_LAYER_WITH_SINGLE_GLOBAL)``.
shard_config: Alias for ``config``.
overwrite: Replace an existing non-empty destination directory.
trust_remote_code: Allow remote code while reading ``config.json`` to
derive layer prefixes. Name-based detection is used when disabled.
Returns:
The destination directory path.
The default layout writes one directory per transformer layer
(``model.layers.0/layer.safetensors``) and exactly one root
``global.safetensors`` containing embeddings, lm-head, norms, and every other
non-layer tensor. The global shard is deliberately not named
``model.safetensors``: loaders such as ``transformers.from_pretrained``
prefer that single-file name over ``model.safetensors.index.json`` and would
. The real LazyTurtle reads and materializes that nested source when staging is unset, as independently executed; its optional staging basename guard is conditional:
def _checkpoint_shard_path(
self,
shard: str,
*,
module_path: Optional[str],
) -> str:
source_path = os.path.join(self.model_local_path, shard)
scope = self._active_source_scope(module_path)
root = self._active_source_root
if root is None or scope is None:
return source_path
if os.path.basename(shard) != shard:
raise ValueError("LazyTurtle checkpoint shard name is unsafe")
. The EXL3 save path builds a passthrough plan unconditionally for eligible native sources:
checkpoint_passthrough_plan = None
if runtime_format == FORMAT.GPTQ_V2:
log.warn(
f"Using 'format = {FORMAT.GPTQ_V2}': the serialized model is only supported by GPT-QModel version >= {MIN_VERSION_WITH_V2}."
)
if runtime_format == FORMAT.EXL3:
_validate_exllamav3_publication_modules(
self,
validated_overlay=save_state_overlay,
)
tensor_storage = _build_exllamav3_tensor_storage_for_save(
self,
validated_overlay=save_state_overlay,
)
quantize_config.tensor_storage = tensor_storage
self.quantize_config.tensor_storage = copy.deepcopy(tensor_storage)
checkpoint_passthrough_plan = _exllamav3_checkpoint_passthrough_plan(
self,
tensor_storage,
)
. The planner selects source identities without disqualifying directory shard paths:
def _exllamav3_checkpoint_passthrough_plan(owner, tensor_storage):
"""Describe an exact native checkpoint passthrough when names are stable.
A lazy shell uses runtime module names, which can differ from the original
safetensors keys after Transformers applies a conversion map. Serializing
untouched tensors from that shell silently renames native checkpoint state
and can also materialize it unnecessarily. When every EXL3 replacement
has the same authoritative ``<module>.weight`` name in the source index,
retain all other source entries byte-for-byte under their original names.
"""
checkpoint_source = getattr(owner, "turtle_model", None)
weight_map = getattr(checkpoint_source, "_weight_map", None)
source_root = getattr(checkpoint_source, "model_local_path", None)
if not isinstance(weight_map, dict) or not weight_map:
return None
if not isinstance(source_root, str) or not source_root:
return None
if not isinstance(tensor_storage, dict) or not tensor_storage:
return None
quant_names = set()
replaced_source_modules = set()
source_candidates = getattr(
owner,
"exllamav3_checkpoint_module_candidates",
None,
)
fused_replacements = getattr(owner, "exllamav3_checkpoint_replaced_tensors", None)
replaced_fused_names = None
if callable(fused_replacements):
replaced_fused_names = fused_replacements(tensor_storage)
if (
not isinstance(replaced_fused_names, (set, frozenset))
or not replaced_fused_names
or not all(isinstance(name, str) for name in replaced_fused_names)
or not replaced_fused_names.issubset(weight_map)
):
raise RuntimeError("EXL3 fused checkpoint replacement set is invalid")
for module_name, entry in tensor_storage.items():
if not isinstance(module_name, str) or not module_name:
return None
stored = entry.get("stored_tensors") if isinstance(entry, dict) else None
if not isinstance(stored, dict) or not stored:
return None
names = set(stored)
if any(
not isinstance(name, str) or not name.startswith(f"{module_name}.")
for name in names
):
return None
quant_names.update(names)
if replaced_fused_names is not None:
continue
if callable(source_candidates):
candidates = source_candidates(module_name)
if (
not isinstance(candidates, (list, tuple))
or not candidates
or any(
not isinstance(candidate, str) or not candidate
for candidate in candidates
)
or len(set(candidates)) != len(candidates)
):
raise RuntimeError(
"EXL3 checkpoint module candidates must be unique "
f"non-empty strings for {module_name}"
)
else:
candidates = (module_name,)
matches = [
candidate
for candidate in candidates
if f"{candidate}.weight" in weight_map
]
if len(matches) != 1:
if callable(source_candidates):
raise RuntimeError(
"EXL3 checkpoint module mapping is not unique for "
f"{module_name}: {matches}"
)
return None
replaced_source_modules.add(matches[0])
if replaced_fused_names is not None:
return {
"checkpoint_source": checkpoint_source,
"quant_names": frozenset(quant_names),
"replaced_source_names": frozenset(replaced_fused_names),
}
# Conversion-based architectures are eligible only when the publication
# module identities themselves are also source-checkpoint identities. This
# makes passthrough exact and keeps the fallback behavior for architectures
# whose quantized prefixes require a more involved conversion contract.
# An EXL3 module replaces the complete native module state, not only its
# weight tensor. Native FP8 checkpoints commonly keep auxiliary tensors
# such as ``weight_scale_inv`` under the same prefix; preserving those
# after replacing the weight leaks stale source state into the published
# tensor namespace. Match the complete authoritative source prefix, just
# like the ordinary save-state overlay path does.
replaced_source_names = set()
for name in weight_map:
owner_name = name
while "." in owner_name:
owner_name = owner_name.rsplit(".", 1)[0]
if owner_name in replaced_source_modules:
replaced_source_names.add(name)
break
return {
"checkpoint_source": checkpoint_source,
"quant_names": frozenset(quant_names),
"replaced_source_names": frozenset(replaced_source_names),
}
def _torch_dtype_from_safetensors_name(name: str) -> torch.dtype:
. The builder then rejects any index filename differing from its basename:
native_sources: Dict[str, TensorSource] = {}
for shard_name in sorted(by_shard):
# Hugging Face snapshots intentionally store basename-only symlinks to
# the repository's shared ``blobs`` directory, which is outside the
# snapshot root after realpath resolution. Reject path components and
# traversal, but permit that canonical snapshot-link layout.
if os.path.basename(shard_name) != shard_name or shard_name in {".", ".."}:
raise RuntimeError(f"Checkpoint shard name is unsafe: {shard_name}")
shard_path = os.path.realpath(os.path.join(source_root, shard_name))
if not os.path.isfile(shard_path):
raise RuntimeError(f"Checkpoint shard is not a regular file: {shard_name}")
. Once selected, save_quantized() calls this builder with no materialization fallback:
if checkpoint_passthrough_plan is not None:
state_dict = _build_exllamav3_checkpoint_passthrough_state_dict(
self,
checkpoint_passthrough_plan,
offload_root=offload_root,
validated_overlay=save_state_overlay,
)
else:
state_dict = get_state_dict_for_save(self.model, offload_root=offload_root)
if checkpoint_passthrough_plan is None:
state_dict.update(out_of_model_state_dict)
out_of_model_state_dict.clear()
_apply_save_state_overlay(
self,
state_dict,
validated_overlay=save_state_overlay,
)
checkpoint_key_for_save = getattr(self, "checkpoint_key_for_save", None)
if callable(checkpoint_key_for_save) and checkpoint_passthrough_plan is None:
state_dict = _convert_checkpoint_state_dict_keys(state_dict, checkpoint_key_for_save)
. The existing passthrough regression uses a basename-only source symlink:
def test_exl3_checkpoint_passthrough_preserves_native_source_identity(tmp_path, fused):
snapshot = tmp_path / "snapshot"
blobs = tmp_path / "blobs"
snapshot.mkdir()
blobs.mkdir()
blob_path = blobs / "payload"
source_path = snapshot / "source.safetensors"
native = torch.tensor([1.25, -2.5], dtype=torch.float32)
source_weight = "fused.gate_up_proj" if fused else "expert.weight"
save_file(
{
source_weight: torch.ones((2, 2), dtype=torch.bfloat16),
"expert.weight_scale_inv": torch.ones((1, 1), dtype=torch.float32),
"original.hc_attn_base": native,
},
blob_path,
)
source_path.symlink_to(blob_path)
model = torch.nn.Module()
model.expert = _FakeEXL3()
model.expert.register_buffer("trellis", torch.ones((1,), dtype=torch.int16))
model.expert.register_buffer("suh", torch.ones((1,), dtype=torch.float16))
model.expert.register_buffer("svh", torch.ones((1,), dtype=torch.float16))
model.expert.register_buffer("mcg", torch.ones((), dtype=torch.int32))
# This runtime-only spelling must never leak into the published checkpoint.
model.runtime_alias = torch.nn.Parameter(torch.zeros((2,), dtype=torch.float32))
owner = SimpleNamespace(
model=model,
turtle_model=SimpleNamespace(
model_local_path=str(snapshot),
_weight_map={
source_weight: source_path.name,
"expert.weight_scale_inv": source_path.name,
"original.hc_attn_base": source_path.name,
},
),
)
storage = {
"expert": {
"stored_tensors": {
f"expert.{suffix}": {}
for suffix in ("trellis", "suh", "svh", "mcg")
}
}
}
if fused:
owner.exllamav3_checkpoint_replaced_tensors = lambda storage: {
source_weight, "expert.weight_scale_inv"
}
plan = writer._exllamav3_checkpoint_passthrough_plan(owner, storage)
assert plan["replaced_source_names"] == frozenset(
{source_weight, "expert.weight_scale_inv"}
)
state = writer._build_exllamav3_checkpoint_passthrough_state_dict(owner, plan)
.

To reproduce / expected behavior

From the public checkout at 35987df, with its requirements installed, run the following command (Python 3.12.16, torch 2.15.0+cpu, Transformers 5.22.2, Accelerate 1.15.0 and safetensors 0.8.0 were used):

python - <<'PY'
import json
import tempfile
from pathlib import Path
from types import SimpleNamespace

import torch
from safetensors.torch import save_file
from gptqmodel.reshard import reshard, ShardConfig
from gptqmodel.models import writer
from gptqmodel.utils.structure import LazyTurtle

with tempfile.TemporaryDirectory() as d:
    source, nested = Path(d)/'source', Path(d)/'nested'
    source.mkdir()
    save_file({
        'model.layers.0.proj.weight': torch.ones(2, 2),
        'model.layers.0.norm.weight': torch.ones(2),
        'model.embed_tokens.weight': torch.ones(4, 2),
    }, source/'model.safetensors')
    reshard(source, nested, ShardConfig(layer_prefixes=['model.layers']))
    weight_map = json.loads((nested/'model.safetensors.index.json').read_text())['weight_map']
    model = torch.nn.Module()
    model.model = torch.nn.Module()
    model.model.layers = torch.nn.ModuleList([torch.nn.Module()])
    model.model.layers[0].proj = torch.nn.Linear(2, 2, bias=False, device='meta')
    model.model.layers[0].norm = torch.nn.Module()
    model.model.layers[0].norm.register_parameter('weight', torch.nn.Parameter(torch.empty(2, device='meta')))
    turtle = LazyTurtle.maybe_create(
        model_local_path=str(nested), config=SimpleNamespace(_experts_implementation=None),
        model_init_kwargs={'device_map': {'': 'cpu'}}, target_model=model)
    turtle.materialize_submodule(
        target_model=model, target_submodule=model.model.layers[0],
        device=torch.device('cpu'), module_path='model.layers.0', recurse=True)
    print('native layer loaded:', model.model.layers[0].norm.weight.tolist(),
          model.model.layers[0].proj.weight.sum().item())
    model.model.layers[0].proj = torch.nn.Module()
    model.model.layers[0].proj.register_buffer('trellis', torch.ones(1, dtype=torch.int16))
    owner = SimpleNamespace(model=model, turtle_model=turtle)
    plan = writer._exllamav3_checkpoint_passthrough_plan(owner, {
        'model.layers.0.proj': {'stored_tensors': {'model.layers.0.proj.trellis': {}}}
    })
    print('reshard map:', weight_map)
    print('passthrough selected:', plan is not None)
    try:
        writer._build_exllamav3_checkpoint_passthrough_state_dict(owner, plan)
    except RuntimeError as exc:
        print(type(exc).__name__ + ':', exc)
    # Control: the same source tensors with basename-only shard references work.
    owner.turtle_model.model_local_path = str(source)
    owner.turtle_model._weight_map = {key: 'model.safetensors' for key in weight_map}
    control = writer._build_exllamav3_checkpoint_passthrough_state_dict(owner, plan)
    print('flat source control:', sorted(control))
PY

Expected: the source layer loads and the safe nested relative shard can be used to preserve its norm and embedding while replacing only the projection. The basename-only source control should have the same successful result.

Observed result

native layer loaded: [1.0, 1.0] 4.0
reshard map: {'model.embed_tokens.weight': 'global.safetensors', 'model.layers.0.norm.weight': 'model.layers.0/layer.safetensors', 'model.layers.0.proj.weight': 'model.layers.0/layer.safetensors'}
passthrough selected: True
RuntimeError: Checkpoint shard name is unsafe: model.layers.0/layer.safetensors
flat source control: ['model.embed_tokens.weight', 'model.layers.0.norm.weight', 'model.layers.0.proj.trellis']

Validation limits

Executed public reshard(), real LazyTurtle construction/materialization, and shipped EXL3 planner/state builder on CPU with three generic small tensors. A stand-in packed trellis module supplies the publication inventory, matching the dispatch shape of the public tests. This proves source reachability and path rejection, not EXL3 GPU numerics, calibration, quantization or a full save_quantized() integration run. No model download.

Duplicate check

Independently ran gh issue list --repo ModelCloud/GPTQModel --state all --limit 100 --search QUERY for reshard, "unsafe shard", EXL3, passthrough, "nested" "shard", and "per-layer" checkpoint. No matching report found. Reshard, unsafe-shard and nested-shard searches returned no results. Read closed #1977 (GLM VRAM/quantization failure) and closed #2916 (Transformers create_repo import); neither describes this. Read merged #3602 and its follow-up note about #3712, then inspected the #3712 diff to verify it fixes a different condition.

Activity

  1. added
    bug
    on Nov 13, 2026
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