1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
| import os import json import random import torch import io import pandas as pd import pyarrow.parquet as pq from PIL import Image import torch.nn as nn import torch.nn.functional as F from typing import List, Dict, Any from transformers import ( PreTrainedModel, PretrainedConfig, AutoTokenizer, AutoModelForCausalLM, AutoProcessor, AutoModel, Trainer, TrainingArguments ) from transformers.modeling_outputs import CausalLMOutputWithPast from torch.utils.data import Dataset from tqdm import tqdm
class VLMConfig(PretrainedConfig): model_type = "vlm_model"
def __init__( self, llm_model_path='model/Qwen2.5-0.5B-Instruct', vision_model_path='model/siglip-base-patch16-224', freeze_vision_model=True, freeze_llm_model=True, image_pad_num=49, **kwargs ): self.vision_model_path = vision_model_path self.llm_model_path = llm_model_path self.freeze_vision_model = freeze_vision_model self.freeze_llm_model = freeze_llm_model self.image_pad_num = image_pad_num super().__init__(**kwargs)
class VLM(PreTrainedModel): config_class = VLMConfig
def __init__(self, config): super().__init__(config) self.config = config self.vision_model = AutoModel.from_pretrained(self.config.vision_model_path) self.processor = AutoProcessor.from_pretrained(self.config.vision_model_path) self.llm_model = AutoModelForCausalLM.from_pretrained(self.config.llm_model_path) self.tokenizer = AutoTokenizer.from_pretrained(self.config.llm_model_path) if '<|image_pad|>' not in self.tokenizer.get_vocab(): self.tokenizer.add_special_tokens({'additional_special_tokens': ['<|image_pad|>']}) self.llm_model.resize_token_embeddings(len(self.tokenizer)) vision_hidden_size = self.vision_model.config.vision_config.hidden_size llm_hidden_size = self.llm_model.config.hidden_size self.linear1 = nn.Linear(vision_hidden_size * 4, llm_hidden_size) self.linear2 = nn.Linear(llm_hidden_size, llm_hidden_size) if self.config.freeze_vision_model: for param in self.vision_model.parameters(): param.requires_grad = False if self.config.freeze_llm_model: for param in self.llm_model.parameters(): param.requires_grad = False def forward(self, input_ids, labels, pixel_values, attention_mask=None): text_embeds = self.llm_model.get_input_embeddings()(input_ids) if pixel_values is not None: image_embeds = self.vision_model.vision_model(pixel_values).last_hidden_state b, s, d = image_embeds.shape image_embeds = image_embeds.view(b, -1, d*4) image_features = self.linear2(F.silu(self.linear1(image_embeds))) text_embeds = text_embeds.to(image_features.dtype) inputs_embeds = self.merge_input_ids_with_image_features(image_features, text_embeds, input_ids) else: inputs_embeds = text_embeds outputs = self.llm_model( inputs_embeds=inputs_embeds, attention_mask=attention_mask, labels=labels, return_dict=True ) return outputs def merge_input_ids_with_image_features(self, image_features, inputs_embeds, input_ids): image_pad_id = self.tokenizer.convert_tokens_to_ids('<|image_pad|>') batch_indices, image_indices = torch.where(input_ids == image_pad_id) unique_batch_indices = batch_indices.unique() for batch_idx in unique_batch_indices: pad_positions = image_indices[batch_indices == batch_idx] if len(pad_positions) >= self.config.image_pad_num: pad_positions = pad_positions[:self.config.image_pad_num] for i, pos in enumerate(pad_positions): if i < image_features.shape[1]: inputs_embeds[batch_idx, pos] = image_features[batch_idx, i] return inputs_embeds
class MedicalImageDataset(Dataset): def __init__(self, data_dir, tokenizer, processor, image_pad_num=49): self.data_dir = data_dir self.tokenizer = tokenizer self.processor = processor self.image_pad_num = image_pad_num self.data = [] self.instructions = [ "Describe the following image in detail", "Provide a detailed description of the given image", "Give an elaborate explanation of the image you see", "Share a comprehensive rundown of the presented image", "Offer a thorough analysis of the image", "Explain the various aspects of the image before you", "Clarify the contents of the displayed image with great detail", "Characterize the image using a well-detailed description", "Break down the elements of the image in a detailed manner", "Walk through the important details of the image", "Portray the image with a rich, descriptive narrative", "Narrate the contents of the image with precision", "Analyze the image in a comprehensive and detailed manner", "Illustrate the image through a descriptive explanation", "Examine the image closely and share its details", "Write an exhaustive depiction of the given image" ] parquet_files = [f for f in os.listdir(data_dir) if f.endswith('.parquet')] print(f"Found {len(parquet_files)} parquet files") for pq_file in tqdm(parquet_files, desc="Loading data"): file_path = os.path.join(data_dir, pq_file) table = pq.read_table(file_path) df = table.to_pandas() for _, row in df.iterrows(): if all(field in row for field in ['image', 'caption', 'id']): image_bytes = row['image']['bytes'] if isinstance(row['image'], dict) and 'bytes' in row['image'] else None self.data.append({ 'image': image_bytes, 'caption': row['caption'], 'id': row['id'] }) print(f"Loaded {len(self.data)} image-caption pairs") def __len__(self): return len(self.data) def __getitem__(self, idx): item = self.data[idx] instruction = random.choice(self.instructions) prompt = f"{instruction}\n" + "<|image_pad|>" * self.image_pad_num answer = item['caption'] try: image = Image.open(io.BytesIO(item['image'])).convert('RGB') pixel_values = self.processor(images=image, return_tensors="pt").pixel_values.squeeze(0) if type(pixel_values) != torch.Tensor: print("Wrong!!!!!!!!!!!!!!!!!") except Exception as e: print(f"Error loading image {item['id']}: {e}") image = Image.new('RGB', (224, 224), color='white') pixel_values = self.processor(text=None, images=image, return_tensors="pt")['pixel_values'] system = "You are a helpful medical image analysis assistant." user_message = prompt assistant_message = answer text = f"{system}\n\nUser: {user_message}\n\nAssistant: {assistant_message}" encoding = self.tokenizer(text, return_tensors="pt", padding="max_length", truncation=True, max_length=512) input_ids = encoding["input_ids"][0] attention_mask = encoding["attention_mask"][0] assistant_start = text.find("Assistant: ") if assistant_start != -1: prefix_text = text[:assistant_start] prefix_tokens = self.tokenizer(prefix_text, add_special_tokens=False)["input_ids"] assistant_pos = len(prefix_tokens) if self.tokenizer.bos_token_id is not None: assistant_pos += 1 else: assistant_pos = len(input_ids) // 2 labels = input_ids.clone() labels[:assistant_pos] = -100 return { "input_ids": input_ids, "attention_mask": attention_mask, "labels": labels, "pixel_values": pixel_values }
class MyDataCollator: def __init__(self, tokenizer): self.tokenizer = tokenizer def __call__(self, features): valid_features = [] for f in features: if f["pixel_values"] is not None and isinstance(f["pixel_values"], torch.Tensor): valid_features.append(f) else: print(f"Warning: Skipping invalid sample with None or non-tensor pixel_values") if not valid_features: raise ValueError("No valid samples in batch!") batch = { "input_ids": torch.stack([f["input_ids"] for f in valid_features]), "attention_mask": torch.stack([f["attention_mask"] for f in valid_features]), "labels": torch.stack([f["labels"] for f in valid_features]), "pixel_values": torch.stack([f["pixel_values"] for f in valid_features]) } return batch
def main(): config = VLMConfig( llm_model_path='model/Qwen2.5-0.5B-Instruct', vision_model_path='model/siglip-base-patch16-224', freeze_vision_model=True, freeze_llm_model=True, image_pad_num=49 ) model = VLM(config) tokenizer = AutoTokenizer.from_pretrained(config.llm_model_path) processor = AutoProcessor.from_pretrained(config.vision_model_path) tokenizer.add_special_tokens({'additional_special_tokens': ['<|image_pad|>']}) if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token total_params = sum(p.numel() for p in model.parameters()) trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) print(f"总参数量: {total_params}, 可训练参数量: {trainable_params}") dataset = MedicalImageDataset( data_dir="data/MedTrinity", tokenizer=tokenizer, processor=processor, image_pad_num=49 ) training_args = TrainingArguments( output_dir="./output", num_train_epochs=1, per_device_train_batch_size=8, gradient_accumulation_steps=4, save_steps=500, save_total_limit=2, learning_rate=1e-4, warmup_steps=500, logging_dir="./logs", logging_steps=50, eval_strategy="no", fp16=True, dataloader_num_workers=4, report_to="tensorboard", ) trainer = Trainer( model=model, args=training_args, train_dataset=dataset, data_collator=MyDataCollator(tokenizer), ) trainer.train() trainer.save_model("./final_model") print("训练完成,模型已保存到 ./final_model")
if __name__ == "__main__": main()
|