import torch from torch import nn from transformers.models.qwen3.modeling_qwen3 import Qwen3ForCausalLM, Qwen3Model, Qwen3Config from transformers.models.qwen3.configuration_qwen3 import Qwen3Config from transformers import AutoConfig, AutoModelForCausalLM from .fake_quant import W8A8Linear, quantize_llama_like class Qwen3QuantizedConfig(Qwen3Config): """ Configuration class for quantized Qwen3 models """ model_type = "qwen3_quantized" def __init__(self, **kwargs): super().__init__(**kwargs) self.is_quantized = kwargs.get('is_quantized', True) self.quantization_method = kwargs.get('quantization_method', 'smoothquant_int8') class Qwen3ForCausalLMQuantized(Qwen3ForCausalLM): """ Quantized version of Qwen3ForCausalLM that automatically applies quantization and is compatible with AutoModelForCausalLM.from_pretrained """ config_class = Qwen3QuantizedConfig def __init__(self, config): super().__init__(config) # Apply quantization if this is a quantized model if hasattr(config, 'is_quantized') and config.is_quantized: self._apply_quantization() def _apply_quantization(self): """Apply quantization to the model""" print("🔧 Applying quantization to model...") quantize_llama_like(self) # Count quantized layers int8_layers = 0 for name, module in self.named_modules(): if isinstance(module, W8A8Linear): int8_layers += 1 print(f"✅ Converted {int8_layers} layers to quantized W8A8Linear") @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): """ Override from_pretrained to handle quantized models """ # Load config first to check if it's quantized config = AutoConfig.from_pretrained(pretrained_model_name_or_path) if hasattr(config, 'is_quantized') and config.is_quantized: # For quantized models, we need special handling print("🔧 Detected quantized model, loading with special handling...") # Create model instance model = cls(config) # Load state dict manually import os state_dict_path = os.path.join(pretrained_model_name_or_path, "pytorch_model.bin") if os.path.exists(state_dict_path): state_dict = torch.load(state_dict_path, map_location="cpu") missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False) if missing_keys: print(f"Missing keys: {missing_keys}") if unexpected_keys: print(f"Unexpected keys: {unexpected_keys}") # Handle device placement device_map = kwargs.get('device_map', None) if device_map == "auto": model = model.cuda() return model else: # For non-quantized models, use standard loading return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) # Register the quantized model class with its own config AutoConfig.register("qwen3_quantized", Qwen3QuantizedConfig) AutoModelForCausalLM.register(Qwen3QuantizedConfig, Qwen3ForCausalLMQuantized) def create_quantized_model_config(base_config, quantization_method="smoothquant_int8"): """Create a config for quantized model""" config_dict = base_config.to_dict() config_dict['model_type'] = 'qwen3_quantized' config_dict['is_quantized'] = True config_dict['quantization_method'] = quantization_method config_dict['auto_map'] = { "AutoConfig": "quantized_model.Qwen3QuantizedConfig", "AutoModelForCausalLM": "quantized_model.Qwen3ForCausalLMQuantized" } config = Qwen3QuantizedConfig(**config_dict) return config