Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(stream): refuse a packed or integer-quantised source by name, before the cache is written (#2103)

Alpamys Makazhan4a78a7ba74d1
diff --git a/changelog.d/0.76.0/2103.fixed.md b/changelog.d/0.76.0/2103.fixed.md
new file mode 100644
index 00000000..7ce7e6ad
--- /dev/null
+++ b/changelog.d/0.76.0/2103.fixed.md
@@ -0,0 +1,23 @@
+- **Layer streaming refuses a quantised checkpoint it cannot dequantise, by name, before a byte of
+ the layer cache is written.** A Kimi-K2-Thinking-shaped `deepseek_v3` checkpoint
+ (compressed-tensors `pack-quantized` INT4: int32 `weight_packed`, `weight_scale`, int64
+ `weight_shape`) used to be accepted: the sharder cast every int32 word and int64 shape to the
+ stream dtype, wrote the whole cache, and the streamed build then failed with "shard is missing
+ decoder weights". A source whose names still matched, such as bitsandbytes LLM.int8() (an int8
+ `weight` beside its `SCB`), did not fail at all: the int8 codes were streamed as weights. Now
+ refused, by the sharder, the disk pre-flight and the trainer setup in the same words: a
+ `quantization_config` whose `quant_method` is anything but `fp8` (compressed-tensors in any
+ format, GPTQ, AWQ, bitsandbytes, HQQ, AQLM, EETQ, torchao, quanto and every other quantiser
+ transformers registers, or `load_in_4bit`/`load_in_8bit` alone), refused from `config.json`
+ before any weight is resolved; and any tensor stored as an integer or packed type (I8, I16, I32,
+ I64, U8, U16, U32, U64, BOOL, F4), or named like a quantiser's companion (`weight_packed`,
+ `weight_scale`, `qweight`, `qzeros`, `g_idx`, `SCB`, `absmax`, `quant_map`, `W_q`, ...). The
+ message names the format, says layer streaming cannot dequantise it, and points to a bf16 or
+ FP8-block copy. Still read: plain floating point, DeepSeek-V3's block FP8, qwen4_exp's oMLX/oQ
+ affine bundles, and the integer buffers a supported model really has (qwen4_exp's PLE n-gram
+ hashing tables, `position_ids`). A pre-flight that met a stored type its header reader has no
+ spelling for (U32, U16, F4, ...) now refuses that tensor instead of sizing the cache at a guess.
+ The sharder checks the source before it creates the cache folder, looks a cache up or
+ quarantines an index, so a refusal leaves an existing cache untouched and a cache an older Soup
+ sharded from such a source is not reused. A `quantization_config` that is not a mapping is
+ refused as malformed, and one under `text_config` is read too. (#2103)
diff --git a/docs/performance-and-quantization.md b/docs/performance-and-quantization.md
index 32ae394d..a1974cf1 100644
--- a/docs/performance-and-quantization.md
+++ b/docs/performance-and-quantization.md
@@ -532,6 +532,7 @@ Measured:
Limits and refusals:
- **Architecture.** Only `model_type: deepseek_v3` is admitted. A Kimi K2 checkpoint declares `model_type: kimi_k2` and is still refused by name, FP8 or not.
- **Other FP8 formats.** Each of these is refused, and the message names the supported format: per-tensor scales, `e5m2` weights, `compressed-tensors`, ue8m0 (power-of-two) scales, static activation scales, a missing or misshapen scale, an FP8 tensor without a scale, and a scale without its tensor. A `weight_block_size` axis outside [1, 1048576] is refused too. A spelling the config already gives away is refused at setup, before any weight is resolved or downloaded; the rest before the first byte of the cache is written.
+- **Integer and packed formats.** Kimi-K2-Thinking's compressed-tensors `pack-quantized` INT4 (int32 `weight_packed`, `weight_scale`, int64 `weight_shape`) is not dequantised, and nor is any other integer quantiser; see the refusal list below.
- **Damaged values.** A weight that is NaN after dequantisation (the e4m3fn bytes 0x7F and 0xFF), a negative scale, a non-finite scale, and a weight past float16's range under a float16 stream (pre-Ampere cards; stream it in bfloat16) are refused, naming the tensor, when that tensor is read: before the cache index is written, though files of earlier layers may already be on disk (no index names them, so they are never used, and the next run shards again). A zero scale, as an all-zero block has, is kept.
- **Cache identity.** For `deepseek_v3`, `config.json` is part of the cache's source identity, as are the weight files, so a cache sharded from the bf16 checkpoint is never reused for its FP8 copy at the same path, nor the reverse.
- **After training.** The adapter is trained against the dequantised weights. Merging it or serving it loads the base through transformers' own FP8 path, which is a different numerical path from the one the adapter was trained on.
@@ -788,6 +789,12 @@ prints this advice when it sees you accumulating.
- `stream_source` / `stream_ngram_source` / `stream_buffers` / `stream_read_ahead` / `stream_vram_override` / `stream_vram_probe` / `stream_nf4_scale_cache` / `stream_expert_layout` / `stream_disk_kind` / `stream_pin` / `stream_loss_chunk` set while `stream_layers: false` → a footgun, refused
- `stream_expert_layout: per_expert` with `moe_lora` → refused: a routed expert streamed one at a time has nowhere to keep an adapter. On a base that is not `model_type: deepseek_v3` → refused at setup, before the weights are resolved
- an FP8 checkpoint in any format other than DeepSeek-V3's block FP8, or an FP8 base that is not `model_type: deepseek_v3` → refused naming the supported format: at setup when `config.json` gives it away, otherwise before the cache is written. The block format itself is dequantised at shard time (see "FP8 block-quantised bases" above)
+- any other quantised checkpoint → refused by name, before a byte of the cache is written, and in the same words by the sharder, the disk pre-flight and the setup. The sharder checks the source first, from its `config.json` and headers, so a refusal creates no cache folder, leaves an existing cache and its `index.json` untouched, and never reuses a cache an older Soup sharded from such a source. Layer streaming reads plain floating-point weights, DeepSeek-V3's block FP8 and, on qwen4_exp only, oMLX/oQ affine bundles; the message says which format it found, that layer streaming cannot dequantise it, and to point `training.base` at a bf16 or FP8-block copy. Refused:
+ - a `config.json` `quantization_config` whose `quant_method` is not `fp8`: `compressed-tensors` in any format (Kimi-K2-Thinking's `pack-quantized` INT4 among them), `gptq`, `awq`, `bitsandbytes` (or `load_in_4bit` / `load_in_8bit` with no method), `hqq`, `aqlm`, `eetq`, `torchao`, `quanto`, `fbgemm_fp8`, `mxfp4`, `mxfp8`, `nvfp4`, `gguf` and every other quantiser transformers registers, or a name it does not. Also read from `text_config` when the top level has none, and a value that is not a mapping (a string, a list, a number) is refused as malformed. `quant_method` is matched exactly, as transformers matches it: `FP8` is not `fp8`. Refused at setup, before any weight is resolved or downloaded. A config with no `quant_method` (the oMLX/oQ spelling, `bits` and `group_size` only) is decided by its tensors;
+ - a tensor stored as an integer or packed type (I8, I16, I32, I64, U8, U16, U32, U64, BOOL, F4), which a plain read would cast to floats and train on: GPTQ/AWQ `qweight`, compressed-tensors `weight_packed`, bitsandbytes uint8 and int8 weights, oMLX/oQ uint32 words on an architecture other than qwen4_exp;
+ - a floating-point tensor named like a quantiser's companion: `weight_scale` (compressed-tensors; DeepSeek-V3's block FP8 spells its scale `weight_scale_inv`), `weight_global_scale`, `weight_zero_point`, `input_scale`, `qzeros`, `g_idx`, `SCB`, `absmax`, `quant_map`, `W_q`, `codebooks` and the like.
+
+ Not refused: the integer buffers a supported model really carries, which are qwen4_exp's PLE n-gram hashing tables (`layer_multipliers`, `ngram_heads_vocab_sizes`, `ngram_heads_offsets`, int64; the runtime keeps the skeleton's own values) and `position_ids`. The supported families' own checkpoints carry no other integer tensor (pinned by a tiny checkpoint of each in `tests/test_stream_refuses_packed_quant.py`). Dequantise any other source to bf16 first
- `stream_nf4_scale_cache` without `quantization: 4bit` and double quantization → refused: there are no nested NF4 scales to cache
- a non-default `stream_read_ahead` beside `stream_source: ram` → refused. The read-ahead reader belongs to the NVMe disk tier and `ram` never falls back to it, so the setting would validate, be documented, and reach nothing. The default is accepted, because a default is not a decision
- a disk-tier run whose host staging (`stream_read_ahead` layers, plus one slot each for the embedding and an untied `lm_head`) plus the resident extras will not fit the free-RAM headroom → refused by name, naming the depth to lower. Refused rather than clamped: a depth you set is a decision, and silently lowering it would hand back a slower run than the one you configured
diff --git a/src/soup_cli/trainer/stream_setup.py b/src/soup_cli/trainer/stream_setup.py
index 9b288ec0..39a88445 100644
--- a/src/soup_cli/trainer/stream_setup.py
+++ b/src/soup_cli/trainer/stream_setup.py
@@ -897,7 +897,7 @@ class StreamingSetupMixin:
refuse_if_data_parallel(self.device)
from soup_cli.utils.expert_stream import EXPERT_LAYOUT_PER_EXPERT
- from soup_cli.utils.fp8_block import fp8_block_size
+ from soup_cli.utils.fp8_block import check_source_quantization, quantization_config_of
from soup_cli.utils.layer_shard import (
PER_EXPERT_LAYOUT_ARCHS,
QUANT_NF4,
@@ -977,12 +977,14 @@ class StreamingSetupMixin:
f"base streams as {arch!r}. Use stream_expert_layout='fused'."
)
# An FP8 block-quantised base (DeepSeek-V3's published format) is dequantised by
- # the sharder. A spelling it does not dequantise, or an FP8 base on another
- # architecture, is refused here from the config alone: before any weight is
+ # the sharder. A spelling it does not dequantise, an FP8 base on another
+ # architecture, or any other declared quantiser (compressed-tensors, GPTQ, AWQ,
+ # bitsandbytes, ...) is refused here from the config alone: before any weight is
# resolved or downloaded. The disk pre-flight sizes the cache from the same
# config (the shards hold dequantised weights, the scales are not stored).
- source_quantization = getattr(model_config, "quantization_config", None)
- fp8_block = fp8_block_size(source_quantization, arch=arch)
+ # The top-level declaration, or a multimodal wrapper's text_config one.
+ source_quantization = quantization_config_of(model_config)
+ fp8_block = check_source_quantization(source_quantization, arch=arch)
on_cuda = str(self.device).startswith("cuda")
# #385 — ASK THE CARD. bf16 needs Ampere, and a T4 (Colab free), a P100
diff --git a/src/soup_cli/utils/fp8_block.py b/src/soup_cli/utils/fp8_block.py
index 455a9afb..c75ada57 100644
--- a/src/soup_cli/utils/fp8_block.py
+++ b/src/soup_cli/utils/fp8_block.py
@@ -20,6 +20,16 @@ Every other FP8 spelling is refused, naming what is supported: per-tensor scales
compressed-tensors, ue8m0 scales, static activation scales, a missing or misshapen scale,
an FP8 tensor without a scale and a scale without its tensor.
+Every other quantised source is refused here too, by name and before a byte of the cache
+is written (:func:`refuse_unsupported_quantization`, :func:`refuse_unsupported_tensor`):
+a ``quantization_config`` whose ``quant_method`` is not ``fp8`` (compressed-tensors in any
+format, GPTQ, AWQ, bitsandbytes, HQQ, ...), and a tensor stored as an integer or packed
+type, or named like a quantiser's companion (``weight_packed``, ``qweight``, ``SCB``, ...).
+A plain read would cast the stored words to floats and the run would train on them.
+The exceptions are the integer buffers a supported model really has
+(:data:`INTEGER_BUFFER_SUFFIXES`) and qwen4_exp's oMLX/oQ affine bundles, which the
+sharder dequantises itself.
+
No top-level torch: ``layer_shard`` imports this module on the light CLI path.
"""
@@ -62,7 +72,99 @@ SUPPORTED_FP8_FORMAT = (
)
-class UnsupportedFP8Error(ValueError):
+#: The tail of every refusal of a quantised source that is not an FP8 one.
+SUPPORTED_SOURCE_FORMATS = (
+ "Layer streaming cannot dequantise it: it reads plain floating-point weights "
+ "(bfloat16, float16, float32), DeepSeek-V3's block FP8 (quant_method 'fp8' with "
+ f"weight_block_size, on model_type {', '.join(FP8_BLOCK_ARCHS)}) and, on qwen4_exp "
+ "only, oMLX/oQ affine bundles. Point training.base at a bf16 or FP8-block copy of "
+ "this model, or dequantise it to bf16 first."
+)
+
+#: The safetensors dtypes a plain read may cast to the stream dtype. FP8 is planned
+#: separately (:func:`plan_fp8_block`); every other stored type is a packed or integer
+#: one that a cast would turn into garbage weights.
+FLOAT_SOURCE_DTYPES = frozenset({"BF16", "F16", "F32", "F64"})
+
+#: Integer buffers a supported architecture really carries in its checkpoint. Read by
+#: key suffix, so a wrapper prefix (``language_model.``) does not hide one:
+#:
+#: - qwen4_exp's PLE n-gram hashing tables (``nn.Buffer`` of torch.long, persistent):
+#: the sharder stores them cast and the runtime never loads them back
+#: (``layer_shard._LAYER_BUFFER_KEYS``), so the skeleton keeps their exact values;
+#: - ``position_ids``, the int64 buffer vision towers and older encoders persist.
+INTEGER_BUFFER_SUFFIXES = (
+ ".ple.ple_embedding.layer_multipliers",
+ ".ple.ple_embedding.ngram_heads_vocab_sizes",
+ ".ple.ple_embedding.ngram_heads_offsets",
+ ".position_ids",
+)
+
+_COMPRESSED_TENSORS = "compressed-tensors"
+_GPTQ_OR_AWQ = "GPTQ or AWQ (int4 weights packed into int32 'qweight' words)"
+_BNB_8BIT = "bitsandbytes LLM.int8() (int8 weights with 'SCB' row scales)"
+_BNB_4BIT = "bitsandbytes 4-bit (NF4/FP4 nibbles packed into uint8, with 'absmax')"
+#: Key suffixes that exist only in a quantiser's on-disk format, checked in this order
+#: (a longer suffix before the shorter one it ends with). ``_scale_inv`` is not here: it
+#: is DeepSeek-V3's block-FP8 scale, planned by :func:`plan_fp8_block`.
+QUANTISED_KEY_SUFFIXES: Tuple[Tuple[str, str], ...] = (
+ ("weight_packed", f"{_COMPRESSED_TENSORS} pack-quantized (int weights packed into "
+ "int32 'weight_packed' words)"),
+ ("weight_shape", f"{_COMPRESSED_TENSORS} pack-quantized ('weight_shape' records the "
+ "unpacked shape)"),
+ ("weight_global_scale", f"{_COMPRESSED_TENSORS} NVFP4"),
+ ("weight_zero_point", f"{_COMPRESSED_TENSORS} (asymmetric zero points)"),
+ ("weight_g_idx", f"{_COMPRESSED_TENSORS} (activation-order group index)"),
+ ("weight_scale", f"{_COMPRESSED_TENSORS} ('weight_scale'; DeepSeek-V3's block FP8 "
+ "spells its scale 'weight_scale_inv')"),
+ ("input_global_scale", "static activation scales (NVFP4)"),
+ ("input_scale", "static activation scales"),
+ ("output_scale", "static activation scales"),
+ ("qweight", _GPTQ_OR_AWQ),
+ ("qzeros", "GPTQ or AWQ (int32-packed 'qzeros' zero points)"),
+ ("g_idx", "GPTQ (activation-order 'g_idx')"),
+ (".SCB", _BNB_8BIT),
+ (".weight_format", _BNB_8BIT),
+ (".quant_state.bitsandbytes__nf4", _BNB_4BIT),
+ (".quant_state.bitsandbytes__fp4", _BNB_4BIT),
+ (".nested_quant_map", _BNB_4BIT),
+ (".nested_absmax", _BNB_4BIT),
+ (".quant_map", _BNB_4BIT),
+ (".absmax", _BNB_4BIT),
+ (".W_q", "HQQ (packed 'W_q')"),
+ (".codebooks", "AQLM (additive codebooks)"),
+ (".codes", "AQLM (int codes)"),
+ (".weight_scales", "EETQ (int8 weights with 'weight_scales')"),
+ ("._data", "quanto (quantised '_data')"),
+ ("._scale", "quanto (quantised '_scale')"),
+ ("_qdata", "torchao (quantised '_qdata')"),
+)
+
+#: What a stored type that is not floating point holds in a quantised checkpoint, for a
+#: tensor whose name does not already say (:data:`QUANTISED_KEY_SUFFIXES`).
+_PACKED_DTYPE_FORMATS = {
+ "I32": "int32, the word GPTQ, AWQ and compressed-tensors pack int4 weights into",
+ "U32": (
+ "uint32, the word oMLX/oQ affine (MLX) checkpoints pack quantised weights into "
+ "(layer streaming dequantises those on qwen4_exp only)"
+ ),
+ "U8": "uint8, which bitsandbytes 4-bit packs NF4/FP4 nibbles into (HQQ and MXFP4 too)",
+ "I8": "int8, an int8-quantised weight (bitsandbytes LLM.int8(), compressed-tensors, EETQ)",
+ "F4": "FP4, packed MXFP4/NVFP4 values",
+ "C64": "complex64, not a real-valued weight type",
+}
+
+#: ``quant_method`` values that are FP8 formats other than DeepSeek-V3's block FP8:
+#: refused as :class:`UnsupportedFP8Error`, with the FP8 format named.
+_FP8_FAMILY_METHODS = frozenset({"fbgemm_fp8", "mxfp8"})
+
+
+class UnsupportedQuantizedSourceError(ValueError):
+ """A quantised checkpoint layer streaming does not dequantise; the message names the
+ format, says so, and points to a bf16 or FP8-block source."""
+
+
+class UnsupportedFP8Error(UnsupportedQuantizedSourceError):
"""An FP8 checkpoint layer streaming does not dequantise; the message names the format."""
@@ -76,6 +178,10 @@ def _refuse(problem: str) -> UnsupportedFP8Error:
return UnsupportedFP8Error(f"{problem}. {SUPPORTED_FP8_FORMAT}")
+def _refuse_source(problem: str) -> UnsupportedQuantizedSourceError:
+ return UnsupportedQuantizedSourceError(f"{problem}. {SUPPORTED_SOURCE_FORMATS}")
+
+
def as_quantization_mapping(quantization_config: Any) -> Optional[Mapping[str, Any]]:
"""A config's ``quantization_config`` as a mapping, or ``None`` when there is none.
@@ -169,6 +275,175 @@ def fp8_block_size(quantization_config: Any, *, arch: str) -> Optional[Tuple[int
return int(block[0]), int(block[1])
+def _int_setting(value: Any) -> Optional[int]:
+ value = _setting(value)
+ return value if isinstance(value, int) and not isinstance(value, bool) else None
+
+
+def _compressed_tensors_detail(quant: Mapping[str, Any]) -> Tuple[str, bool]:
+ """``(detail, is_fp8)`` for a compressed-tensors config: its format and weight spec.
+
+ Read from the untrusted config defensively; only the first group's weights are named.
+ """
+ fmt = _setting(quant.get("format"))
+ parts = [f"format {_brief(fmt)}"] if fmt is not None else []
+ weights: Optional[Mapping[str, Any]] = None
+ groups = quant.get("config_groups")
+ if isinstance(groups, Mapping):
+ for group in groups.values():
+ if isinstance(group, Mapping) and isinstance(group.get("weights"), Mapping):
+ weights = group["weights"]
+ break
+ bits = kind = None
+ if weights is not None:
+ bits = _int_setting(weights.get("num_bits"))
+ kind = _setting(weights.get("type"))
+ if bits is not None and kind in ("int", "float"):
+ spec = f"{bits}-bit {kind} weights"
+ group_size = _int_setting(weights.get("group_size"))
+ if group_size is not None:
+ spec += f" in groups of {group_size}"
+ parts.append(spec)
+ is_fp8 = fmt == "float-quantized" or (kind == "float" and bits == 8)
+ return (f" ({', '.join(parts)})" if parts else ""), is_fp8
+
+
+def refuse_unsupported_quantization(quantization_config: Any) -> None:
+ """Refuse a ``quantization_config`` declaring a quantiser layer streaming cannot read.
+
+ Passes no config (``None``), a config that declares no quantiser (the oMLX/oQ affine
+ spelling,
+ ``bits`` and ``group_size`` without a ``quant_method``, whose tensors decide) and
+ ``quant_method: "fp8"``, which :func:`fp8_block_size` decides. Every other
+ ``quant_method`` is refused naming it: the ones transformers registers
+ (compressed-tensors in any format, gptq, awq, bitsandbytes, hqq, aqlm, eetq, torchao,
+ quanto, ...) and any value it does not. ``load_in_4bit`` / ``load_in_8bit`` without a method
+ is bitsandbytes, as transformers reads it. A value that is not a mapping (a string,
+ a list, a number) is refused as malformed. ``quant_method`` is matched exactly, as
+ transformers looks it up: ``FP8`` is not ``fp8``. Another FP8 format raises
+ :class:`UnsupportedFP8Error`, everything else :class:`UnsupportedQuantizedSourceError`.
+ """
+ quant = as_quantization_mapping(quantization_config)
+ if quant is None:
+ if quantization_config is None:
+ return
+ # A string, list or number declares SOMETHING; transformers cannot read it either.
+ raise _refuse_source(
+ f"config.json quantization_config is {_brief(quantization_config)}, not a "
+ f"mapping: a malformed declaration no quantiser can be read from"
+ )
+ method = _setting(quant.get("quant_method"))
+ bnb_bits = (
+ 4 if quant.get("load_in_4bit") is True
+ else 8 if quant.get("load_in_8bit") is True
+ else None
+ )
+ if method is None:
+ if bnb_bits is None:
+ return
+ raise _refuse_source(
+ f"config.json quantization_config declares load_in_{bnb_bits}bit: "
+ f"bitsandbytes pre-quantised {bnb_bits}-bit weights"
+ )
+ if method == "fp8":
+ return
+ # An unhashable value (a list) is a declared quantiser too, named as written.
+ is_fp8 = isinstance(method, str) and method in _FP8_FAMILY_METHODS
+ if method == _COMPRESSED_TENSORS:
+ detail, is_fp8 = _compressed_tensors_detail(quant)
+ elif bnb_bits is not None:
+ detail = f" ({bnb_bits}-bit)"
+ else:
+ bits = _int_setting(quant.get("bits"))
+ detail = f" ({bits}-bit)" if bits is not None else ""
+ problem = f"config.json quantization_config declares quant_method {_brief(method)}{detail}"
+ raise _refuse(problem) if is_fp8 else _refuse_source(problem)
+
+
+def check_source_quantization(
+ quantization_config: Any, *, arch: str
+) -> Optional[Tuple[int, int]]:
+ """The config-alone gate of a layer-streamed source, run before any header is read.
+
+ ``(bm, bn)`` for a supported FP8 block config (:func:`fp8_block_size`), ``None`` for
+ a config that declares no quantiser; any other declared quantisation is refused by
+ name (:func:`refuse_unsupported_quantization`). The sharder, the disk pre-flight and
+ the trainer setup all call this, and :func:`plan_fp8_block` repeats it.
+ """
+ block = fp8_block_size(quantization_config, arch=arch)
+ refuse_unsupported_quantization(quantization_config)
+ return block
+
+
+def quantised_format_of(key: str) -> Optional[str]:
+ """The quantiser a key's suffix belongs to (:data:`QUANTISED_KEY_SUFFIXES`), or None."""
+ for suffix, name in QUANTISED_KEY_SUFFIXES:
+ if key.endswith(suffix):
+ return name
+ return None
+
+
+def refuse_unsupported_tensor(key: str, stored_dtype: str) -> None:
+ """Refuse one source tensor that a plain read would cast into a wrong weight.
+
+ ``stored_dtype`` is the safetensors spelling (``I32``, ``BF16``, ...). Passes a
+ floating-point tensor with an ordinary name and an integer buffer a supported model
+ really has (:data:`INTEGER_BUFFER_SUFFIXES`). FP8 is not this function's: every caller
+ plans or refuses it first (:func:`plan_fp8_block`, ``layer_shard._refuse_fp8``).
+ Refuses every other stored type, and a floating-point tensor named like a quantiser's
+ companion (:data:`QUANTISED_KEY_SUFFIXES`). The message names the format by the suffix, or
+ else by what the stored type is used for (:data:`_PACKED_DTYPE_FORMATS`): both are
+ read off the one tensor, so every caller words the same tensor the same way.
+ """
+ dtype = str(stored_dtype).upper()
+ fmt = quantised_format_of(key)
+ if dtype in FLOAT_SOURCE_DTYPES:
+ if fmt is None:
+ return
+ raise _refuse_source(
+ f"checkpoint tensor {_brief(key)} ({_brief(stored_dtype)}) belongs to {fmt}, "
+ f"whose weights a plain read would stream still quantised"
+ )
+ if key.endswith(INTEGER_BUFFER_SUFFIXES):
+ return
+ if fmt is None:
+ fmt = _PACKED_DTYPE_FORMATS.get(dtype, "an integer or packed type")
+ raise _refuse_source(
+ f"checkpoint tensor {_brief(key)} is stored as {_brief(stored_dtype)}: {fmt}. A "
+ f"plain read would cast its stored words to floats and train on them as weights"
+ )
+
+
+def _affine_weight(key: str, tensors: Mapping[str, Any]) -> bool:
+ """``<m>.weight`` with both ``<m>.scales`` and ``<m>.biases``: an oMLX/oQ affine weight."""
+ if not key.endswith(".weight"):
+ return False
+ base = key[: -len(".weight")]
+ return base + ".scales" in tensors and base + ".biases" in tensors
+
+
+def refuse_unsupported_tensors(
+ tensors: Mapping[str, Tuple[str, Sequence[int]]],
+ plan: Optional["FP8BlockPlan"],
+ *,
+ arch: str,
+) -> None:
+ """Refuse the first tensor, in key order, that no reader of layer streaming dequantises.
+
+ ``tensors`` maps canonical keys to ``(safetensors dtype, shape)``. ``plan``'s FP8 block
+ weights and scales are dequantised by the sharder. So, on qwen4_exp, is an oMLX/oQ
+ affine weight (``layer_shard._read_oq_tensor`` checks its uint32 words); its float
+ ``.scales`` and ``.biases`` pass as any float tensor does.
+ """
+ planned = plan.weights | plan.scales if plan is not None else frozenset()
+ for key in sorted(tensors):
+ if key in planned:
+ continue
+ if arch == "qwen4_exp" and _affine_weight(key, tensors):
+ continue
+ refuse_unsupported_tensor(key, tensors[key][0])
+
+
@dataclass(frozen=True)
class FP8BlockPlan:
"""Which tensors of a checkpoint are FP8 block weights, and which are their scales.
@@ -205,7 +480,25 @@ def plan_fp8_block(
Returns ``None`` when the checkpoint holds no FP8 tensor and no block scale. The
sharder and the disk pre-flight both call this, so they agree on which keys are
dequantised and which are consumed.
+
+ It is also where every other quantised source is refused, in the same words for
+ both: a declared quantiser that is not ``fp8``
+ (:func:`refuse_unsupported_quantization`), then the first tensor no reader
+ dequantises (:func:`refuse_unsupported_tensors`).
"""
+ plan = _classify_fp8(quantization_config, tensors, arch=arch)
+ refuse_unsupported_quantization(quantization_config)
+ refuse_unsupported_tensors(tensors, plan, arch=arch)
+ return plan
+
+
+def _classify_fp8(
+ quantization_config: Any,
+ tensors: Mapping[str, Tuple[str, Sequence[int]]],
+ *,
+ arch: str,
+) -> Optional[FP8BlockPlan]:
+ """:func:`plan_fp8_block`'s FP8 half: the block plan, or the FP8 spelling refused."""
block = fp8_block_size(quantization_config, arch=arch)
scales = {key for key in tensors if key.endswith(FP8_SCALE_SUFFIX)}
weights = {
@@ -275,11 +568,35 @@ def plan_fp8_block(
return FP8BlockPlan(block=block, weights=frozenset(weights), scales=frozenset(scales))
-def read_checkpoint_quantization_config(weights_dir: str) -> Optional[Mapping[str, Any]]:
+def quantization_config_of(config: Any) -> Any:
+ """A model config's ``quantization_config``: its own, else its ``text_config``'s.
+
+ ``config`` is a ``config.json`` mapping or a transformers config object. A multimodal
+ wrapper can carry the declaration on its text sub-config only; the top level wins
+ when both are present, as it does for transformers' own loader. The value is
+ returned as found, so :func:`check_source_quantization` refuses a malformed one.
+ """
+
+ def _get(owner: Any, name: str) -> Any:
+ if isinstance(owner, Mapping):
+ return owner.get(name)
+ return getattr(owner, name, None)
+
+ own = _get(config, "quantization_config")
+ if own is not None:
+ return own
+ # A missing or non-config text_config (None, a string) has no such attribute: None.
+ return _get(_get(config, "text_config"), "quantization_config")
+
+
+def read_checkpoint_quantization_config(weights_dir: str) -> Any:
"""``quantization_config`` from ``config.json`` beside the weights, or ``None``.
- ``None`` when there is no regular, readable, size-bounded ``config.json`` or it has no
- such mapping: :func:`plan_fp8_block` then refuses an FP8 checkpoint by saying so.
+ ``None`` when there is no regular, readable, size-bounded ``config.json`` or it
+ declares none (at the top level or under ``text_config``,
+ :func:`quantization_config_of`): :func:`plan_fp8_block` then refuses an FP8
+ checkpoint by saying so. A declaration that is not a mapping is returned as it is,
+ for :func:`check_source_quantization` to refuse as malformed.
"""
path = os.path.join(os.path.realpath(os.path.expanduser(weights_dir)), "config.json")
if not os.path.isfile(path) or os.path.islink(path):
@@ -291,8 +608,8 @@ def read_checkpoint_quantization_config(weights_dir: str) -> Optional[Mapping[st
payload = json.load(handle)
except (OSError, UnicodeDecodeError, ValueError, RecursionError):
return None
- quant = payload.get("quantization_config") if isinstance(payload, dict) else None
- return quant if isinstance(quant, dict) else None
+ # Valid JSON that is not an object (a list, a number) has no such key: None.
+ return quantization_config_of(payload)
def dequantize_fp8_block(
diff --git a/src/soup_cli/utils/layer_shard.py b/src/soup_cli/utils/layer_shard.py
index bb5841df..0944c9ea 100644
--- a/src/soup_cli/utils/layer_shard.py
+++ b/src/soup_cli/utils/layer_shard.py
@@ -56,10 +56,11 @@ from soup_cli.utils.fp8_block import (
SUPPORTED_FP8_FORMAT,
FP8BlockPlan,
UnsupportedFP8Error,
+ check_source_quantization,
dequantize_fp8_block,
- fp8_block_size,
plan_fp8_block,
read_checkpoint_quantization_config,
+ refuse_unsupported_tensor,
)
logger = logging.getLogger(__name__)
@@ -1000,6 +1001,11 @@ class SourceHeaderError(ValueError):
"""
+#: Stored types safetensors defines that ``safetensors_reader`` has no spelling for and a
+#: quantiser writes: packed or integer ones. FP8 spellings are left to the FP8 plan, and
+#: anything else (C64, a corrupt name) stays an unreadable header.
+_SAFETENSORS_ONLY_DTYPES = frozenset({"U16", "U32", "U64", "F4", "F6_E2M3", "F6_E3M2"})
+
#: What reading and parsing one header can raise: a missing or unreadable file, a
#: malformed header (``ValueError``), a null or nested dimension or offset
#: (``TypeError``), an infinite one (``OverflowError``) and JSON nested deeper than
@@ -1016,13 +1022,27 @@ def _read_source_tensors(
spelled twice, or more than ``_MAX_TOTAL_TENSORS`` across the files, is
refused the way :func:`shard_checkpoint` refuses it.
"""
- from soup_cli.utils.safetensors_reader import RAW_DTYPES, read_header
+ from soup_cli.utils.safetensors_reader import (
+ RAW_DTYPES,
+ UnsupportedDtypeError,
+ read_header,
+ )
shapes: Dict[str, Tuple[str, Tuple[int, ...]]] = {}
spelled: Dict[str, str] = {}
for path in shard_paths:
try:
header = read_header(path)
+ except UnsupportedDtypeError as exc:
+ # A packed or integer type this reader has no spelling for (U32, U16, F4...):
+ # the sharder reads the header through safetensors and refuses that tensor
+ # (``plan_fp8_block``), so refuse it here in its words, before any copy.
+ # FP8 spellings it lacks (F8_E8M0) are the FP8 plan's to word: unread here.
+ if exc.dtype in _SAFETENSORS_ONLY_DTYPES:
+ refuse_unsupported_tensor(_canonical_stream_key(exc.tensor), exc.dtype)
+ raise SourceHeaderError(
+ f"cannot read the safetensors header of {path}: {exc}"
+ ) from exc
except _HEADER_READ_ERRORS as exc:
raise SourceHeaderError(
f"cannot read the safetensors header of {path}: {exc}"
@@ -1124,8 +1144,9 @@ def estimate_shard_cache_bytes(
"""
if arch == "qwen4_exp":
return None
- # The config alone decides an unsupported FP8 spelling: refused before any header.
- fp8_block_size(quantization_config, arch=arch)
+ # The config alone decides an unsupported FP8 spelling, or another declared
+ # quantiser: refused before any header, as the sharder refuses it.
+ check_source_quantization(quantization_config, arch=arch)
if dtype not in _SUPPORTED_DTYPES:
raise ValueError(
f"unsupported dtype {dtype!r} for layer streaming; "
@@ -1744,6 +1765,13 @@ def shard_checkpoint(
are stacked or written to their experts file, cast to the stream dtype and then
stored by the rules above. The scales are consumed and never stored. Any other
FP8 spelling is refused before anything is written.
+
+ Every other quantised source is refused too (``fp8_block.check_source_quantization``
+ and the header plan, :func:`~soup_cli.utils.fp8_block.plan_fp8_block`). The source
+ is checked first, from its ``config.json`` and headers alone, before ``out_dir`` or
+ a stripe folder is made, a cache is looked up or an index is quarantined: a refused
+ source creates and renames nothing, and a cache older code sharded from it is not
+ reused.
"""
if expert_layout not in ("", EXPERT_LAYOUT_PER_EXPERT):
raise ValueError(
@@ -1784,82 +1812,16 @@ def shard_checkpoint(
fp32_layer_keys = layer_buffer_keys(arch)
drop_extra_layers = arch == "deepseek_v3" and num_hidden_layers is not None
shards = _discover_safetensors(weights_dir)
- resolved_out = _validate_out_dir(out_dir)
-
- from soup_cli.utils.stripe_roots import (
- STRIPE_DIRS_ENV,
- StripeRootError,
- layer_roots_for,
- primary_cache_identity,
- secure_stripe_folder,
- stripe_folder_problem,
- validate_stripe_root,
- )
-
- # Bound our own writes (syntax, existence, symlink, overlap). The distinct-volume and
- # NVMe rules ran once at setup (resolve_stripe_roots); the ~9 s probe is not repeated.
- validated: List[str] = []
- for root in stripe_roots:
- validated.append(
- validate_stripe_root(
- root, primary_root=os.path.dirname(resolved_out), accepted=validated
- )
- )
- stripe = tuple(validated)
- # Before anything reads, writes or deletes in a stripe folder: it must not be a link or
- # junction, and it is made (or re-made) owner-only — on the reuse path too, since that is
- # the path that trusts files already on the drive. A folder that fails refuses the run.
- shard_dirs = stripe_dirs(resolved_out, stripe)
- for directory, root in zip(shard_dirs[1:], stripe):
- secure_stripe_folder(directory, root)
-
- source_files = checkpoint_source_components(
- weights_dir,
- _source_file_components(shards),
- include_config=source_identity_includes_config(arch),
- )
- fingerprint = _fingerprint_components(source_files)
- if not force:
- cached, miss_reason = inspect_shard_cache(
- resolved_out,
- dtype,
- fingerprint,
- source_files,
- quant,
- double_quant,
- device_kind,
- external_mode,
- stripe_roots=stripe,
- expert_layout=expert_layout,
- )
- if cached is not None:
- if notify is not None:
- _notify_unindexed_cache_files(resolved_out, cached, notify)
- return cached
- if notify is not None:
- from soup_cli.utils.terminal import for_terminal
-
- # The reason can carry paths from the index, the variable and stripe drives: printed
- # as text, never as markup or raw control bytes.
- notify(f"[yellow]Re-sharding layer cache:[/] {for_terminal(miss_reason)}.")
- _notify_orphaned_stripes(resolved_out, stripe, notify)
- if _content_change_requires_index_quarantine(
- resolved_out,
- dtype=dtype,
- fingerprint=fingerprint,
- quant=quant,
- double_quant=double_quant,
- quant_device=device_kind,
- external_mode=external_mode,
- expert_layout=expert_layout,
- ):
- _quarantine_shard_index(resolved_out)
-
from safetensors import safe_open
- # An FP8 spelling the config alone rules out is refused before any header is read.
+ # Every check of the SOURCE comes first, before the out dir is made, a stripe
+ # folder secured, a cache looked up or an index quarantined: a refused source
+ # creates and renames nothing, and a cache sharded from it by older code is not
+ # reused (its hit would return before any later check). Headers only, no tensor.
+ # An FP8 spelling, or another quantiser, that the config alone rules out is refused
+ # before any header is read.
source_quantization = read_checkpoint_quantization_config(weights_dir)
- fp8_block_size(source_quantization, arch=arch)
+ check_source_quantization(source_quantization, arch=arch)
# pass 1 — build key -> shard without materialising a single tensor
where: Dict[str, Tuple[str, str]] = {}
@@ -1924,12 +1886,6 @@ def shard_checkpoint(
if match:
layer_ids.add(int(match.group(1)))
- # Before any byte is read or written: every FP8 tensor must be a block weight with
- # its scale, every scale must sit beside one (the disk pre-flight runs the same plan).
- fp8_plan = plan_fp8_block(source_quantization, source_tensors, arch=arch)
- consumed = _fp8_consumed_keys(fp8_plan)
- del source_tensors
-
oq_config = None
if saw_oq_companion:
from soup_cli.utils.oq_affine import load_affine_quant_config
@@ -1952,6 +1908,88 @@ def shard_checkpoint(
if (match := _LAYER_RE.match(key)) is not None
}
+ # Before any byte is read or written: every FP8 tensor must be a block weight with
+ # its scale, every scale must sit beside one, and no tensor read below may be a
+ # packed or integer one a plain read would cast (the disk pre-flight runs the same
+ # plan). Over the keys this sharder reads: an oQ bundle's vision and MTP weights
+ # are dropped above, never read.
+ fp8_plan = plan_fp8_block(
+ source_quantization, {key: source_tensors[key] for key in where}, arch=arch
+ )
+ consumed = _fp8_consumed_keys(fp8_plan)
+ del source_tensors
+
+ resolved_out = _validate_out_dir(out_dir)
+
+ from soup_cli.utils.stripe_roots import (
+ STRIPE_DIRS_ENV,
+ StripeRootError,
+ layer_roots_for,
+ primary_cache_identity,
+ secure_stripe_folder,
+ stripe_folder_problem,
+ validate_stripe_root,
+ )
+
+ # Bound our own writes (syntax, existence, symlink, overlap). The distinct-volume and
+ # NVMe rules ran once at setup (resolve_stripe_roots); the ~9 s probe is not repeated.
+ validated: List[str] = []
+ for root in stripe_roots:
+ validated.append(
+ validate_stripe_root(
+ root, primary_root=os.path.dirname(resolved_out), accepted=validated
+ )
+ )
+ stripe = tuple(validated)
+ # Before anything reads, writes or deletes in a stripe folder: it must not be a link or
+ # junction, and it is made (or re-made) owner-only — on the reuse path too, since that is
+ # the path that trusts files already on the drive. A folder that fails refuses the run.
+ shard_dirs = stripe_dirs(resolved_out, stripe)
+ for directory, root in zip(shard_dirs[1:], stripe):
+ secure_stripe_folder(directory, root)
+
+ source_files = checkpoint_source_components(
+ weights_dir,
+ _source_file_components(shards),
+ include_config=source_identity_includes_config(arch),
+ )
+ fingerprint = _fingerprint_components(source_files)
+ if not force:
+ cached, miss_reason = inspect_shard_cache(
+ resolved_out,
+ dtype,
+ fingerprint,
+ source_files,
+ quant,
+ double_quant,
+ device_kind,
+ external_mode,
+ stripe_roots=stripe,
+ expert_layout=expert_layout,
+ )
+ if cached is not None:
+ if notify is not None:
+ _notify_unindexed_cache_files(resolved_out, cached, notify)
+ return cached
+ if notify is not None:
+ from soup_cli.utils.terminal import for_terminal
+
+ # The reason can carry paths from the index, the variable and stripe drives: printed
+ # as text, never as markup or raw control bytes.
+ notify(f"[yellow]Re-sharding layer cache:[/] {for_terminal(miss_reason)}.")
+ _notify_orphaned_stripes(resolved_out, stripe, notify)
+ if _content_change_requires_index_quarantine(
+ resolved_out,
+ dtype=dtype,
+ fingerprint=fingerprint,
+ quant=quant,
+ double_quant=double_quant,
+ quant_device=device_kind,
+ external_mode=external_mode,
+ expert_layout=expert_layout,
+ ):
+ _quarantine_shard_index(resolved_out)
+
if expert_layout and not any(_PER_EXPERT_RE.match(key) for key in where):
raise ValueError(
f"expert_layout={expert_layout!r} found no per-expert routed weights "
@@ -2738,12 +2776,17 @@ def _refuse_fp8(key: str, stored_dtype: str) -> None:
"""The backstop under every plain read: an FP8 tensor or block scale that reaches a
cast was not dequantised by an accepted :class:`FP8BlockPlan`. A plain cast keeps
the raw e4m3 values and drops the scales, so the run would train on wrong weights
- while the resident load (which dequantises) looks fine."""
+ while the resident load (which dequantises) looks fine.
+
+ So is any other tensor that is not plain floating point, or that a quantiser
+ named (:func:`~soup_cli.utils.fp8_block.refuse_unsupported_tensor`): the header
+ plan refuses those first, and this is what still stands if a path skips it."""
if stored_dtype.upper().startswith("F8") or key.endswith("_scale_inv"):
raise UnsupportedFP8Error(
f"checkpoint tensor {key!r} is FP8 ({stored_dtype}) or an FP8 block scale "
f"that would be cast without its scales. {SUPPORTED_FP8_FORMAT}"
)
+ refuse_unsupported_tensor(key, stored_dtype)
def _read_source_tensor(
diff --git a/src/soup_cli/utils/safetensors_reader.py b/src/soup_cli/utils/safetensors_reader.py
index ddd13860..29f59f97 100644
--- a/src/soup_cli/utils/safetensors_reader.py
+++ b/src/soup_cli/utils/safetensors_reader.py
@@ -142,6 +142,23 @@ class TensorRange:
return self.end - self.start
+class UnsupportedDtypeError(ValueError):
+ """A header names a tensor in a dtype this reader does not read (``U32``, ``F4``, ...).
+
+ A ``ValueError`` like every other malformed-header refusal here; its own type so the
+ layer-stream disk pre-flight can refuse that tensor in the sharder's words
+ (``layer_shard._read_source_tensors``) instead of treating the header as unreadable.
+ ``tensor`` and ``dtype`` are the header's own (untrusted) strings. Both have defaults
+ so the exception rebuilds from its message alone, as ``pickle`` and ``copy`` rebuild
+ it (its attributes then come back from its ``__dict__``).
+ """
+
+ def __init__(self, message: str, *, tensor: str = "", dtype: object = None) -> None:
+ super().__init__(message)
+ self.tensor = tensor
+ self.dtype = dtype
+
+
def read_header(path: str) -> Dict[str, TensorRange]:
"""Every tensor in ``path``, with absolute byte ranges. Never maps the file."""
return read_header_with_identity(path)[0]
@@ -185,9 +202,11 @@ def read_header_with_identity(path: str) -> Tuple[Dict[str, TensorRange], ShardI
raise ValueError(f"{path}: entry {name!r} is not an object")
raw_dtype = meta.get("dtype")
if raw_dtype not in _DTYPES:
- raise ValueError(
+ raise UnsupportedDtypeError(
f"{path}: tensor {name!r} has unsupported dtype {raw_dtype!r}; "
- f"supported: {', '.join(sorted(_DTYPES))}"
+ f"supported: {', '.join(sorted(_DTYPES))}",
+ tensor=name,
+ dtype=raw_dtype,
)
dtype = _DTYPES[raw_dtype]
# No default: ``dict.get(key, default)`` substitutes only when the KEY is
diff --git a/tests/test_fp8_block_streaming.py b/tests/test_fp8_block_streaming.py
index d6469984..297c95bc 100644
--- a/tests/test_fp8_block_streaming.py
+++ b/tests/test_fp8_block_streaming.py
@@ -643,7 +643,9 @@ def _mutated_checkpoint(tmp_path, spelling):
elif spelling == "per-tensor-config":
quant = {"quant_method": "fp8", "weight_block_size": None}
elif spelling == "compressed-tensors":
- quant = {"quant_method": "compressed-tensors"}
+ # compressed-tensors' own FP8 spelling: a bare quant_method no longer says FP8,
+ # and is refused as a quantised source of unknown format.
+ quant = {"quant_method": "compressed-tensors", "format": "float-quantized"}
elif spelling == "no-config":
quant = None
elif spelling == "llama":
@@ -739,7 +741,9 @@ def test_the_estimate_refuses_an_fp8_config_spelling_before_reading_a_header(tmp
(b"", None),
(b"not json", None),
(b"[1, 2]", None),
- (b'{"quantization_config": "fp8"}', None),
+ # Returned as found since the review round of the packed-quant refusal: the
+ # gate refuses a declaration that is not a mapping as malformed.
+ (b'{"quantization_config": "fp8"}', "fp8"),
(b'{"model_type": "deepseek_v3"}', None),
(b'{"quantization_config": {"quant_method": "fp8"}}', {"quant_method": "fp8"}),
],
@@ -1499,7 +1503,9 @@ def test_the_plain_read_backstop_refuses_every_fp8_spelling(key, dtype):
_refuse_fp8(key, dtype)
[email protected]("dtype", ["BF16", "F16", "F32", "U8"])
+# U8 used to pass here too: the backstop now refuses every integer or packed type
+# (tests/test_stream_refuses_packed_quant.py), so a plain tensor is a floating one.
[email protected]("dtype", ["BF16", "F16", "F32", "F64"])
def test_the_plain_read_backstop_passes_a_plain_tensor(dtype):
from soup_cli.utils.layer_shard import _refuse_fp8
diff --git a/tests/test_stream_refuses_packed_quant.py b/tests/test_stream_refuses_packed_quant.py
new file mode 100644
index 00000000..27c4f5d3
--- /dev/null
+++ b/tests/test_stream_refuses_packed_quant.py
@@ -0,0 +1,1306 @@
+"""Layer streaming refuses, by name and before a byte is written, a source it cannot read.
+
+Kimi-K2-Thinking ships its routed experts as compressed-tensors ``pack-quantized`` INT4:
+``quantization_config.quant_method: "compressed-tensors"`` and, per linear,
+``<prefix>.weight_packed`` (int32 words, eight int4 values each), ``<prefix>.weight_scale``
+and ``<prefix>.weight_shape`` (int64). On ``model_type: deepseek_v3`` the sharder
+accepted it: ``plan_fp8_block`` refused compressed-tensors only beside FP8 tensors, so it
+cast every int32 word and every int64 shape to the stream dtype, wrote the whole cache,
+and the streamed build then failed with "shard is missing decoder weights". A source
+whose names still match (bitsandbytes LLM.int8(): an int8 ``weight`` plus an ``SCB``)
+did not fail at all: the int8 codes were streamed as weights and trained on.
+
+Refused now, in one shared path (``utils/fp8_block.py``, where #2061 put the FP8 one):
+
+- a ``quantization_config`` declaring any ``quant_method`` but ``fp8``
+ (:func:`check_source_quantization` from the config alone; :func:`plan_fp8_block`
+ again over the headers, which the sharder and the disk pre-flight both run);
+- a tensor stored as an integer or packed type, or named like a quantiser's companion
+ (:func:`refuse_unsupported_tensor`), in the header plan and under every plain read.
+
+Kept: plain floating point, DeepSeek-V3's block FP8, qwen4_exp's oMLX/oQ affine bundles,
+and the integer buffers a supported model really has (qwen4_exp's PLE hashing tables).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import types
+
+import pytest
+
+_TAIL = "Layer streaming cannot dequantise it"
+_POINTER = "Point training.base at a bf16 or FP8-block copy of this model"
+_FP8_TAIL = "DeepSeek-V3's block FP8"
+
+#: Kimi-K2-Thinking's own quantization_config (text of its config.json, 2026-10).
+K2_THINKING_QUANT = {
+ "config_groups": {
+ "group_0": {
+ "input_activations": None,
+ "output_activations": None,
+ "targets": ["Linear"],
+ "weights": {
+ "actorder": None,
+ "block_structure": None,
+ "dynamic": False,
+ "group_size": 32,
+ "num_bits": 4,
+ "observer": "minmax",
+ "observer_kwargs": {},
+ "strategy": "group",
+ "symmetric": True,
+ "type": "int",
+ },
+ }
+ },
+ "format": "pack-quantized",
+ "ignore": [
+ "lm_head",
+ "re:.*self_attn.*",
+ "re:.*shared_experts.*",
+ "re:.*mlp\\.(gate|up|gate_up|down)_proj.*",
+ ],
+ "kv_cache_scheme": None,
+ "quant_method": "compressed-tensors",
+ "quantization_status": "compressed",
+}
+K2_NEEDLE = (
+ "quant_method 'compressed-tensors' (format 'pack-quantized', 4-bit int weights in "
+ "groups of 32)"
+)
+DEEPSEEK_FP8 = {
+ "activation_scheme": "dynamic",
+ "fmt": "e4m3",
+ "quant_method": "fp8",
+ "weight_block_size": [128, 128],
+}
+
+HIDDEN, INTER, VOCAB, EXPERTS, LAYERS = 64, 32, 16, 2, 2
+
+
+# ==========================================================================
+# synthetic checkpoints (real safetensors files in tmp_path)
+# ==========================================================================
+def _dense_state(prefix="model."):
+ """A tiny llama-shaped bf16 state; ``prefix`` spells a wrapper (``language_model.``)."""
+ import torch
+
+ generator = torch.Generator().manual_seed(5)
+
+ def normal(*shape):
+ return torch.randn(*shape, generator=generator).to(torch.bfloat16)
+
+ state = {
+ f"{prefix}embed_tokens.weight": normal(VOCAB, HIDDEN),
+ f"{prefix}norm.weight": normal(HIDDEN),
+ "lm_head.weight": normal(VOCAB, HIDDEN),
+ }
+ for layer in range(LAYERS):
+ base = f"{prefix}layers.{layer}."
+ state[base + "input_layernorm.weight"] = normal(HIDDEN)
+ state[base + "self_attn.o_proj.weight"] = normal(HIDDEN, HIDDEN)
+ state[base + "mlp.down_proj.weight"] = normal(HIDDEN, INTER)
+ return state
+
+
+def _k2_state(prefix="model."):
+ """Kimi-K2-Thinking's layout on a tiny DeepSeek-V3: bf16 attention, router and norms,
+ float32 router bias and rotary buffer, compressed-tensors INT4 routed experts."""
+ import torch
+
+ generator = torch.Generator().manual_seed(7)
+ state = {
+ f"{prefix}embed_tokens.weight": torch.randn(VOCAB, HIDDEN).to(torch.bfloat16),
+ f"{prefix}norm.weight": torch.ones(HIDDEN, dtype=torch.bfloat16),
+ "lm_head.weight": torch.randn(VOCAB, HIDDEN).to(torch.bfloat16),
+ }
+ for layer in range(LAYERS):
+ base = f"{prefix}layers.{layer}."
+ state[base + "input_layernorm.weight"] = torch.ones(HIDDEN, dtype=torch.bfloat16)
+ state[base + "self_attn.o_proj.weight"] = torch.randn(HIDDEN, HIDDEN).to(
+ torch.bfloat16
+ )
+ state[base + "self_attn.rotary_emb.inv_freq"] = torch.ones(4)
+ state[base + "mlp.gate.weight"] = torch.randn(EXPERTS, HIDDEN).to(torch.bfloat16)
+ state[base + "mlp.gate.e_score_correction_bias"] = torch.zeros(EXPERTS)
+ for expert in range(EXPERTS):
+ for name, (rows, cols) in (
+ ("gate_proj", (INTER, HIDDEN)),
+ ("up_proj", (INTER, HIDDEN)),
+ ("down_proj", (HIDDEN, INTER)),
+ ):
+ key = base + f"mlp.experts.{expert}.{name}."
+ state[key + "weight_packed"] = torch.randint(
+ -(2**31), 2**31 - 1, (rows, cols // 8), dtype=torch.int32,
+ generator=generator,
+ )
+ state[key + "weight_scale"] = torch.rand(
+ rows, cols // 32, generator=generator
+ ).to(torch.bfloat16)
+ state[key + "weight_shape"] = torch.tensor([rows, cols], dtype=torch.int64)
+ return state
+
+
+def _write(directory, state, *, quant=None, model_type="deepseek_v3"):
+ from safetensors.torch import save_file
+
+ directory.mkdir(parents=True, exist_ok=True)
+ save_file(state, str(directory / "model.safetensors"))
+ config = {"model_type": model_type, "num_hidden_layers": LAYERS}
+ if quant is not None:
+ config["quantization_config"] = quant
+ (directory / "config.json").write_text(json.dumps(config), encoding="utf-8")
+ return str(directory)
+
+
+def _shard(weights, out, *, arch="deepseek_v3"):
+ from soup_cli.utils.layer_shard import shard_checkpoint
+
+ kwargs = {"num_hidden_layers": LAYERS} if arch == "deepseek_v3" else {}
+ return shard_checkpoint(weights, str(out), dtype="bfloat16", arch=arch, **kwargs)
+
+
+def _estimate(weights, *, arch="deepseek_v3"):
+ from soup_cli.utils.fp8_block import read_checkpoint_quantization_config
+ from soup_cli.utils.layer_shard import _discover_safetensors, estimate_shard_cache_bytes
+
+ return estimate_shard_cache_bytes(
+ _discover_safetensors(weights), dtype="bfloat16", arch=arch,
+ num_hidden_layers=LAYERS if arch == "deepseek_v3" else None,
+ quantization_config=read_checkpoint_quantization_config(weights),
+ )
+
+
+def _refusals(tmp_path, weights, *, arch="deepseek_v3"):
+ """(sharder message, estimator message); asserts the sharder wrote nothing."""
+ out = tmp_path / "shards"
+ with pytest.raises(ValueError) as sharder:
+ _shard(weights, out, arch=arch)
+ assert not out.exists() or not os.listdir(out)
+ with pytest.raises(ValueError) as estimator:
+ _estimate(weights, arch=arch)
+ return str(sharder.value), str(estimator.value)
+
+
+# ==========================================================================
+# the reported source: Kimi-K2-Thinking's compressed-tensors INT4 on deepseek_v3
+# ==========================================================================
+def test_a_k2_thinking_int4_source_is_refused_before_a_byte_is_written(tmp_path):
+ weights = _write(tmp_path / "k2", _k2_state(), quant=K2_THINKING_QUANT)
+ sharder, estimator = _refusals(tmp_path, weights)
+ assert K2_NEEDLE in sharder
+ assert _TAIL in sharder and _POINTER in sharder
+ assert estimator == sharder
+
+
+def test_the_k2_refusal_is_the_shared_quantised_source_error_not_an_fp8_one(tmp_path):
+ from soup_cli.utils.fp8_block import UnsupportedFP8Error, UnsupportedQuantizedSourceError
+
+ weights = _write(tmp_path / "k2", _k2_state(), quant=K2_THINKING_QUANT)
+ with pytest.raises(UnsupportedQuantizedSourceError) as caught:
+ _shard(weights, tmp_path / "s")
+ assert not isinstance(caught.value, UnsupportedFP8Error)
+ assert issubclass(UnsupportedFP8Error, UnsupportedQuantizedSourceError)
+
+
+ "prefix", ["model.", "language_model.model.", "model.language_model."],
+ ids=["plain", "language_model", "vlm"],
+)
+def test_without_its_config_the_packed_tensors_still_refuse_in_one_voice(tmp_path, prefix):
+ """No quantization_config at all (stripped, or a hand conversion): the int32 words
+ are refused by their own name and type, whatever wrapper prefix spells them."""
+ weights = _write(tmp_path / "k2", _k2_state(prefix))
+ sharder, estimator = _refusals(tmp_path, weights)
+ assert "model.layers.0.mlp.experts.0.down_proj.weight_packed" in sharder
+ assert "is stored as 'I32': compressed-tensors pack-quantized" in sharder
+ assert _TAIL in sharder and _POINTER in sharder
+ assert estimator == sharder
+
+
+def test_the_setup_refuses_a_k2_base_before_resolving_its_weights(tmp_path, monkeypatch):
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ def _must_not_resolve(*_args, **_kwargs):
+ raise AssertionError("weights resolved for a base that cannot stream")
+
+ model_cfg = types.SimpleNamespace(
+ model_type="deepseek_v3", hidden_size=HIDDEN, num_hidden_layers=LAYERS,
+ vocab_size=VOCAB, intermediate_size=INTER, quantization_config=K2_THINKING_QUANT,
+ )
+ with pytest.raises(ValueError) as caught:
+ _drive_qwen4_streaming_setup(
+ tmp_path, monkeypatch, resolve_weights=_must_not_resolve, arch="deepseek_v3",
+ model_cfg=model_cfg,
+ )
+ assert K2_NEEDLE in str(caught.value) and _TAIL in str(caught.value)
+
+
+# ==========================================================================
+# the config gate: every declared quantiser but fp8
+# ==========================================================================
+_CT_GROUP = {"group_0": {"targets": ["Linear"], "weights": {"num_bits": 8, "type": "int"}}}
+_CONFIG_SPELLINGS = {
+ "k2-thinking": (K2_THINKING_QUANT, K2_NEEDLE, False),
+ "ct-int8": (
+ {"quant_method": "compressed-tensors", "format": "int-quantized",
+ "config_groups": _CT_GROUP},
+ "(format 'int-quantized', 8-bit int weights)", False,
+ ),
+ "ct-nvfp4": (
+ {"quant_method": "compressed-tensors", "format": "nvfp4-pack-quantized"},
+ "(format 'nvfp4-pack-quantized')", False,
+ ),
+ "ct-fp8": (
+ {"quant_method": "compressed-tensors", "format": "float-quantized"},
+ "(format 'float-quantized')", True,
+ ),
+ "ct-fp8-by-group": (
+ {"quant_method": "compressed-tensors",
+ "config_groups": {"g": {"weights": {"num_bits": 8, "type": "float"}}}},
+ "(8-bit float weights)", True,
+ ),
+ "ct-bare": ({"quant_method": "compressed-tensors"}, "'compressed-tensors'.", False),
+ "gptq": ({"quant_method": "gptq", "bits": 4, "group_size": 128}, "'gptq' (4-bit)", False),
+ "awq": ({"quant_method": "awq", "bits": 4, "version": "gemm"}, "'awq' (4-bit)", False),
+ "bnb-4bit": (
+ {"quant_method": "bitsandbytes", "load_in_4bit": True,
+ "bnb_4bit_quant_type": "nf4"},
+ "'bitsandbytes' (4-bit)", False,
+ ),
+ "bnb-8bit": (
+ {"quant_method": "bitsandbytes", "load_in_8bit": True}, "'bitsandbytes' (8-bit)",
+ False,
+ ),
+ "bnb-without-method": (
+ {"load_in_4bit": True}, "declares load_in_4bit: bitsandbytes pre-quantised 4-bit",
+ False,
+ ),
+ "hqq": ({"quant_method": "hqq", "nbits": 4}, "'hqq'", False),
+ "aqlm": ({"quant_method": "aqlm", "nbits_per_codebook": 16}, "'aqlm'", False),
+ "eetq": ({"quant_method": "eetq", "weights": "int8"}, "'eetq'", False),
+ "torchao": ({"quant_method": "torchao", "quant_type": {}}, "'torchao'", False),
+ "quanto": ({"quant_method": "quanto", "weights": "int8"}, "'quanto'", False),
+ "mxfp4": ({"quant_method": "mxfp4"}, "'mxfp4'", False),
+ "fbgemm-fp8": ({"quant_method": "fbgemm_fp8"}, "'fbgemm_fp8'", True),
+ "mxfp8": ({"quant_method": "mxfp8"}, "'mxfp8'", True),
+ "unknown": ({"quant_method": "my-own-quantizer"}, "'my-own-quantizer'", False),
+ "not-a-string": ({"quant_method": 5}, "quant_method 5.", False),
+ "empty-string": ({"quant_method": ""}, "quant_method ''.", False),
+ "list": ({"quant_method": ["gptq"]}, "quant_method ['gptq'].", False),
+}
+
+
[email protected]("spelling", sorted(_CONFIG_SPELLINGS))
+def test_every_declared_quantiser_but_fp8_is_refused_by_name(spelling):
+ from soup_cli.utils.fp8_block import (
+ UnsupportedFP8Error,
+ UnsupportedQuantizedSourceError,
+ check_source_quantization,
+ )
+
+ config, needle, is_fp8 = _CONFIG_SPELLINGS[spelling]
+ with pytest.raises(UnsupportedQuantizedSourceError) as caught:
+ check_source_quantization(config, arch="deepseek_v3")
+ message = str(caught.value)
+ assert needle in message
+ assert isinstance(caught.value, UnsupportedFP8Error) is is_fp8
+ assert (_FP8_TAIL if is_fp8 else _POINTER) in message
+ assert "Dequantise" in message or "dequantise" in message
+
+
+def test_every_quantiser_transformers_registers_but_fp8_is_refused():
+ """The registry of the installed transformers (5.17: 27 names), not a copy of it."""
+ pytest.importorskip("transformers")
+ from transformers.quantizers.auto import AUTO_QUANTIZATION_CONFIG_MAPPING
+
+ from soup_cli.utils.fp8_block import (
+ UnsupportedQuantizedSourceError,
+ check_source_quantization,
+ )
+
+ methods = sorted(set(AUTO_QUANTIZATION_CONFIG_MAPPING) | {"bitsandbytes"})
+ assert {"compressed-tensors", "gptq", "awq", "bitsandbytes_4bit", "hqq"} <= set(methods)
+ accepted = []
+ for method in methods:
+ try:
+ check_source_quantization({"quant_method": method}, arch="llama")
+ except UnsupportedQuantizedSourceError as exc:
+ assert repr(method) in str(exc), method
+ else:
+ accepted.append(method)
+ assert accepted == []
+ # 'fp8' is accepted only as DeepSeek-V3's block format, on deepseek_v3:
+ assert check_source_quantization(DEEPSEEK_FP8, arch="deepseek_v3") == (128, 128)
+
+
+def test_a_transformers_quantization_config_object_is_read_too():
+ transformers = pytest.importorskip("transformers")
+ from soup_cli.utils.fp8_block import (
+ UnsupportedQuantizedSourceError,
+ check_source_quantization,
+ )
+
+ with pytest.raises(UnsupportedQuantizedSourceError, match=r"'bitsandbytes' \(4-bit\)"):
+ check_source_quantization(
+ transformers.BitsAndBytesConfig(load_in_4bit=True), arch="llama"
+ )
+
+
+ "config",
+ [
+ None,
+ {},
+ {"bits": 4, "group_size": 32, "mode": "affine"},
+ {"group_size": 64, "bits": 4, "model.layers.0.mlp.gate": {"bits": 8, "group_size": 64}},
+ {"quant_method": None},
+ {"load_in_4bit": False, "load_in_8bit": False},
+ ],
+ ids=["none", "empty", "oq-affine", "mlx-overrides", "null-method", "bnb-flags-off"],
+)
+def test_a_config_that_declares_no_quantiser_passes_the_gate(config):
+ """The oMLX/oQ affine spelling declares no quant_method: its tensors decide."""
+ from soup_cli.utils.fp8_block import check_source_quantization
+
+ assert check_source_quantization(config, arch="qwen4_exp") is None
+
+
+def _corrupt_checkpoint_with_config(directory, quantization_config):
+ """A config naming a refused quantiser beside weights no reader could open."""
+ directory.mkdir(parents=True)
+ (directory / "model.safetensors").write_bytes(b"\xff" * 64)
+ config = {"model_type": "deepseek_v3", "quantization_config": quantization_config}
+ (directory / "config.json").write_text(json.dumps(config), encoding="utf-8")
+ return str(directory)
+
+
[email protected]("spelling", ["k2-thinking", "gptq", "bnb-4bit", "ct-fp8"])
+def test_the_config_alone_refuses_before_any_header_in_every_caller(tmp_path, spelling):
+ from soup_cli.utils.fp8_block import check_source_quantization
+ from soup_cli.utils.layer_shard import estimate_shard_cache_bytes, shard_checkpoint
+
+ config = _CONFIG_SPELLINGS[spelling][0]
+ weights = _corrupt_checkpoint_with_config(tmp_path / "w", config)
+ with pytest.raises(ValueError) as gate:
+ check_source_quantization(config, arch="deepseek_v3")
+ with pytest.raises(ValueError) as sharder:
+ shard_checkpoint(weights, str(tmp_path / "s"), dtype="bfloat16", arch="deepseek_v3")
+ with pytest.raises(ValueError) as estimator:
+ estimate_shard_cache_bytes(
+ [os.path.join(weights, "model.safetensors")], dtype="bfloat16",
+ arch="deepseek_v3", quantization_config=config,
+ )
+ assert str(sharder.value) == str(estimator.value) == str(gate.value)
+
+
+_MALFORMED_GROUPS = {
+ "list": ["group_0"],
+ "string": "group_0",
+ "group-not-a-mapping": {"g": ["weights"]},
+ "weights-not-a-mapping": {"g": {"weights": "int4"}},
+ "bool-bits": {"g": {"weights": {"num_bits": True, "type": "int"}}},
+}
+
+
[email protected]("spelling", sorted(_MALFORMED_GROUPS))
+def test_a_malformed_compressed_tensors_config_is_still_refused_cleanly(spelling):
+ from soup_cli.utils.fp8_block import (
+ UnsupportedFP8Error,
+ UnsupportedQuantizedSourceError,
+ check_source_quantization,
+ )
+
+ config = {"quant_method": "compressed-tensors", "config_groups": _MALFORMED_GROUPS[spelling]}
+ with pytest.raises(UnsupportedQuantizedSourceError) as caught:
+ check_source_quantization(config, arch="deepseek_v3")
+ assert not isinstance(caught.value, UnsupportedFP8Error)
+ assert "declares quant_method 'compressed-tensors'. " in str(caught.value)
+
+
+def test_a_bool_group_size_is_not_printed_as_one():
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError, check_source_quantization
+
+ config = {
+ "quant_method": "compressed-tensors",
+ "config_groups": {"g": {"weights": {"num_bits": 4, "type": "int", "group_size": True}}},
+ }
+ with pytest.raises(UnsupportedQuantizedSourceError) as caught:
+ check_source_quantization(config, arch="deepseek_v3")
+ assert "(4-bit int weights). " in str(caught.value)
+
+
+def test_a_bool_bit_width_is_not_printed_as_one():
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError, check_source_quantization
+
+ with pytest.raises(UnsupportedQuantizedSourceError) as caught:
+ check_source_quantization({"quant_method": "gptq", "bits": True}, arch="llama")
+ assert "declares quant_method 'gptq'. " in str(caught.value)
+
+
+def test_the_header_plan_repeats_the_config_gate():
+ """plan_fp8_block is the one plan both callers run: it refuses a declared quantiser
+ even when no FP8 tensor is present (where it used to return None)."""
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError, plan_fp8_block
+
+ tensors = {"model.layers.0.o_proj.weight": ("BF16", (4, 4))}
+ with pytest.raises(UnsupportedQuantizedSourceError, match="'gptq'"):
+ plan_fp8_block({"quant_method": "gptq"}, tensors, arch="llama")
+ assert plan_fp8_block(None, tensors, arch="llama") is None
+
+
+# ==========================================================================
+# the tensor rule: stored types and quantiser names
+# ==========================================================================
+_INT_DTYPES = {
+ "int8": "I8", "int16": "I16", "int32": "I32", "int64": "I64", "uint8": "U8",
+ "bool": "BOOL", "uint16": "U16", "uint32": "U32", "uint64": "U64",
+}
+_WHERE = {
+ "layer": "model.layers.1.mlp.down_proj.weight",
+ "extras": "model.norm.weight",
+ "head": "lm_head.weight",
+}
+
+
[email protected]("where", sorted(_WHERE))
[email protected]("dtype", sorted(_INT_DTYPES))
+def test_an_integer_or_packed_tensor_is_refused_wherever_it_sits(tmp_path, dtype, where):
+ """U16/U32/U64 are types the header reader has no spelling for: the pre-flight used
+ to call the header unreadable and size the cache at a guess; it now refuses the
+ tensor in the sharder's words."""
+ import torch
+
+ state = _dense_state()
+ key = _WHERE[where]
+ state[key] = torch.ones(state[key].shape, dtype=torch.float32).to(getattr(torch, dtype))
+ weights = _write(tmp_path / "w", state, model_type="llama")
+ sharder, estimator = _refusals(tmp_path, weights, arch="llama")
+ assert f"checkpoint tensor {key!r} is stored as {_INT_DTYPES[dtype]!r}" in sharder
+ assert _TAIL in sharder and _POINTER in sharder
+ assert estimator == sharder
+
+
+ ("suffix", "needle"),
+ [
+ ("weight_scale", "compressed-tensors ('weight_scale'"),
+ ("weight_global_scale", "compressed-tensors NVFP4"),
+ ("input_scale", "static activation scales"),
+ ("SCB", "bitsandbytes LLM.int8()"),
+ ("weight.absmax", "bitsandbytes 4-bit"),
+ ("weight.quant_map", "bitsandbytes 4-bit"),
+ ("weight.nested_absmax", "bitsandbytes 4-bit"),
+ ("qweight_proj.weight", None),
+ ("qweight", "GPTQ or AWQ"),
+ ("g_idx", "GPTQ"),
+ ("W_q", "HQQ"),
+ ("codebooks", "AQLM"),
+ ("weight_scales", "EETQ"),
+ ],
+)
+def test_a_float_tensor_named_by_a_quantiser_is_refused(tmp_path, suffix, needle):
+ """A float companion beside a weight that is still quantised: the scales of an INT4
+ or int8 weight streamed as a parameter while the weight itself is not dequantised."""
+ import torch
+
+ state = _dense_state()
+ key = f"model.layers.0.self_attn.o_proj.{suffix}"
+ state[key] = torch.ones(HIDDEN, 1)
+ weights = _write(tmp_path / "w", state, model_type="llama")
+ if needle is None: # a name that only CONTAINS one is not refused
+ _shard(weights, tmp_path / "s", arch="llama")
+ _estimate(weights, arch="llama")
+ return
+ sharder, estimator = _refusals(tmp_path, weights, arch="llama")
+ assert f"checkpoint tensor {key!r} ('F32') belongs to {needle}" in sharder
+ assert _TAIL in sharder and _POINTER in sharder
+ assert estimator == sharder
+
+
+_Q = "model.layers.0.self_attn.q_proj."
+#: Each quantiser's own spelling of its companion tensors, written out here (not read off
+#: QUANTISED_KEY_SUFFIXES), with the format the refusal must name.
+_QUANTISER_SPELLINGS = {
+ _Q + "weight_packed": "compressed-tensors pack-quantized (int weights packed",
+ _Q + "weight_shape": "compressed-tensors pack-quantized ('weight_shape'",
+ _Q + "weight_global_scale": "compressed-tensors NVFP4",
+ _Q + "weight_zero_point": "compressed-tensors (asymmetric zero points)",
+ _Q + "weight_g_idx": "compressed-tensors (activation-order group index)",
+ _Q + "weight_scale": "compressed-tensors ('weight_scale'; DeepSeek-V3's block FP8",
+ _Q + "input_global_scale": "static activation scales (NVFP4)",
+ _Q + "input_scale": "static activation scales",
+ _Q + "output_scale": "static activation scales",
+ _Q + "qweight": "GPTQ or AWQ (int4 weights packed into int32 'qweight' words)",
+ _Q + "qzeros": "GPTQ or AWQ (int32-packed 'qzeros' zero points)",
+ _Q + "g_idx": "GPTQ (activation-order 'g_idx')",
+ _Q + "SCB": "bitsandbytes LLM.int8()",
+ _Q + "weight_format": "bitsandbytes LLM.int8()",
+ _Q + "weight.quant_state.bitsandbytes__nf4": "bitsandbytes 4-bit",
+ _Q + "weight.quant_state.bitsandbytes__fp4": "bitsandbytes 4-bit",
+ _Q + "weight.quant_map": "bitsandbytes 4-bit",
+ _Q + "weight.nested_quant_map": "bitsandbytes 4-bit",
+ _Q + "weight.absmax": "bitsandbytes 4-bit",
+ _Q + "weight.nested_absmax": "bitsandbytes 4-bit",
+ _Q + "W_q": "HQQ (packed 'W_q')",
+ _Q + "codebooks": "AQLM (additive codebooks)",
+ _Q + "codes": "AQLM (int codes)",
+ _Q + "weight_scales": "EETQ",
+ _Q + "weight._data": "quanto (quantised '_data')",
+ _Q + "weight._scale": "quanto (quantised '_scale')",
+ _Q + "_weight_qdata": "torchao",
+}
+
+
[email protected]("key", sorted(_QUANTISER_SPELLINGS))
+def test_each_quantisers_companion_spelling_is_refused_naming_it(key):
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError, refuse_unsupported_tensor
+
+ with pytest.raises(UnsupportedQuantizedSourceError) as caught:
+ refuse_unsupported_tensor(key, "BF16")
+ assert _QUANTISER_SPELLINGS[key] in str(caught.value)
+
+
+ ("dtype", "needle"),
+ [
+ ("I32", "int32, the word GPTQ, AWQ and compressed-tensors pack int4 weights into"),
+ ("U32", "uint32, the word oMLX/oQ affine (MLX) checkpoints pack"),
+ ("U8", "uint8, which bitsandbytes 4-bit packs NF4/FP4 nibbles into"),
+ ("I8", "int8, an int8-quantised weight"),
+ ("F4", "FP4, packed MXFP4/NVFP4 values"),
+ ("I16", "an integer or packed type"),
+ ("BOOL", "an integer or packed type"),
+ ],
+)
+def test_a_plain_name_in_a_packed_type_is_named_by_what_the_type_holds(dtype, needle):
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError, refuse_unsupported_tensor
+
+ with pytest.raises(UnsupportedQuantizedSourceError) as caught:
+ refuse_unsupported_tensor("model.layers.0.self_attn.q_proj.weight", dtype)
+ assert f"is stored as {dtype!r}: {needle}" in str(caught.value)
+
+
+def test_an_mlx_affine_source_on_another_architecture_is_refused_naming_the_format(tmp_path):
+ """oMLX/oQ affine is read on qwen4_exp only; elsewhere its uint32 words would be cast."""
+ import torch
+
+ state = _dense_state()
+ state["model.layers.0.self_attn.o_proj.weight"] = torch.zeros(
+ (HIDDEN, HIDDEN // 8), dtype=torch.uint32
+ )
+ state["model.layers.0.self_attn.o_proj.scales"] = torch.ones(HIDDEN, 1).to(torch.bfloat16)
+ state["model.layers.0.self_attn.o_proj.biases"] = torch.zeros(HIDDEN, 1).to(torch.bfloat16)
+ weights = _write(
+ tmp_path / "w", state, quant={"bits": 4, "group_size": 32}, model_type="llama"
+ )
+ sharder, estimator = _refusals(tmp_path, weights, arch="llama")
+ assert "is stored as 'U32': uint32, the word oMLX/oQ affine (MLX)" in sharder
+ assert "on qwen4_exp only" in sharder
+ assert estimator == sharder
+
+
+def test_a_header_only_type_is_refused_under_its_canonical_name(tmp_path):
+ """The pre-flight words a type its reader lacks by the sharder's canonical key, so a
+ wrapper prefix does not make the two messages differ."""
+ import torch
+
+ state = _dense_state("language_model.model.")
+ state["language_model.model.layers.1.mlp.down_proj.weight"] = torch.zeros(
+ (HIDDEN, INTER), dtype=torch.uint32
+ )
+ weights = _write(tmp_path / "w", state, model_type="llama")
+ sharder, estimator = _refusals(tmp_path, weights, arch="llama")
+ assert "checkpoint tensor 'model.layers.1.mlp.down_proj.weight' is stored as 'U32'" in sharder
+ assert estimator == sharder
+
+
+def test_a_header_dtype_no_quantiser_writes_still_reads_as_an_unreadable_header(tmp_path):
+ """Only types safetensors defines become the refusal; a corrupt spelling stays the
+ pre-flight's 'header unreadable' fallback, as before."""
+ import struct
+
+ from soup_cli.utils.layer_shard import SourceHeaderError, estimate_shard_cache_bytes
+
+ for raw in ("XYZ", "F8_E8M0", "C64"):
+ payload = json.dumps(
+ {"model.layers.0.w": {"dtype": raw, "shape": [1], "data_offsets": [0, 1]}}
+ ).encode()
+ path = tmp_path / f"{raw}.safetensors"
+ path.write_bytes(struct.pack("<Q", len(payload)) + payload + b"\0")
+ with pytest.raises(SourceHeaderError):
+ estimate_shard_cache_bytes([str(path)], dtype="bfloat16", arch="llama")
+
+
+def test_the_disk_preflight_lets_the_refusal_through_instead_of_guessing(tmp_path):
+ """``_preflight_cache_estimate`` falls back to the coarse figure on an unreadable
+ header only: a source the sharder would refuse is refused before any copy."""
+ import torch
+
+ from soup_cli.trainer.stream_setup import _preflight_cache_estimate, _ResolvedWeights
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError
+
+ state = _dense_state()
+ state["model.layers.0.self_attn.o_proj.weight"] = torch.zeros(
+ (HIDDEN, HIDDEN // 8), dtype=torch.uint32
+ )
+ weights = _write(tmp_path / "w", state, model_type="llama")
+ with pytest.raises(UnsupportedQuantizedSourceError, match="'U32'"):
+ _preflight_cache_estimate(_ResolvedWeights(weights), arch="llama", dtype="bfloat16")
+
+
+# ==========================================================================
+# the backstop under every plain read
+# ==========================================================================
[email protected]("dtype", ["I8", "I16", "I32", "I64", "U8", "U16", "U32", "BOOL", "F4"])
+def test_the_plain_read_backstop_refuses_an_integer_or_packed_tensor(dtype):
+ from soup_cli.utils.fp8_block import UnsupportedFP8Error, UnsupportedQuantizedSourceError
+ from soup_cli.utils.layer_shard import _refuse_fp8
+
+ with pytest.raises(UnsupportedQuantizedSourceError) as caught:
+ _refuse_fp8("model.layers.0.q_proj.weight", dtype)
+ assert not isinstance(caught.value, UnsupportedFP8Error)
+ assert repr(dtype) in str(caught.value)
+
+
+ "key",
+ [
+ "model.layers.0.q_proj.weight_packed",
+ "model.layers.0.q_proj.SCB",
+ "model.layers.0.q_proj.weight.absmax",
+ ],
+)
+def test_the_plain_read_backstop_refuses_a_quantiser_companion(key):
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError
+ from soup_cli.utils.layer_shard import _refuse_fp8
+
+ with pytest.raises(UnsupportedQuantizedSourceError, match="belongs to"):
+ _refuse_fp8(key, "BF16")
+
+
+ ("key", "dtype"),
+ [
+ ("model.layers.0.q_proj.weight", "BF16"),
+ ("model.layers.0.q_proj.weight", "F16"),
+ ("model.layers.0.q_proj.weight", "F32"),
+ ("model.layers.0.q_proj.weight", "F64"),
+ ("model.layers.0.ple.ple_embedding.layer_multipliers", "I64"),
+ ("language_model.model.layers.3.ple.ple_embedding.ngram_heads_offsets", "I64"),
+ ("model.layers.3.ple.ple_embedding.ngram_heads_vocab_sizes", "I32"),
+ ("model.visual.embeddings.position_ids", "I64"),
+ ("model.layers.0.self_attn.rotary_emb.inv_freq", "F32"),
+ ("model.layers.0.mlp.gate.e_score_correction_bias", "F32"),
+ ("model.layers.0.q_proj.scales", "BF16"),
+ ("model.layers.0.q_proj.biases", "BF16"),
+ ],
+)
+def test_the_plain_read_backstop_passes_floats_and_real_integer_buffers(key, dtype):
+ from soup_cli.utils.layer_shard import _refuse_fp8
+
+ _refuse_fp8(key, dtype)
+
+
+def test_a_plain_read_of_an_integer_tensor_raises_before_the_cast(tmp_path):
+ import torch
+ from safetensors import safe_open
+ from safetensors.torch import save_file
+
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError
+ from soup_cli.utils.layer_shard import _read_tensor
+
+ path = str(tmp_path / "w.safetensors")
+ save_file({"w": torch.arange(8, dtype=torch.int32).reshape(2, 4)}, path)
+ with safe_open(path, framework="pt") as handle:
+ with pytest.raises(UnsupportedQuantizedSourceError, match="'I32'"):
+ _read_tensor(handle, "w", "bfloat16")
+
+
+# ==========================================================================
+# what must keep working
+# ==========================================================================
+def test_the_fp8_block_source_still_plans_beside_float_buffers():
+ from soup_cli.utils.fp8_block import plan_fp8_block
+
+ weight = "model.layers.0.self_attn.o_proj.weight"
+ tensors = {
+ weight: ("F8_E4M3", (256, 256)),
+ weight + "_scale_inv": ("F32", (2, 2)),
+ "model.layers.0.input_layernorm.weight": ("BF16", (256,)),
+ "model.layers.0.mlp.gate.e_score_correction_bias": ("F32", (8,)),
+ "model.layers.0.self_attn.rotary_emb.inv_freq": ("F32", (32,)),
+ }
+ plan = plan_fp8_block(DEEPSEEK_FP8, tensors, arch="deepseek_v3")
+ assert plan.weights == {weight}
+
+
+def test_a_qwen4_oq_bundle_with_its_integer_buffers_still_shards(tmp_path):
+ """The supported quantised source: uint32 affine weights with '.scales'/'.biases',
+ the PLE's int64 hashing tables, and the oQ PLE 'weight_scale' and vision weights the
+ sharder drops (so the plan must not see them: a '.weight_scale' would be refused)."""
+ import torch
+ from safetensors import safe_open
+ from safetensors.torch import save_file
+
+ from soup_cli.utils.layer_shard import layer_shard_path, shard_checkpoint
+
+ weights = tmp_path / "weights"
+ weights.mkdir()
+ ple = "language_model.model.layers.0.ple.ple_embedding."
+ save_file(
+ {
+ "language_model.model.layers.0.proj.weight": torch.tensor(
+ [[0, 1, 2, 3], [4, 5, 6, 7]], dtype=torch.uint32
+ ),
+ "language_model.model.layers.0.proj.scales": torch.ones((2, 1)).to(
+ torch.bfloat16
+ ),
+ "language_model.model.layers.0.proj.biases": torch.zeros((2, 1)).to(
+ torch.bfloat16
+ ),
+ ple + "layer_multipliers": torch.tensor([3, 5], dtype=torch.int64),
+ ple + "ngram_heads_vocab_sizes": torch.tensor([17, 19], dtype=torch.int64),
+ ple + "ngram_heads_offsets": torch.tensor([0, 17], dtype=torch.int64),
+ ple + "ngram_embedding.shards.0.weight": torch.tensor(
+ [[0, 1, 2, 3]] * 3, dtype=torch.uint32
+ ),
+ ple + "ngram_embedding.shards.0.scales": torch.ones((3, 1)).to(torch.bfloat16),
+ ple + "ngram_embedding.shards.0.biases": torch.zeros((3, 1)).to(torch.bfloat16),
+ ple + "ngram_embedding.weight_scale": torch.ones(1),
+ "vision_tower.blocks.0.attn.weight_scale": torch.ones(1),
+ "vision_tower.embeddings.position_ids": torch.arange(4),
+ },
+ weights / "model.safetensors",
+ )
+ (weights / "config.json").write_text(
+ json.dumps({"quantization_config": {"bits": 4, "group_size": 32, "mode": "affine"}}),
+ encoding="utf-8",
+ )
+ index = shard_checkpoint(str(weights), str(tmp_path / "s"), dtype="float32", arch="qwen4_exp")
+ assert "proj.weight" in index.layer_keys
+ assert "ple.ple_embedding.layer_multipliers" in index.layer_keys
+ with safe_open(layer_shard_path(str(tmp_path / "s"), 0), framework="pt") as handle:
+ assert handle.get_tensor("proj.weight").shape == (2, 32)
+
+
+ "tensors",
+ [
+ {"model.layers.0.proj.weight": ("U32", (2, 4)),
+ "model.layers.0.proj.scales": ("BF16", (2, 1))},
+ {"model.layers.0.proj.weight": ("U32", (2, 4)),
+ "model.layers.0.proj.biases": ("BF16", (2, 1))},
+ {"model.layers.0.proj.packed": ("U32", (2, 4)),
+ "model.layers.0.proj.scales": ("BF16", (2, 1)),
+ "model.layers.0.proj.biases": ("BF16", (2, 1))},
+ ],
+ ids=["scales-only", "biases-only", "not-a-weight"],
+)
+def test_on_qwen4_only_a_complete_affine_weight_is_exempt(tensors):
+ """The exemption is the oQ triple ``<m>.weight`` + ``<m>.scales`` + ``<m>.biases``."""
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError, plan_fp8_block
+
+ with pytest.raises(UnsupportedQuantizedSourceError, match="'U32'"):
+ plan_fp8_block(None, tensors, arch="qwen4_exp")
+ complete = {
+ "model.layers.0.proj.weight": ("U32", (2, 4)),
+ "model.layers.0.proj.scales": ("BF16", (2, 1)),
+ "model.layers.0.proj.biases": ("BF16", (2, 1)),
+ }
+ assert plan_fp8_block(None, complete, arch="qwen4_exp") is None
+
+
+def test_the_same_affine_bundle_off_qwen4_is_refused_before_layer_0_is_written(tmp_path):
+ """The exemption is qwen4_exp's own reader: elsewhere the uint32 words would be cast.
+ In the LAST layer, so a refusal left to the read backstop would come after layer 0's
+ file was written; the header plan refuses before any."""
+ import torch
+
+ state = _dense_state()
+ base = f"model.layers.{LAYERS - 1}.self_attn.o_proj."
+ state[base + "weight"] = torch.zeros((HIDDEN, HIDDEN // 8), dtype=torch.uint32)
+ state[base + "scales"] = torch.ones(HIDDEN, 1).to(torch.bfloat16)
+ state[base + "biases"] = torch.zeros(HIDDEN, 1).to(torch.bfloat16)
+ weights = _write(tmp_path / "w", state, model_type="qwen3")
+ sharder, estimator = _refusals(tmp_path, weights, arch="qwen3")
+ assert f"checkpoint tensor {base + 'weight'!r} is stored as 'U32'" in sharder
+ assert estimator == sharder
+
+
+_TINY_COMMON = dict(
+ vocab_size=64, hidden_size=16, intermediate_size=32, num_hidden_layers=2,
+ num_attention_heads=2, num_key_value_heads=1, head_dim=8, max_position_embeddings=64,
+ bos_token_id=1, eos_token_id=2, pad_token_id=0,
+)
+_TINY_LINEAR = dict(
+ linear_key_head_dim=4, linear_value_head_dim=4, linear_num_key_heads=2,
+ linear_num_value_heads=2, layer_types=["linear_attention", "full_attention"],
+)
+#: model_type -> (stream family, extra config). Every SUPPORTED_STREAM_ARCHS family, plus
+#: the qwen3_5 aliases that stream as qwen3.
+_TINY_FAMILIES = {
+ "llama": ("llama", {}),
+ "qwen2": ("qwen2", {}),
+ "qwen3": ("qwen3", {}),
+ "mistral": ("mistral", {}),
+ "gemma": ("gemma", {}),
+ "gemma2": ("gemma2", {}),
+ "gemma3_text": ("gemma3_text", {}),
+ "phi": ("phi", {}),
+ "phi3": ("phi3", {}),
+ "deepseek_v3": ("deepseek_v3", dict(
+ hidden_size=64, intermediate_size=128, moe_intermediate_size=32,
+ first_k_dense_replace=1, num_attention_heads=4, num_key_value_heads=4,
+ n_shared_experts=1, n_routed_experts=4, n_group=2, topk_group=1,
+ num_experts_per_tok=2, kv_lora_rank=16, q_lora_rank=24, qk_nope_head_dim=16,
+ qk_rope_head_dim=8, v_head_dim=16, head_dim=None,
+ )),
+ "qwen3_5_text": ("qwen3", _TINY_LINEAR),
+ "qwen3_5_moe_text": ("qwen3", dict(
+ _TINY_LINEAR, num_experts=2, num_experts_per_tok=1, moe_intermediate_size=8,
+ shared_expert_intermediate_size=8,
+ )),
+ "qwen4_exp": ("qwen4_exp", None),
+}
+
+
+def test_every_supported_family_has_a_tiny_checkpoint_below():
+ from soup_cli.utils.layer_stream import SUPPORTED_STREAM_ARCHS
+
+ assert set(SUPPORTED_STREAM_ARCHS) <= {family for family, _ in _TINY_FAMILIES.values()}
+
+
[email protected]("model_type", sorted(_TINY_FAMILIES))
+def test_every_supported_family_shards_its_own_checkpoint(tmp_path, model_type):
+ """The supported families' own save_pretrained output is never refused. Its only
+ integer tensors are qwen4_exp's three PLE hashing tables (int64), pinned here."""
+ import torch
+
+ transformers = pytest.importorskip("transformers")
+ from soup_cli.utils.fp8_block import FLOAT_SOURCE_DTYPES
+ from soup_cli.utils.layer_shard import _discover_safetensors, _read_source_tensors
+
+ family, extra = _TINY_FAMILIES[model_type]
+ if extra is None:
+ from tests.test_issue602_qwen4_ple_streaming import _tiny_qwen4_config
+
+ config = _tiny_qwen4_config()
+ else:
+ kwargs = {k: v for k, v in dict(_TINY_COMMON, **extra).items() if v is not None}
+ config = transformers.AutoConfig.for_model(model_type, **kwargs)
+ torch.manual_seed(0)
+ model = transformers.AutoModelForCausalLM.from_config(config, dtype=torch.float32)
+ weights = str(tmp_path / "model")
+ model.save_pretrained(weights, safe_serialization=True)
+ del model
+
+ tensors = _read_source_tensors(_discover_safetensors(weights))
+ integers = sorted(
+ key.rsplit(".", 1)[-1] for key, (dtype, _shape) in tensors.items()
+ if dtype not in FLOAT_SOURCE_DTYPES
+ )
+ expected = (
+ ["layer_multipliers", "ngram_heads_offsets", "ngram_heads_vocab_sizes"]
+ if family == "qwen4_exp" else []
+ )
+ assert integers == expected
+
+ index = _shard(weights, tmp_path / "s", arch=family)
+ assert index.n_layers == 2
+ if family != "qwen4_exp": # qwen4_exp has its own estimator
+ assert _estimate(weights, arch=family).total_bytes > 0
+
+
+# ==========================================================================
+# hygiene: untrusted names reach a terminal
+# ==========================================================================
+def test_a_refusal_never_quotes_raw_control_bytes():
+ from soup_cli.utils.fp8_block import (
+ UnsupportedQuantizedSourceError,
+ check_source_quantization,
+ refuse_unsupported_tensor,
+ )
+
+ hostile = "x\x1b[31m\x07\r"
+ with pytest.raises(UnsupportedQuantizedSourceError) as by_config:
+ check_source_quantization({"quant_method": hostile}, arch="llama")
+ with pytest.raises(UnsupportedQuantizedSourceError) as by_format:
+ check_source_quantization(
+ {"quant_method": "compressed-tensors", "format": hostile}, arch="llama"
+ )
+ with pytest.raises(UnsupportedQuantizedSourceError) as by_kind:
+ check_source_quantization(
+ {"quant_method": "compressed-tensors",
+ "config_groups": {"g": {"weights": {"num_bits": 4, "type": hostile}}}},
+ arch="llama",
+ )
+ with pytest.raises(UnsupportedQuantizedSourceError) as by_tensor:
+ refuse_unsupported_tensor(f"model.layers.0.{hostile}.weight", hostile)
+ for caught in (by_config, by_format, by_kind, by_tensor):
+ message = str(caught.value)
+ assert not any(ord(char) < 32 for char in message), message
+
+
+# ==========================================================================
+# review round: the refusal comes before anything is created, renamed or reused
+# ==========================================================================
+def _tree_state(directory):
+ """name -> bytes of every file under ``directory`` (a cache is small here)."""
+ state = {}
+ for base, _dirs, files in os.walk(directory):
+ for name in files:
+ path = os.path.join(base, name)
+ with open(path, "rb") as handle:
+ state[os.path.relpath(path, directory)] = handle.read()
+ return state
+
+
+def _int32_llama(directory):
+ """A llama source with no quantization_config and one int32 decoder weight."""
+ import torch
+
+ state = _dense_state()
+ state["model.layers.1.mlp.down_proj.weight"] = torch.zeros((HIDDEN, INTER), dtype=torch.int32)
+ return _write(directory, state, model_type="llama")
+
+
[email protected]("source", ["k2-config", "int32-no-config"])
+def test_a_refusal_creates_no_cache_folder(tmp_path, source):
+ from soup_cli.utils.layer_shard import shard_checkpoint
+
+ if source == "k2-config":
+ weights = _write(tmp_path / "w", _k2_state(), quant=K2_THINKING_QUANT)
+ else:
+ weights = _int32_llama(tmp_path / "w")
+ arch = "deepseek_v3" if source == "k2-config" else "llama"
+ out = tmp_path / "cache" / "model"
+ with pytest.raises(ValueError, match=_TAIL):
+ shard_checkpoint(weights, str(out), dtype="bfloat16", arch=arch)
+ assert not out.exists()
+ assert not (tmp_path / "cache").exists()
+
+
+def test_a_refusal_creates_no_stripe_folder(tmp_path):
+ from soup_cli.utils.layer_shard import shard_checkpoint
+
+ weights = _int32_llama(tmp_path / "w")
+ stripe = tmp_path / "second-drive"
+ stripe.mkdir()
+ with pytest.raises(ValueError, match=_TAIL):
+ shard_checkpoint(
+ weights, str(tmp_path / "cache" / "model"), dtype="bfloat16", arch="llama",
+ stripe_roots=[str(stripe)],
+ )
+ assert os.listdir(stripe) == []
+
+
+def test_a_refused_source_leaves_a_valid_prior_cache_untouched(tmp_path):
+ """A good cache, then the source replaced by one that is refused: the cache miss used
+ to quarantine index.json (renamed to index.json.resharding) before the refusal."""
+ import shutil
+
+ from soup_cli.utils.layer_shard import shard_checkpoint
+
+ weights = tmp_path / "w"
+ _write(weights, _dense_state(), model_type="llama")
+ out = tmp_path / "cache"
+ shard_checkpoint(str(weights), str(out), dtype="bfloat16", arch="llama")
+ before = _tree_state(out)
+ assert "index.json" in before
+
+ shutil.rmtree(weights)
+ _int32_llama(weights)
+ with pytest.raises(ValueError, match="is stored as 'I32'"):
+ shard_checkpoint(str(weights), str(out), dtype="bfloat16", arch="llama")
+ assert _tree_state(out) == before
+ assert not (out / "index.json.resharding").exists()
+
+
+def test_a_cache_sharded_before_the_refusal_existed_is_not_reused(tmp_path, monkeypatch):
+ """A cache that older code wrote from an int32 source (no quantization_config) is a
+ cache HIT for the same source: the refusal must not sit behind the hit's return."""
+ import soup_cli.utils.layer_shard as layer_shard
+ from soup_cli.utils.fp8_block import _classify_fp8
+
+ weights = _int32_llama(tmp_path / "w")
+ out = tmp_path / "cache"
+ with monkeypatch.context() as old_code: # the sharder as it was: FP8 checks only
+ old_code.setattr(layer_shard, "plan_fp8_block", _classify_fp8)
+ old_code.setattr(layer_shard, "refuse_unsupported_tensor", lambda *_a, **_k: None)
+ layer_shard.shard_checkpoint(weights, str(out), dtype="bfloat16", arch="llama")
+ before = _tree_state(out)
+ with pytest.raises(ValueError, match="is stored as 'I32'"):
+ layer_shard.shard_checkpoint(weights, str(out), dtype="bfloat16", arch="llama")
+ assert _tree_state(out) == before
+
+
+def test_the_setup_refuses_a_bad_source_in_the_preflight(tmp_path, monkeypatch):
+ """No quantization_config, so the config gate passes; the disk pre-flight reads the
+ headers and refuses there: before its cache lookup, before the resolver goes on to
+ copy anything, and before the sharder."""
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ weights = _write(tmp_path / "k2", _k2_state())
+ size = os.path.getsize(os.path.join(weights, "model.safetensors"))
+ plan = types.SimpleNamespace(
+ weights_dir=weights, source_dir=weights, source_bytes=size, materialized_copy_bytes=0,
+ materialize_bytes=0, needs_materialization=False,
+ source_files=(("model.safetensors", size, 0),), source_revision=None,
+ )
+
+ def _resolve(_base, *, before_materialize=None):
+ before_materialize(plan)
+ raise AssertionError("the resolver went on past a source that cannot stream")
+
+ model_cfg = types.SimpleNamespace(
+ model_type="deepseek_v3", hidden_size=HIDDEN, num_hidden_layers=LAYERS,
+ vocab_size=VOCAB, intermediate_size=INTER, quantization_config=None,
+ )
+ with pytest.raises(ValueError, match="weight_packed' is stored as 'I32'"):
+ _drive_qwen4_streaming_setup(
+ tmp_path, monkeypatch, resolve_weights=_resolve, arch="deepseek_v3",
+ model_cfg=model_cfg,
+ )
+
+
+# ==========================================================================
+# review round: the four surviving mutants
+# ==========================================================================
+ "key",
+ [
+ "model.xposition_ids",
+ "model.layers.0.xple.ple_embedding.layer_multipliers",
+ "model.layers.0.xple.ple_embedding.ngram_heads_vocab_sizes",
+ "model.layers.0.xple.ple_embedding.ngram_heads_offsets",
+ ],
+)
+def test_an_integer_buffer_is_matched_by_its_whole_last_names(key):
+ """Each exemption starts at a dot: a name that merely ends in the same letters is
+ another tensor, and an int64 one is refused."""
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError, refuse_unsupported_tensor
+
+ with pytest.raises(UnsupportedQuantizedSourceError, match="'I64'"):
+ refuse_unsupported_tensor(key, "I64")
+
+
[email protected]("raw", ["F6_E2M3", "F6_E3M2", "F4", "U16", "U32", "U64"])
+def test_every_header_only_quantiser_type_is_refused_by_the_preflight(tmp_path, raw):
+ """Types the pre-flight's header reader has no spelling for, written by MX/NVFP4 and
+ MLX quantisers: refused by name, not sized at a guess."""
+ import struct
+
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError
+ from soup_cli.utils.layer_shard import estimate_shard_cache_bytes
+
+ payload = json.dumps(
+ {"model.layers.0.mlp.down_proj.weight": {
+ "dtype": raw, "shape": [4, 4], "data_offsets": [0, 12]}}
+ ).encode()
+ path = tmp_path / "model.safetensors"
+ path.write_bytes(struct.pack("<Q", len(payload)) + payload + b"\0" * 12)
+ with pytest.raises(UnsupportedQuantizedSourceError) as caught:
+ estimate_shard_cache_bytes([str(path)], dtype="bfloat16", arch="llama")
+ assert f"is stored as {raw!r}" in str(caught.value)
+
+
[email protected]("method", ["FP8", "Fp8", "fp8 ", " fp8"])
+def test_quant_method_fp8_is_matched_exactly_as_transformers_matches_it(method):
+ """transformers looks the method up as an exact key (``AUTO_QUANTIZATION_CONFIG_MAPPING``
+ has 'fp8' only; 'FP8' is an unknown quantisation type to it). So is it here: any other
+ spelling is a quantiser layer streaming does not read, refused naming it."""
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError, check_source_quantization
+
+ config = {**DEEPSEEK_FP8, "quant_method": method}
+ with pytest.raises(UnsupportedQuantizedSourceError) as caught:
+ check_source_quantization(config, arch="deepseek_v3")
+ assert f"declares quant_method {method!r}" in str(caught.value)
+
+
+def test_transformers_matches_quant_method_case_sensitively():
+ pytest.importorskip("transformers")
+ from transformers.quantizers.auto import AUTO_QUANTIZATION_CONFIG_MAPPING
+
+ assert "fp8" in AUTO_QUANTIZATION_CONFIG_MAPPING
+ assert "FP8" not in AUTO_QUANTIZATION_CONFIG_MAPPING
+ assert all(name == name.lower() for name in AUTO_QUANTIZATION_CONFIG_MAPPING)
+
+
[email protected]("bits", [4, 6, 16])
+def test_a_compressed_tensors_float_group_is_fp8_only_at_eight_bits(bits):
+ """NVFP4 declares float weights of 4 bits: that is not an FP8 format."""
+ from soup_cli.utils.fp8_block import (
+ UnsupportedFP8Error,
+ UnsupportedQuantizedSourceError,
+ check_source_quantization,
+ )
+
+ config = {
+ "quant_method": "compressed-tensors",
+ "config_groups": {"g": {"weights": {"num_bits": bits, "type": "float"}}},
+ }
+ with pytest.raises(UnsupportedQuantizedSourceError) as caught:
+ check_source_quantization(config, arch="deepseek_v3")
+ assert not isinstance(caught.value, UnsupportedFP8Error)
+ assert f"({bits}-bit float weights)" in str(caught.value)
+
+
+# ==========================================================================
+# review round: a malformed or nested quantization_config
+# ==========================================================================
+ "value", ["fp8", ["fp8"], 4, True, False, 0.5], ids=["str", "list", "int", "true",
+ "false", "float"]
+)
+def test_a_quantization_config_that_is_not_a_mapping_is_refused_as_malformed(tmp_path, value):
+ """It used to be read as 'no quantization_config' and pass the gate."""
+ from soup_cli.utils.fp8_block import UnsupportedQuantizedSourceError, check_source_quantization
+ from soup_cli.utils.layer_shard import estimate_shard_cache_bytes, shard_checkpoint
+
+ weights = _corrupt_checkpoint_with_config(tmp_path / "w", value)
+ with pytest.raises(UnsupportedQuantizedSourceError) as gate:
+ check_source_quantization(value, arch="deepseek_v3")
+ assert f"quantization_config is {value!r}" in str(gate.value)
+ assert "not a mapping" in str(gate.value)
+ with pytest.raises(ValueError) as sharder:
+ shard_checkpoint(weights, str(tmp_path / "s"), dtype="bfloat16", arch="deepseek_v3")
+ with pytest.raises(ValueError) as estimator:
+ estimate_shard_cache_bytes(
+ [os.path.join(weights, "model.safetensors")], dtype="bfloat16",
+ arch="deepseek_v3", quantization_config=value,
+ )
+ assert str(sharder.value) == str(estimator.value) == str(gate.value)
+
+
+def test_a_quantization_config_under_text_config_is_read_too(tmp_path):
+ from soup_cli.utils.fp8_block import read_checkpoint_quantization_config
+ from soup_cli.utils.layer_shard import shard_checkpoint
+
+ weights = tmp_path / "w"
+ weights.mkdir()
+ (weights / "model.safetensors").write_bytes(b"\xff" * 64)
+ (weights / "config.json").write_text(
+ json.dumps({"model_type": "deepseek_v3",
+ "text_config": {"quantization_config": K2_THINKING_QUANT}}),
+ encoding="utf-8",
+ )
+ assert read_checkpoint_quantization_config(str(weights)) == K2_THINKING_QUANT
+ with pytest.raises(ValueError, match=re.escape(K2_NEEDLE)):
+ shard_checkpoint(str(weights), str(tmp_path / "s"), dtype="bfloat16", arch="deepseek_v3")
+
+
+def test_the_top_level_quantization_config_wins_over_the_nested_one(tmp_path):
+ from soup_cli.utils.fp8_block import quantization_config_of
+
+ nested = {"quantization_config": {"quant_method": "gptq"}}
+ assert quantization_config_of(
+ {"quantization_config": DEEPSEEK_FP8, "text_config": nested}
+ ) == DEEPSEEK_FP8
+ assert quantization_config_of({"text_config": nested}) == {"quant_method": "gptq"}
+ assert quantization_config_of({"text_config": "gptq"}) is None
+ assert quantization_config_of({}) is None
+ config = types.SimpleNamespace(
+ quantization_config=None, text_config=types.SimpleNamespace(quantization_config=None)
+ )
+ assert quantization_config_of(config) is None
+ config.text_config.quantization_config = {"quant_method": "awq"}
+ assert quantization_config_of(config) == {"quant_method": "awq"}
+
+
+def test_the_setup_reads_a_nested_quantization_config(tmp_path, monkeypatch):
+ from tests.test_issue602_qwen4_ple_streaming import _drive_qwen4_streaming_setup
+
+ def _must_not_resolve(*_args, **_kwargs):
+ raise AssertionError("weights resolved for a base that cannot stream")
+
+ model_cfg = types.SimpleNamespace(
+ model_type="deepseek_v3", hidden_size=HIDDEN, num_hidden_layers=LAYERS,
+ vocab_size=VOCAB, intermediate_size=INTER, quantization_config=None,
+ text_config=None,
+ )
+ model_cfg.text_config = types.SimpleNamespace(
+ model_type="deepseek_v3", hidden_size=HIDDEN, num_hidden_layers=LAYERS,
+ vocab_size=VOCAB, intermediate_size=INTER, quantization_config=K2_THINKING_QUANT,
+ )
+ with pytest.raises(ValueError, match=re.escape(K2_NEEDLE)):
+ _drive_qwen4_streaming_setup(
+ tmp_path, monkeypatch, resolve_weights=_must_not_resolve, arch="deepseek_v3",
+ model_cfg=model_cfg,
+ )
+
+
+# ==========================================================================
+# review round: the header reader's error survives pickling and copying
+# ==========================================================================
+def test_the_unsupported_dtype_error_round_trips_through_pickle_and_copy():
+ import copy
+ import pickle
+
+ from soup_cli.utils.safetensors_reader import UnsupportedDtypeError
+
+ error = UnsupportedDtypeError("w.safetensors: tensor 'x' ...", tensor="x", dtype="U32")
+ for clone in (pickle.loads(pickle.dumps(error)), copy.copy(error), copy.deepcopy(error)):
+ assert type(clone) is UnsupportedDtypeError
+ assert str(clone) == str(error)
+ assert (clone.tensor, clone.dtype) == ("x", "U32")
+ bare = UnsupportedDtypeError("message only")
+ assert (bare.tensor, bare.dtype) == ("", None)
+
+
+# ==========================================================================
+# pins: the cache format, and a packed tensor inside an FP8 block source
+# ==========================================================================
+def test_the_shard_format_version_is_not_bumped():
+ """A bump invalidates EVERY existing layer cache (the 30 GB demo cache among them), so
+ it must be deliberate, never a side effect. This refusal does not need one: the source
+ is checked before a cache hit returns, so a stale cache of a bad source is refused."""
+ from soup_cli.utils.layer_shard import _SHARD_FORMAT_VERSION
+
+ assert _SHARD_FORMAT_VERSION == 5
+
+
+def _fp8_block_state():
+ """A tiny DeepSeek-V3 FP8 block source: e4m3 linears with float32 block scales."""
+ import torch
+
+ state = _dense_state()
+ for layer in range(LAYERS):
+ key = f"model.layers.{layer}.self_attn.o_proj.weight"
+ state[key] = state[key].to(torch.float32).to(torch.float8_e4m3fn)
+ state[key + "_scale_inv"] = torch.ones(1, 1)
+ return state
+
+
+ ("key", "dtype", "needle"),
+ [
+ ("model.layers.1.mlp.experts.0.gate_proj.weight_packed", "int32",
+ "is stored as 'I32': compressed-tensors pack-quantized"),
+ ("model.layers.0.mlp.down_proj.weight", "uint8",
+ "is stored as 'U8': uint8, which bitsandbytes 4-bit packs"),
+ ],
+ ids=["i32-weight-packed", "u8-weight"],
+)
+def test_a_packed_tensor_beside_an_fp8_block_source_is_refused(tmp_path, key, dtype, needle):
+ """An accepted FP8 plan covers its FP8 weights and their scales only: every other tensor
+ still meets the tensor rule, in the same words for the sharder and the pre-flight."""
+ import torch
+
+ state = _fp8_block_state()
+ state[key] = torch.zeros((HIDDEN, INTER // 8), dtype=getattr(torch, dtype))
+ weights = _write(tmp_path / "w", state, quant=DEEPSEEK_FP8)
+ sharder, estimator = _refusals(tmp_path, weights)
+ assert f"checkpoint tensor {key!r} {needle}" in sharder
+ assert _TAIL in sharder and _POINTER in sharder
+ assert estimator == sharder
+
+
+def test_the_same_fp8_block_source_without_the_packed_tensor_shards(tmp_path):
+ """The control: the FP8 block source alone is planned and sharded, not refused."""
+ weights = _write(tmp_path / "w", _fp8_block_state(), quant=DEEPSEEK_FP8)
+ assert _shard(weights, tmp_path / "s").n_layers == LAYERS
+ assert _estimate(weights).total_bytes > 0