|
| 1 | +# SPDX-FileCopyrightText: 2024-2025 ModelCloud.ai |
| 2 | +# SPDX-FileCopyrightText: 2024-2025 qubitium@modelcloud.ai |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +# Contact: qubitium@modelcloud.ai, x.com/qubitium |
| 5 | +from types import SimpleNamespace |
| 6 | +from typing import Dict, Optional |
| 7 | + |
| 8 | +import requests |
| 9 | +from PIL import Image |
| 10 | +import torch |
| 11 | +from transformers import AutoModelForCausalLM, AutoProcessor, ProcessorMixin |
| 12 | + |
| 13 | +from ...utils.calibration import batched |
| 14 | +from ...utils.image import extract_vision_info, fetch_image |
| 15 | +from ...utils.model import MODALITY, move_to |
| 16 | +from ...utils.offload import offload_to_disk |
| 17 | +from .._const import CPU |
| 18 | +from ..base import BaseQModel |
| 19 | + |
| 20 | +class Ovis2_5QModel(BaseQModel): |
| 21 | + loader = AutoModelForCausalLM |
| 22 | + |
| 23 | + pre_lm_head_norm_module = "llm.model.model.norm" |
| 24 | + |
| 25 | + # HF_CONVERSION_MAP_REVERSED = ( |
| 26 | + # # Ovis 2.5 builds the SigLIP visual backbone via `AutoModel`, whose |
| 27 | + # # runtime shell exposes `visual_tokenizer.vit.*` directly, while |
| 28 | + # # checkpoint tensors still live under `visual_tokenizer.vit.vision_model.*`. |
| 29 | + # SimpleNamespace( |
| 30 | + # source_patterns=[r"^visual_tokenizer\.vit\.(?!vision_model\.)(.+)$"], |
| 31 | + # target_patterns=[r"^visual_tokenizer.vit.vision_model.\1"], |
| 32 | + # operations=[], |
| 33 | + # ), |
| 34 | + # ) |
| 35 | + |
| 36 | + module_tree = [ |
| 37 | + "llm", |
| 38 | + "model", |
| 39 | + "layers", |
| 40 | + "#", |
| 41 | + { |
| 42 | + "input_layernorm": ("input_layernorm:!",), |
| 43 | + "self_attn": ("q_proj:0", "k_proj:0", "v_proj:0", "o_proj:1"), |
| 44 | + "post_attention_layernorm": ("post_attention_layernorm:!",), |
| 45 | + "mlp": ("gate_proj:0", "up_proj:0", "down_proj:1"), |
| 46 | + } |
| 47 | + ] |
| 48 | + |
| 49 | + modality = [MODALITY.IMAGE_TO_TEXT] |
| 50 | + |
| 51 | + require_load_processor = True |
| 52 | + |
| 53 | + def pre_quantize_generate_hook_start(self): |
| 54 | + self.shell_module_materialize(self.model.llm.model.embed_tokens, self.quantize_config.device) |
| 55 | + self.shell_module_materialize(self.model.llm.model.rotary_emb, self.quantize_config.device) |
| 56 | + self.shell_module_materialize(self.model.visual_tokenizer, self.quantize_config.device) |
| 57 | + self.shell_module_materialize(self.model.vte, self.quantize_config.device) |
| 58 | + |
| 59 | + # VisionRotaryEmbedding cannot be correctly reconstructed via `_build_nonpersistent_buffer_template()`. |
| 60 | + # Therefore, VisionRotaryEmbedding is manually reconstructed here. |
| 61 | + rotary_pos_emb_cls = type(self.model.visual_tokenizer.vit.vision_model.encoder.rotary_pos_emb) |
| 62 | + config = self.model.config.vit_config |
| 63 | + assert "VisionRotaryEmbedding" in rotary_pos_emb_cls.__name__ |
| 64 | + rotary_pos_emb = rotary_pos_emb_cls(config.hidden_size // config.num_attention_heads // 2).to(self.quantize_config.device) |
| 65 | + self.model.visual_tokenizer.vit.vision_model.encoder.rotary_pos_emb = rotary_pos_emb |
| 66 | + |
| 67 | + def pre_quantize_generate_hook_end(self): |
| 68 | + if self.quantize_config.offload_to_disk: |
| 69 | + offload_to_disk(model=self.model.llm, |
| 70 | + module=self.model.llm.model.embed_tokens, |
| 71 | + disk_path=self.quantize_config.offload_to_disk_path, |
| 72 | + ) |
| 73 | + offload_to_disk(model=self.model.llm, |
| 74 | + module=self.model.llm.model.rotary_emb, |
| 75 | + disk_path=self.quantize_config.offload_to_disk_path, |
| 76 | + ) |
| 77 | + offload_to_disk(model=self.model, |
| 78 | + module=self.model.visual_tokenizer, |
| 79 | + disk_path=self.quantize_config.offload_to_disk_path, |
| 80 | + ) |
| 81 | + offload_to_disk(model=self.model, |
| 82 | + module=self.model.vte, |
| 83 | + disk_path=self.quantize_config.offload_to_disk_path, |
| 84 | + ) |
| 85 | + return |
| 86 | + |
| 87 | + self.model.llm.model.embed_tokens = move_to(self.model.llm.model.embed_tokens, device=CPU) |
| 88 | + self.model.llm.model.rotary_emb = move_to(self.model.llm.model.rotary_emb, device=CPU) |
| 89 | + self.model.visual_tokenizer = move_to(self.model.visual_tokenizer, device=CPU) |
| 90 | + self.model.vte = move_to(self.model.vte, device=CPU) |
| 91 | + |
| 92 | + def preprocess_dataset(self, sample: Dict) -> Dict: |
| 93 | + return sample |
| 94 | + |
| 95 | + def load_processor(self) -> ProcessorMixin: |
| 96 | + return AutoProcessor.from_pretrained(self.model_local_path) |
| 97 | + |
| 98 | + @staticmethod |
| 99 | + def process_vision_info( |
| 100 | + conversations: list[dict] | list[list[dict]], |
| 101 | + ) -> Optional[list[Image.Image]]: |
| 102 | + vision_infos = extract_vision_info(conversations) |
| 103 | + # Read images |
| 104 | + image_inputs = [] |
| 105 | + for vision_info in vision_infos: |
| 106 | + if "image" in vision_info or "image_url" in vision_info: |
| 107 | + image_inputs.append(fetch_image(vision_info)) |
| 108 | + else: |
| 109 | + raise ValueError("image, image_url should in content.") |
| 110 | + if len(image_inputs) == 0: |
| 111 | + image_inputs = None |
| 112 | + return image_inputs |
| 113 | + |
| 114 | + @staticmethod |
| 115 | + def replace_image_with_pil(sample): |
| 116 | + """ |
| 117 | + image url -> PIL.Image |
| 118 | + """ |
| 119 | + |
| 120 | + for msg in sample: |
| 121 | + if "content" not in msg and not isinstance(msg["content"], dict): |
| 122 | + continue |
| 123 | + |
| 124 | + for item in msg["content"]: |
| 125 | + if isinstance(item, dict) and item.get("type") == "image": |
| 126 | + item["image"] = Image.open( |
| 127 | + requests.get(item["image"], stream=True).raw |
| 128 | + ) |
| 129 | + |
| 130 | + return sample |
| 131 | + |
| 132 | + def prepare_dataset(self, calibration_dataset, batch_size: int = 1, **kwargs): |
| 133 | + calib_data = [] |
| 134 | + for batch in batched(calibration_dataset, batch_size, process_func=self.preprocess_dataset): |
| 135 | + for sample in batch: |
| 136 | + sample = self.replace_image_with_pil(sample) |
| 137 | + input_ids, pixel_values, grid_thws = self.model.preprocess_inputs( |
| 138 | + messages=sample, |
| 139 | + add_generation_prompt=True, |
| 140 | + ) |
| 141 | + attention_mask = torch.ne(input_ids, self.model.text_tokenizer.pad_token_id) |
| 142 | + |
| 143 | + if pixel_values is not None: |
| 144 | + pixel_values = pixel_values.to(dtype=self.model.visual_tokenizer.vit.dtype) |
| 145 | + |
| 146 | + calib_data.append( |
| 147 | + { |
| 148 | + "input_ids": input_ids, |
| 149 | + "attention_mask": attention_mask, |
| 150 | + "pixel_values": pixel_values, |
| 151 | + "grid_thws": grid_thws, |
| 152 | + } |
| 153 | + ) |
| 154 | + return calib_data |
0 commit comments