|
| 1 | +from typing import Optional, Dict, Any, Tuple |
| 2 | +from transformers import PreTrainedModel |
| 3 | +from .quant.awq import AWQQuantizer |
| 4 | +from .quant.gptq import GPTQQuantizer |
| 5 | +from .quant.gguf import GGUFQuantizer |
| 6 | +from .trainer.logger import TrainingLogger |
| 7 | + |
| 8 | +class QuantizerFactory: |
| 9 | + @staticmethod |
| 10 | + def quantize_from_pretrained( |
| 11 | + model_name_or_path: str, |
| 12 | + method: str, |
| 13 | + quant_config_dict: Optional[Dict[str, Any]] = None, |
| 14 | + calibration_data: Optional[Any] = None, # Typically torch.Tensor or similar |
| 15 | + calibration_steps: Optional[int] = 100, # Specific to AWQ's quantize method |
| 16 | + device: Optional[str] = None # Explicit device control |
| 17 | + ) -> Tuple[PreTrainedModel, Any]: # Returns (quantized_model, tokenizer) |
| 18 | + """ |
| 19 | + Loads a model from Hugging Face, quantizes it using the specified method, |
| 20 | + and returns the quantized model and its tokenizer. |
| 21 | +
|
| 22 | + Args: |
| 23 | + model_name_or_path (str): Hugging Face model ID or local path. |
| 24 | + method (str): Quantization method to use ('awq', 'gptq', 'gguf'). |
| 25 | + quant_config_dict (Optional[Dict[str, Any]]): Dictionary with quantization parameters. |
| 26 | + Common keys: 'bits', 'group_size', 'batch_size' (for quantizer init). |
| 27 | + AWQ specific: 'zero_point', 'awq_version' (maps to 'version' in AWQQuantizer). |
| 28 | + GPTQ specific: 'actorder', 'percdamp', 'sym'. |
| 29 | + GGUF specific: 'use_packed', 'cpu_offload', 'desc_act', 'desc_ten', 'legacy_format'. |
| 30 | + calibration_data (Optional[Any]): Calibration data required for quantization. |
| 31 | + calibration_steps (Optional[int]): Number of calibration steps, primarily for AWQ's |
| 32 | + quantize() method. Defaults to 100. |
| 33 | + device (Optional[str]): Device to run quantization on ('cpu', 'cuda', 'cuda:x'). |
| 34 | + If None, default device selection logic in BaseQuantizer is used. |
| 35 | + |
| 36 | + Returns: |
| 37 | + Tuple[PreTrainedModel, Any]: The quantized model and its associated tokenizer. |
| 38 | + |
| 39 | + Raises: |
| 40 | + ValueError: If an unsupported quantization method is specified or essential parameters are missing. |
| 41 | + RuntimeError: If quantization fails for some reason. |
| 42 | + """ |
| 43 | + logger = TrainingLogger() |
| 44 | + if quant_config_dict is None: |
| 45 | + quant_config_dict = {} |
| 46 | + |
| 47 | + method_lower = method.lower() |
| 48 | + logger.log_info(f"Attempting to quantize model '{model_name_or_path}' using method: {method_lower}") |
| 49 | + |
| 50 | + bits = quant_config_dict.get('bits', 4) |
| 51 | + group_size = quant_config_dict.get('group_size', 128) |
| 52 | + quantizer_batch_size = quant_config_dict.get('batch_size', 4) |
| 53 | + |
| 54 | + quantizer = None |
| 55 | + |
| 56 | + if method_lower == 'awq': |
| 57 | + awq_zero_point = quant_config_dict.get('zero_point', True) |
| 58 | + awq_version = quant_config_dict.get('awq_version', 'v2') |
| 59 | + |
| 60 | + quantizer = AWQQuantizer( |
| 61 | + model_or_model_name_or_path=model_name_or_path, |
| 62 | + bits=bits, |
| 63 | + group_size=group_size, |
| 64 | + zero_point=awq_zero_point, |
| 65 | + version=awq_version, |
| 66 | + batch_size=quantizer_batch_size, |
| 67 | + device=device |
| 68 | + ) |
| 69 | + logger.log_info(f"Quantizing with AWQ... Bits: {bits}, Group Size: {group_size}, Zero Point: {awq_zero_point}, Version: {awq_version}") |
| 70 | + quantizer.quantize( # Call quantize, model is updated in place |
| 71 | + calibration_data=calibration_data, |
| 72 | + calibration_steps=calibration_steps |
| 73 | + ) |
| 74 | + |
| 75 | + elif method_lower == 'gptq': |
| 76 | + gptq_actorder = quant_config_dict.get('actorder', True) |
| 77 | + gptq_percdamp = quant_config_dict.get('percdamp', 0.01) |
| 78 | + gptq_sym = quant_config_dict.get('sym', True) |
| 79 | + |
| 80 | + quantizer = GPTQQuantizer( |
| 81 | + model_or_model_name_or_path=model_name_or_path, |
| 82 | + bits=bits, |
| 83 | + group_size=group_size, |
| 84 | + actorder=gptq_actorder, |
| 85 | + percdamp=gptq_percdamp, |
| 86 | + sym=gptq_sym, |
| 87 | + batch_size=quantizer_batch_size, |
| 88 | + device=device |
| 89 | + ) |
| 90 | + logger.log_info(f"Quantizing with GPTQ... Bits: {bits}, Group Size: {group_size}, ActOrder: {gptq_actorder}, Sym: {gptq_sym}") |
| 91 | + quantizer.quantize(calibration_data=calibration_data) # Model updated in place |
| 92 | + |
| 93 | + elif method_lower == 'gguf': |
| 94 | + gguf_use_packed = quant_config_dict.get('use_packed', True) |
| 95 | + gguf_cpu_offload = quant_config_dict.get('cpu_offload', False) |
| 96 | + gguf_desc_act = quant_config_dict.get('desc_act', False) |
| 97 | + gguf_desc_ten = quant_config_dict.get('desc_ten', False) |
| 98 | + gguf_legacy_format = quant_config_dict.get('legacy_format', False) |
| 99 | + |
| 100 | + quantizer = GGUFQuantizer( |
| 101 | + model_or_model_name_or_path=model_name_or_path, |
| 102 | + bits=bits, |
| 103 | + group_size=group_size, |
| 104 | + use_packed=gguf_use_packed, |
| 105 | + cpu_offload=gguf_cpu_offload, |
| 106 | + desc_act=gguf_desc_act, |
| 107 | + desc_ten=gguf_desc_ten, |
| 108 | + legacy_format=gguf_legacy_format, |
| 109 | + batch_size=quantizer_batch_size, |
| 110 | + device=device |
| 111 | + ) |
| 112 | + logger.log_info(f"Quantizing with GGUF... Bits: {bits}, Group Size: {group_size}, Packed: {gguf_use_packed}, CPU Offload: {gguf_cpu_offload}") |
| 113 | + quantizer.quantize(calibration_data=calibration_data) # Model updated in place |
| 114 | + |
| 115 | + else: |
| 116 | + logger.log_error(f"Unsupported quantization method: {method}") |
| 117 | + raise ValueError(f"Unsupported quantization method: {method}. Supported methods are 'awq', 'gptq', 'gguf'.") |
| 118 | + |
| 119 | + if quantizer is None or quantizer.model is None: |
| 120 | + logger.log_error(f"Failed to initialize quantizer or obtain quantized model for method: {method}") |
| 121 | + raise RuntimeError(f"Quantization failed for method: {method}. Quantizer or model is None.") |
| 122 | + |
| 123 | + logger.log_info(f"Successfully quantized model with method: {method_lower}") |
| 124 | + return quantizer.model, quantizer.tokenizer |
0 commit comments