88
99- **Dequantized** (default): All quantized tensors are dequantized to
1010 float. Simple, but loses the compression benefit of quantization.
11- - **Quantized** (``keep_quantized=True``): Linear-layer weights that
12- use supported GGUF types are repacked into MatMulNBits format.
13- Quantized token embeddings are repacked for GatherBlockQuantized.
14- Other tensors (norms and unsupported quant types) are dequantized.
11+ - **Quantized** (``keep_quantized=True``): Linear-layer weights are
12+ normalized to a common MatMulNBits layout, including mixed presets
13+ such as Q4_K_M. Compatible quantized token embeddings are repacked
14+ for GatherBlockQuantized. Other tensors are dequantized.
1515"""
1616
1717from __future__ import annotations
@@ -108,9 +108,9 @@ def build_from_gguf(
108108 model type.
109109 dtype: Override model dtype (e.g. ``"f16"``). When ``None``,
110110 defaults to float32.
111- keep_quantized: When ``True``, preserve quantization for
112- supported GGUF types (Q4_0, Q4_1, Q8_0) by repacking
113- linear-layer weights into MatMulNBits format .
111+ keep_quantized: When ``True``, preserve quantized linear-layer
112+ weights in MatMulNBits format. Mixed Q4_K_M source types are
113+ normalized to 4-bit, block-32 weights .
114114 execution_provider: Target execution provider for EP-aware
115115 optimisations (e.g. ``"cpu"`` to apply the
116116 GroupQueryAttention rewrite). Defaults to ``"default"``
@@ -328,16 +328,16 @@ def _normalize_gguf_weights(
328328
329329
330330def _detect_quant_params (gguf_model , gguf_arch : str ) -> tuple [int , int , bool ]:
331- """Detect bits, block size, and symmetry from dominant GGUF quant type .
331+ """Detect the common MatMulNBits target for GGUF projection weights .
332332
333- Scans block-level (projection) tensors and returns the bit-width,
334- block size, and symmetry flag of the most common repackable type.
333+ Q4_K-containing mixed presets target 4-bit, block-32 asymmetric
334+ MatMulNBits. Other files use the most common directly repackable type.
335335
336336 Returns:
337337 ``(bits, block_size, is_symmetric)`` tuple.
338338
339339 Raises:
340- ValueError: If no repackable quantized tensors are found.
340+ ValueError: If no mapped or repackable weight tensors are found.
341341 """
342342 from gguf import GGMLQuantizationType
343343
@@ -366,19 +366,39 @@ def _detect_quant_params(gguf_model, gguf_arch: str) -> tuple[int, int, bool]:
366366 counts : Counter = Counter ()
367367 for name , _raw , qtype , _shape in gguf_model .tensor_items_raw ():
368368 hf_name = map_gguf_to_hf_names (name , gguf_arch )
369- if hf_name is None :
369+ if hf_name is None or not hf_name . endswith ( ".weight" ) :
370370 continue
371- if can_repack (qtype .value if hasattr (qtype , "value" ) else qtype ):
372- counts [qtype ] += 1
371+ counts [qtype ] += 1
373372
374373 if not counts :
375374 raise ValueError (
376- "No repackable quantized tensors found in GGUF file. "
375+ "No mapped weight tensors found in GGUF file. "
377376 "Use keep_quantized=False for dequantized import."
378377 )
379378
380- dominant = counts .most_common (1 )[0 ][0 ]
381- params = repack_quant_params (dominant .value )
379+ # Q4_K_M is deliberately a mixed preset. Depending on tensor dimensions
380+ # and importance it may contain mostly Q5_0 plus Q4_K, Q6_K, and Q8_0.
381+ # The presence of Q4_K identifies the desired 4-bit MatMulNBits target;
382+ # choosing only among already-repackable types would incorrectly select
383+ # Q8_0 for the official Qwen2.5-0.5B Q4_K_M file.
384+ if GGMLQuantizationType .Q4_K in counts :
385+ dominant = GGMLQuantizationType .Q4_K
386+ else :
387+ repackable_counts = Counter (
388+ {
389+ qtype : count
390+ for qtype , count in counts .items ()
391+ if can_repack (qtype .value if hasattr (qtype , "value" ) else qtype )
392+ }
393+ )
394+ if not repackable_counts :
395+ raise ValueError (
396+ "No repackable quantized tensors found in GGUF file. "
397+ "Use keep_quantized=False for dequantized import."
398+ )
399+ dominant = repackable_counts .most_common (1 )[0 ][0 ]
400+ dominant_value = dominant .value if hasattr (dominant , "value" ) else dominant
401+ params = repack_quant_params (dominant_value )
382402 assert params is not None
383403 bits , block_size = params
384404 is_sym = type_symmetry [dominant ]
@@ -478,12 +498,13 @@ def _load_quantized_state_dict(
478498 module ,
479499 config ,
480500) -> dict :
481- """Load tensors, repacking supported quantized types .
501+ """Load tensors, normalizing quantized projections to MatMulNBits .
482502
483- Projection weights (Q/K/V/O and MLP) that use repackable GGUF
484- types are converted to MatMulNBits format. Quantized embeddings
485- are converted to GatherBlockQuantized format. All other tensors
486- (norms and unsupported quant types) are dequantized.
503+ Projection weights (Q/K/V/O and MLP) are converted to the graph's
504+ common MatMulNBits format. Mixed source types are dequantized and
505+ requantized when they do not already match that target. Compatible
506+ quantized embeddings are converted for GatherBlockQuantized. Norms
507+ and other non-linear tensors remain dequantized.
487508
488509 For llama-family models, quantized Q/K weights receive the
489510 row-level reverse-permutation that ``process_tensors`` would
@@ -496,6 +517,7 @@ def _load_quantized_state_dict(
496517 from mobius .components import QuantizedEmbedding , QuantizedLinear
497518 from mobius .integrations .gguf ._repacker import (
498519 can_repack ,
520+ repack_dequantized_tensor ,
499521 repack_gguf_tensor ,
500522 )
501523 from mobius .integrations .gguf ._tencent_q1_0 import (
@@ -538,6 +560,10 @@ def _load_quantized_state_dict(
538560
539561 state_dict : dict [str , torch .Tensor ] = {}
540562 n_repacked = 0
563+ n_requantized = 0
564+ target_bits = config .quantization .bits
565+ target_block_size = config .quantization .group_size
566+ target_symmetric = config .quantization .sym
541567
542568 for gguf_name , raw , qtype , np_shape in tqdm .tqdm (
543569 gguf_model .tensor_items_raw (),
@@ -552,15 +578,14 @@ def _load_quantized_state_dict(
552578 # Determine the int value of the quant type for can_repack
553579 qtype_val = qtype .value if hasattr (qtype , "value" ) else qtype
554580
555- # Repack if the tensor is repackable AND its target ONNX
556- # parameter is from a QuantizedLinear module.
581+ # Repack every target QuantizedLinear weight. Mixed GGUF presets
582+ # otherwise leave unsupported source types as full float matrices,
583+ # which cannot fit the graph's packed MatMulNBits initializer shape.
557584 stem = hf_name [: - len (".weight" )] if hf_name .endswith (".weight" ) else None
558585 is_tencent_q1_0_tensor = tencent_q1_0 and qtype == GGMLQuantizationType .Q1_0
559- is_quantized_embedding = stem in quantized_embedding_stems
560- should_repack = (
561- stem is not None
562- and (stem in quantized_stems or is_quantized_embedding )
563- and (can_repack (qtype_val ) or is_tencent_q1_0_tensor )
586+ is_quantized_embedding = stem is not None and stem in quantized_embedding_stems
587+ should_repack = stem is not None and (
588+ stem in quantized_stems or is_quantized_embedding
564589 )
565590
566591 if should_repack :
@@ -570,13 +595,31 @@ def _load_quantized_state_dict(
570595 data_section_offset ,
571596 tensors_by_name [gguf_name ],
572597 )
573- else :
598+ elif can_repack ( qtype_val ) :
574599 shape_2d = (int (np_shape [0 ]), int (np_shape [1 ]))
575600 repacked = repack_gguf_tensor (
576601 raw .ravel ().view (np .uint8 ),
577602 qtype_val ,
578603 shape_2d ,
579604 )
605+ if repacked .bits != target_bits or repacked .block_size != target_block_size :
606+ values = gguf_model .dequantize_raw_tensor (raw , qtype , np_shape )
607+ repacked = repack_dequantized_tensor (
608+ values ,
609+ bits = target_bits ,
610+ block_size = target_block_size ,
611+ symmetric = target_symmetric ,
612+ )
613+ n_requantized += 1
614+ else :
615+ values = gguf_model .dequantize_raw_tensor (raw , qtype , np_shape )
616+ repacked = repack_dequantized_tensor (
617+ values ,
618+ bits = target_bits ,
619+ block_size = target_block_size ,
620+ symmetric = target_symmetric ,
621+ )
622+ n_requantized += 1
580623 w = torch .from_numpy (repacked .weight )
581624 s = torch .from_numpy (repacked .scales )
582625
@@ -619,10 +662,11 @@ def _load_quantized_state_dict(
619662 state_dict [hf_name ] = torch .from_numpy (arr )
620663
621664 logger .info (
622- "Loaded %d tensors (%d repacked for quantized ops, %d dequantized)" ,
665+ "Loaded %d state_dict entries (%d GGUF tensors repacked for quantized ops, "
666+ "%d requantized from mixed source types)" ,
623667 len (state_dict ),
624668 n_repacked ,
625- len ( state_dict ) - n_repacked ,
669+ n_requantized ,
626670 )
627671 return state_dict
628672
0 commit comments