Apply embedding quantization (INT8 or INT4).
(
model: nn.Module,
mode: str,
dtype: torch.dtype = torch.float32,
)
| 63 | |
| 64 | |
| 65 | def 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 |
no test coverage detected