MCPcopy Create free account
hub / github.com/pytorch/executorch / apply_embedding_quantization

Function apply_embedding_quantization

examples/models/gemma4/quant_utils.py:65–93  ·  view source on GitHub ↗

Apply embedding quantization (INT8 or INT4).

(
    model: nn.Module,
    mode: str,
    dtype: torch.dtype = torch.float32,
)

Source from the content-addressed store, hash-verified

63
64
65def apply_embedding_quantization(
66 model: nn.Module,
67 mode: str,
68 dtype: torch.dtype = torch.float32,
69) -> nn.Module:
70 """Apply embedding quantization (INT8 or INT4)."""
71 from executorch.examples.models.llama.source_transformation.quantize import (
72 EmbeddingQuantHandler,
73 QuantizedGroupEmbedding,
74 )
75
76 bitwidth = 4 if mode == "emb4" else 8
77 packed = bitwidth == 4
78 logger.info(f"Quantizing embeddings to int{bitwidth} (packed={packed})")
79
80 model = EmbeddingQuantHandler(
81 model,
82 bitwidth=bitwidth,
83 group_size=None,
84 precision=dtype,
85 packed=packed,
86 ).quantized_model()
87
88 for _name, mod in model.named_modules():
89 if isinstance(mod, QuantizedGroupEmbedding):
90 if mod.scales.dtype == torch.bfloat16:
91 mod.register_buffer("scales", mod.scales.to(torch.float16))
92
93 return model

Callers 1

_export_text_decoderFunction · 0.90

Calls 5

infoMethod · 0.80
register_bufferMethod · 0.80
quantized_modelMethod · 0.45
toMethod · 0.45

Tested by

no test coverage detected