@@ -145,6 +145,86 @@ def _raise_for_sharded_gguf(
145145 )
146146
147147
148+ class SparseMoEExportError (NotImplementedError ):
149+ """Routed MoE experts have no sparse fusion for their quantization.
150+
151+ Raised before export when a checkpoint's routed experts lower to per-expert
152+ native ``pkg.nxrt::BlockQuantizedMatMul`` nodes (e.g. GLM-5.2 UD-IQ1_{S,M})
153+ for which no sparse top-k ``BlockQuantizedMoE`` fusion exists — exporting
154+ anyway would recompute every expert for every token (dense-all-expert
155+ compute) with no performance guarantee.
156+ """
157+
158+
159+ def _routed_dense_block_expert_paths (module ) -> list [str ]:
160+ """Return module paths of routed experts lowered as native block linears.
161+
162+ A routed expert is a :class:`BlockQuantizedLinear` whose qualified name
163+ contains a ``.moe.experts.`` (or bare ``.experts.``) segment but is *not* a
164+ ``shared_expert``. These are the modules that, absent a sparse top-k MoE
165+ fusion, force a dense loop over all experts.
166+ """
167+ from mobius .components import BlockQuantizedLinear
168+
169+ paths : list [str ] = []
170+ for name , mod in module .named_modules ():
171+ if not isinstance (mod , BlockQuantizedLinear ):
172+ continue
173+ if "shared_expert" in name :
174+ continue
175+ if ".experts." not in name :
176+ continue
177+ paths .append (name )
178+ return paths
179+
180+
181+ def _assert_sparse_moe_capability (module , config , * , source : str , allow_dense : bool ) -> None :
182+ """Fail closed when routed IQ-block experts have no sparse MoE fusion.
183+
184+ The int4 ``MatMulNBits`` dense-fallback → ``com.microsoft::QMoE`` rewrite is
185+ the only sparse MoE path today; native IQ/MXFP4 block experts stay as
186+ per-expert ``BlockQuantizedMatMul`` nodes. Exporting those yields a graph
187+ that evaluates every expert for every token. Refuse by default; only proceed
188+ (with a loud warning) when the caller explicitly opts in.
189+ """
190+ num_experts = int (getattr (config , "num_local_experts" , 0 ) or 0 )
191+ if num_experts <= 0 :
192+ return
193+ dense_paths = _routed_dense_block_expert_paths (module )
194+ if not dense_paths :
195+ return
196+
197+ example = ", " .join (sorted (dense_paths )[:3 ])
198+ detail = (
199+ f"{ len (dense_paths )} routed expert projections (e.g. { example } ) in "
200+ f"{ source !r} lower to per-expert native BlockQuantizedMatMul nodes."
201+ )
202+ if allow_dense :
203+ logger .warning (
204+ "allow_dense_moe: exporting %d routed MoE expert(s) as independent "
205+ "BlockQuantizedMatMul nodes for %s. This recomputes EVERY expert for "
206+ "every token (dense-all-expert compute); it is NOT a performance path "
207+ "and makes no throughput claim. %s" ,
208+ len (dense_paths ),
209+ source ,
210+ detail ,
211+ )
212+ return
213+
214+ raise SparseMoEExportError (
215+ "Sparse-MoE export blocker: "
216+ f"{ detail } No sparse top-k BlockQuantizedMoE fusion exists for these "
217+ "block formats — only int4 MatMulNBits experts are fused into "
218+ "com.microsoft::QMoE. Exporting anyway would build a dense-all-expert "
219+ "graph (every expert evaluated for every token) with no performance "
220+ "guarantee, so the build fails closed. To study the dense fallback, "
221+ "re-run with allow_dense_moe=True (or set "
222+ "MOBIUS_ALLOW_DENSE_MOE_EXPERTS=1); this makes no throughput claim. "
223+ "The supported fix is a sparse IQ-block BlockQuantizedMoE fusion "
224+ "(top-k gather over native-block expert weights)."
225+ )
226+
227+
148228def _preflight_hf_gguf (api : HfApi , repo_id : str , filename : str ) -> None :
149229 """Use Hub metadata to reject known-bad inputs before a multi-GB download."""
150230 source = f"{ repo_id } :{ filename } "
@@ -184,8 +264,14 @@ def _preflight_hf_gguf(api: HfApi, repo_id: str, filename: str) -> None:
184264
185265def _validate_gguf_model (gguf_model , * , source : str ) -> None :
186266 """Validate a parsed GGUF before config extraction or graph construction."""
187- split_count = int (gguf_model .get_metadata ("split.count" , 1 ))
188- _raise_for_sharded_gguf (source = source , split_count = split_count )
267+ from mobius .integrations .gguf ._shard_set import GgufShardSet
268+
269+ # A GgufShardSet has already assembled and structurally validated the whole
270+ # split set, so the single-file "sharded input is unsupported" guard must
271+ # not fire for it. Plain single-file GGUFModels still reject a lone shard.
272+ if not isinstance (gguf_model , GgufShardSet ):
273+ split_count = int (gguf_model .get_metadata ("split.count" , 1 ))
274+ _raise_for_sharded_gguf (source = source , split_count = split_count )
189275 _raise_for_unsupported_gguf_architecture (
190276 gguf_model .architecture ,
191277 source = source ,
@@ -250,6 +336,7 @@ def build_from_gguf(
250336 mmproj : str | Path | None = None ,
251337 static_cache : bool = False ,
252338 max_seq_len : int | None = None ,
339+ allow_dense_moe : bool | None = None ,
253340) -> ModelPackage :
254341 """Build an ONNX :class:`ModelPackage` from a GGUF file.
255342
@@ -308,6 +395,14 @@ def build_from_gguf(
308395 max_seq_len: Maximum sequence length for the static cache buffers.
309396 Only used when ``static_cache=True``. Defaults to the model's
310397 ``max_position_embeddings``.
398+ allow_dense_moe: Opt in to exporting routed MoE experts that have no
399+ sparse top-k fusion (they lower to per-expert native
400+ ``BlockQuantizedMatMul`` nodes, i.e. dense-all-expert compute with
401+ no performance guarantee). When ``None`` (default), the value of
402+ the ``allow_dense_moe_experts`` flag is used, which defaults to
403+ ``False`` — the build fails closed with a typed capability error
404+ rather than silently shipping a dense graph. This is a research /
405+ correctness knob and makes no throughput claim.
311406
312407 Returns:
313408 A :class:`ModelPackage` containing the built model(s).
@@ -346,7 +441,7 @@ def build_from_gguf(
346441 GGUF_ARCH_TO_MODEL_TYPE ,
347442 gguf_to_config ,
348443 )
349- from mobius .integrations .gguf ._reader import GGUFModel
444+ from mobius .integrations .gguf ._shard_set import open_gguf_model
350445 from mobius .integrations .gguf ._tensor_processors import (
351446 process_tensors ,
352447 )
@@ -360,12 +455,19 @@ def build_from_gguf(
360455 "override; the static cache is wired through CausalLMTask."
361456 )
362457
363- # 1. Parse GGUF file (auto-download from HF Hub when given "owner/repo[:filename]")
458+ from mobius ._flags import flags as _mobius_flags
459+
460+ if allow_dense_moe is None :
461+ allow_dense_moe = _mobius_flags .allow_dense_moe_experts
462+
463+ # 1. Parse GGUF file (auto-download from HF Hub when given "owner/repo[:filename]").
464+ # A ``-000i-of-000N.gguf`` split set is assembled directly from its shards
465+ # (never merged into a second on-disk GGUF); a plain file opens as before.
364466 gguf_path = _resolve_gguf_path (gguf_path )
365- gguf_model = GGUFModel (gguf_path )
467+ gguf_model = open_gguf_model (gguf_path )
366468 _validate_gguf_model (gguf_model , source = str (gguf_path ))
367469 gguf_arch = gguf_model .architecture
368- logger .info ("Loaded GGUF file : %s (arch=%s)" , gguf_path , gguf_arch )
470+ logger .info ("Loaded GGUF model : %s (arch=%s)" , gguf_path , gguf_arch )
369471 preserve_quantization = keep_quantized and _has_quantized_weights (gguf_model , gguf_arch )
370472 if keep_quantized and not preserve_quantization :
371473 logger .info ("GGUF contains no mapped quantized weights; using the float import path" )
@@ -376,6 +478,16 @@ def build_from_gguf(
376478 if model_type is None :
377479 model_type = GGUF_ARCH_TO_MODEL_TYPE .get (gguf_arch , gguf_arch )
378480
481+ # 2b. Architecture-resolution safety rail. When the GGUF architecture string
482+ # bridges to a specialised registry key, verify the metadata-derived config
483+ # actually describes that architecture before selecting its model class, so
484+ # a mislabelled or incomplete GGUF fails closed with precise reasons instead
485+ # of silently building the wrong graph.
486+ if model_type == "glm_moe_dsa" :
487+ from mobius .integrations .gguf ._config_mapping import assert_glm_moe_dsa_resolvable
488+
489+ assert_glm_moe_dsa_resolvable (config , gguf_arch , source = str (gguf_path ))
490+
379491 # ``dataclasses.replace`` below (dtype / quantization) returns a fresh
380492 # instance that does NOT carry the private ``_gguf_*`` attributes set by
381493 # gguf_to_config (they are plain attributes, not dataclass fields). Capture
@@ -489,6 +601,13 @@ def build_from_gguf(
489601 module = module_class (config )
490602 if preserve_quantization :
491603 _replace_native_block_linears (module , gguf_model , gguf_arch )
604+ # Sparse-MoE honesty gate: routed experts lowered as native
605+ # BlockQuantizedMatMul nodes have no sparse top-k fusion yet, so the
606+ # exported graph would recompute every expert for every token. Fail
607+ # closed here (before export) unless the caller explicitly opts in.
608+ _assert_sparse_moe_capability (
609+ module , config , source = str (gguf_path ), allow_dense = allow_dense_moe
610+ )
492611 pkg = build_from_module (
493612 module , config , resolved_task , execution_provider = execution_provider
494613 )
@@ -1164,7 +1283,7 @@ def _can_quantize_embedding(
11641283 if is_tencent_q1_0_layout (gguf_model ):
11651284 return False
11661285
1167- for tensor in gguf_model ._reader . tensors :
1286+ for tensor in gguf_model .reader_tensors () :
11681287 if map_gguf_to_hf_names (tensor .name , gguf_arch ) != "model.embed_tokens.weight" :
11691288 continue
11701289 shape = tuple (reversed (tensor .shape ))
@@ -1314,7 +1433,7 @@ def _load_dequantized_state_dict(
13141433 for gguf_name , np_array in tqdm .tqdm (
13151434 gguf_model .tensor_items (),
13161435 desc = "Dequantizing tensors" ,
1317- total = len ( gguf_model ._tensor_index ) ,
1436+ total = gguf_model .num_tensors ,
13181437 ):
13191438 hf_name = name_mapper (gguf_name , gguf_arch )
13201439 if hf_name is not None :
@@ -1415,7 +1534,7 @@ def _load_quantized_state_dict(
14151534 for gguf_name , raw , qtype , np_shape in tqdm .tqdm (
14161535 gguf_model .tensor_items_raw (),
14171536 desc = "Repacking tensors" ,
1418- total = len ( gguf_model ._tensor_index ) ,
1537+ total = gguf_model .num_tensors ,
14191538 ):
14201539 hf_name = name_mapper (gguf_name , gguf_arch )
14211540 if hf_name is None :
0 commit comments