99- **Dequantized** (default): All quantized tensors are dequantized to
1010 float. Simple, but loses the compression benefit of quantization.
1111- **Quantized** (``keep_quantized=True``): Linear-layer weights that
12- use supported GGUF types (Q4_0, Q4_1, Q8_0) are repacked into
13- MatMulNBits format. Other tensors (norms, embeddings) are
14- dequantized as usual .
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 .
1515"""
1616
1717from __future__ import annotations
@@ -169,6 +169,12 @@ def build_from_gguf(
169169 bits , block_size , is_sym = _detect_quant_params (gguf_model , gguf_arch )
170170 # Float zero-point only when actually using Tencent's native 2-bit form.
171171 float_zp = is_tencent_q1_0_layout (gguf_model ) and flags .tencent_q1_0_use_native_2bit
172+ quantize_embeddings = _can_quantize_embedding (
173+ gguf_model ,
174+ gguf_arch ,
175+ bits = bits ,
176+ block_size = block_size ,
177+ )
172178 config = dataclasses .replace (
173179 config ,
174180 quantization = QuantizationConfig (
@@ -177,14 +183,18 @@ def build_from_gguf(
177183 quant_method = "gguf" ,
178184 sym = is_sym ,
179185 float_zero_point = float_zp ,
186+ quantize_embeddings = quantize_embeddings ,
187+ quantize_lm_head = quantize_embeddings and config .tie_word_embeddings ,
188+ tie_word_embeddings = quantize_embeddings and config .tie_word_embeddings ,
180189 ),
181190 )
182191 logger .info (
183- "Quantized mode: bits=%d, block_size=%d, symmetric=%s, float_zp=%s" ,
192+ "Quantized mode: bits=%d, block_size=%d, symmetric=%s, float_zp=%s, embedding=%s " ,
184193 bits ,
185194 block_size ,
186195 is_sym ,
187196 float_zp ,
197+ quantize_embeddings ,
188198 )
189199
190200 # 4. Look up module class and resolve task
@@ -331,26 +341,26 @@ def _detect_quant_params(gguf_model, gguf_arch: str) -> tuple[int, int, bool]:
331341 """
332342 from gguf import GGMLQuantizationType
333343
334- from mobius .integrations .gguf ._repacker import can_repack
344+ from mobius .integrations .gguf ._repacker import can_repack , repack_quant_params
335345 from mobius .integrations .gguf ._tencent_q1_0 import is_tencent_q1_0_layout
336346 from mobius .integrations .gguf ._tensor_mapping import (
337347 map_gguf_to_hf_names ,
338348 )
339349
340- # Per-type parameters: (bits, block_size, is_symmetric) .
350+ # Symmetry of each supported GGUF quantization type .
341351 #
342352 # Mainline Q1_0 (1-bit binary) is repacked into 2-bit MatMulNBits
343353 # with zp=1 — see _repack_q1_0. Tencent's custom Q1_0 (2-bit SEQ,
344354 # 512-elt blocks) is inflated to 4-bit MatMulNBits with zp=3 — see
345355 # parse_tencent_q1_0_tensor — because the ORT CPU unpacked-float-zp
346356 # path is currently only implemented for bits=4, and the half-integer
347357 # SEQ offset 1.5 cannot be expressed with integer zp at bits=2.
348- type_params : dict = {
349- GGMLQuantizationType .Q4_0 : ( 4 , 32 , True ) ,
350- GGMLQuantizationType .Q4_1 : ( 4 , 32 , False ) ,
351- GGMLQuantizationType .Q4_K : ( 4 , 32 , False ) ,
352- GGMLQuantizationType .Q8_0 : ( 8 , 32 , True ) ,
353- GGMLQuantizationType .Q1_0 : ( 2 , 128 , False ) ,
358+ type_symmetry : dict = {
359+ GGMLQuantizationType .Q4_0 : True ,
360+ GGMLQuantizationType .Q4_1 : False ,
361+ GGMLQuantizationType .Q4_K : False ,
362+ GGMLQuantizationType .Q8_0 : True ,
363+ GGMLQuantizationType .Q1_0 : False ,
354364 }
355365
356366 counts : Counter = Counter ()
@@ -368,7 +378,10 @@ def _detect_quant_params(gguf_model, gguf_arch: str) -> tuple[int, int, bool]:
368378 )
369379
370380 dominant = counts .most_common (1 )[0 ][0 ]
371- bits , block_size , is_sym = type_params [dominant ]
381+ params = repack_quant_params (dominant .value )
382+ assert params is not None
383+ bits , block_size = params
384+ is_sym = type_symmetry [dominant ]
372385
373386 # Tencent Q1_0 files reuse the Q1_0 type id but ship a different
374387 # on-disk layout (2-bit SEQ, 512-element blocks, fp16 scale per block).
@@ -395,6 +408,40 @@ def _detect_quant_params(gguf_model, gguf_arch: str) -> tuple[int, int, bool]:
395408 return bits , block_size , is_sym
396409
397410
411+ def _can_quantize_embedding (
412+ gguf_model ,
413+ gguf_arch : str ,
414+ * ,
415+ bits : int ,
416+ block_size : int ,
417+ ) -> bool :
418+ """Return whether the token embedding can use GatherBlockQuantized.
419+
420+ The graph has one quantization configuration shared by its quantized
421+ modules. Preserve the GGUF embedding only when its repacked representation
422+ uses the same bit width and block size as the projection weights.
423+ """
424+ from mobius .integrations .gguf ._repacker import repack_quant_params
425+ from mobius .integrations .gguf ._tencent_q1_0 import is_tencent_q1_0_layout
426+ from mobius .integrations .gguf ._tensor_mapping import map_gguf_to_hf_names
427+
428+ # Tencent files reuse the Q1_0 type id for a custom layout that gguf-py
429+ # cannot size correctly. Embeddings from those files must stay dequantized.
430+ if is_tencent_q1_0_layout (gguf_model ):
431+ return False
432+
433+ for tensor in gguf_model ._reader .tensors :
434+ if map_gguf_to_hf_names (tensor .name , gguf_arch ) != "model.embed_tokens.weight" :
435+ continue
436+ shape = tuple (reversed (tensor .shape ))
437+ if len (shape ) != 2 :
438+ return False
439+ qtype = tensor .tensor_type
440+ qtype_val = qtype .value if hasattr (qtype , "value" ) else qtype
441+ return repack_quant_params (qtype_val ) == (bits , block_size )
442+ return False
443+
444+
398445def _load_dequantized_state_dict (
399446 gguf_model ,
400447 gguf_arch : str ,
@@ -434,8 +481,9 @@ def _load_quantized_state_dict(
434481 """Load tensors, repacking supported quantized types.
435482
436483 Projection weights (Q/K/V/O and MLP) that use repackable GGUF
437- types are converted to MatMulNBits format. All other tensors
438- (norms, embeddings, unsupported quant types) are dequantized.
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.
439487
440488 For llama-family models, quantized Q/K weights receive the
441489 row-level reverse-permutation that ``process_tensors`` would
@@ -445,7 +493,7 @@ def _load_quantized_state_dict(
445493 import torch
446494 from gguf import GGMLQuantizationType , dequantize
447495
448- from mobius .components import QuantizedLinear
496+ from mobius .components import QuantizedEmbedding , QuantizedLinear
449497 from mobius .integrations .gguf ._repacker import (
450498 can_repack ,
451499 repack_gguf_tensor ,
@@ -464,9 +512,12 @@ def _load_quantized_state_dict(
464512 # Collect module paths that use QuantizedLinear so we know
465513 # which .weight parameters should receive repacked data.
466514 quantized_stems = set ()
515+ quantized_embedding_stems = set ()
467516 for mod_name , mod in module .named_modules ():
468517 if isinstance (mod , QuantizedLinear ):
469518 quantized_stems .add (mod_name )
519+ elif isinstance (mod , QuantizedEmbedding ):
520+ quantized_embedding_stems .add (mod_name )
470521
471522 num_heads = getattr (config , "num_attention_heads" , None )
472523 num_kv_heads = getattr (config , "num_key_value_heads" , None )
@@ -505,9 +556,10 @@ def _load_quantized_state_dict(
505556 # parameter is from a QuantizedLinear module.
506557 stem = hf_name [: - len (".weight" )] if hf_name .endswith (".weight" ) else None
507558 is_tencent_q1_0_tensor = tencent_q1_0 and qtype == GGMLQuantizationType .Q1_0
559+ is_quantized_embedding = stem in quantized_embedding_stems
508560 should_repack = (
509561 stem is not None
510- and stem in quantized_stems
562+ and ( stem in quantized_stems or is_quantized_embedding )
511563 and (can_repack (qtype_val ) or is_tencent_q1_0_tensor )
512564 )
513565
@@ -541,7 +593,10 @@ def _load_quantized_state_dict(
541593 w = _reverse_permute (w , n_head )
542594 s = _reverse_permute (s , n_head )
543595
544- state_dict [hf_name ] = w
596+ if is_quantized_embedding :
597+ state_dict [f"{ stem } .qweight" ] = w .reshape (w .shape [0 ], - 1 )
598+ else :
599+ state_dict [hf_name ] = w
545600 state_dict [f"{ stem } .scales" ] = s
546601 if repacked .zero_points is not None :
547602 zp = torch .from_numpy (repacked .zero_points )
@@ -564,7 +619,7 @@ def _load_quantized_state_dict(
564619 state_dict [hf_name ] = torch .from_numpy (arr )
565620
566621 logger .info (
567- "Loaded %d tensors (%d repacked as MatMulNBits , %d dequantized)" ,
622+ "Loaded %d tensors (%d repacked for quantized ops , %d dequantized)" ,
568623 len (state_dict ),
569624 n_repacked ,
570625 len (state_dict ) - n_repacked ,
0 commit comments