multimodal_engine.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import json
  2. from pathlib import Path
  3. from typing import Any
  4. from app.config import get_settings
  5. from app.core.logging import logger
  6. from app.engines.base import BaseEngine
  7. settings = get_settings()
  8. class MultimodalEngine(BaseEngine):
  9. """多模态模型训练引擎 (LLaVA/Qwen-VL 等视觉语言模型)。"""
  10. def __init__(self):
  11. self._processor = None
  12. self._model = None
  13. async def load_model(self, model_id: str, **kwargs: Any) -> None:
  14. """下载并加载多模态模型。"""
  15. import torch
  16. from transformers import AutoProcessor, LlavaForConditionalGeneration
  17. # 优先从数据库获取实际路径(兼容 ModelScope 下载的目录结构)
  18. from app.services.model_service import resolve_model_path
  19. model_path = await resolve_model_path(model_id)
  20. if model_path:
  21. local_path = model_path
  22. else:
  23. local_path = str(settings.models_dir / model_id.replace("/", "_"))
  24. if not (Path(local_path) / "config.json").exists():
  25. from huggingface_hub import snapshot_download
  26. snapshot_download(repo_id=model_id, local_dir=local_path, local_dir_use_symlinks=False)
  27. self._processor = AutoProcessor.from_pretrained(local_path, trust_remote_code=True)
  28. self._model = LlavaForConditionalGeneration.from_pretrained(
  29. local_path,
  30. torch_dtype=torch.float16,
  31. device_map="auto",
  32. trust_remote_code=True,
  33. )
  34. logger.info(f"Loaded multimodal model: {model_id}")
  35. def get_peft_config(self, method: str, params: dict[str, Any]) -> Any:
  36. from peft import LoraConfig, TaskType
  37. target_modules = params.get("lora_target_modules", "all-linear")
  38. if isinstance(target_modules, str) and target_modules == "all-linear":
  39. target_modules = ["linear", "lm_head", "q_proj", "v_proj", "k_proj", "o_proj"]
  40. return LoraConfig(
  41. r=params.get("lora_r", 16),
  42. lora_alpha=params.get("lora_alpha", 32),
  43. lora_dropout=params.get("lora_dropout", 0.05),
  44. target_modules=target_modules,
  45. task_type=TaskType.CAUSAL_LM,
  46. )
  47. async def preprocess_dataset(
  48. self, dataset_path: str, output_path: str, **kwargs: Any
  49. ) -> str:
  50. """多模态数据集预处理 (image + text pairs)。"""
  51. from app.preprocessors import preprocess_file
  52. processed = preprocess_file(dataset_path, output_path, "sft", "raw")
  53. logger.info(f"Preprocessed {len(processed)} multimodal samples")
  54. return output_path
  55. async def train(
  56. self,
  57. job_id: str,
  58. dataset_path: str,
  59. peft_config: Any,
  60. training_args: dict[str, Any],
  61. callbacks: list | None = None,
  62. ) -> str:
  63. from peft import get_peft_model
  64. from transformers import Trainer, TrainingArguments
  65. from datasets import Dataset as HFDataset
  66. data = []
  67. with open(dataset_path, "r", encoding="utf-8") as f:
  68. for line in f:
  69. line = line.strip()
  70. if line:
  71. data.append(json.loads(line))
  72. def collate_fn(examples):
  73. texts = [item.get("text", "") for item in examples]
  74. image_paths = [item.get("image_path", "") for item in examples if "image_path" in item]
  75. if image_paths:
  76. from PIL import Image
  77. images = [Image.open(p).convert("RGB") for p in image_paths if Path(p).exists()]
  78. if images:
  79. inputs = self._processor(text=texts, images=images, return_tensors="pt", padding=True)
  80. inputs["labels"] = inputs["input_ids"].clone()
  81. return inputs
  82. # fallback: text-only
  83. inputs = self._processor(text=texts, return_tensors="pt", padding=True)
  84. inputs["labels"] = inputs["input_ids"].clone()
  85. return inputs
  86. hf_dataset = HFDataset.from_list(data)
  87. self._model = get_peft_model(self._model, peft_config)
  88. self._model.print_trainable_parameters()
  89. output_dir = str(settings.adapters_dir / job_id)
  90. epochs = training_args.get("epochs", 3)
  91. batch_size = training_args.get("batch_size", 4)
  92. learning_rate = training_args.get("learning_rate", 2e-4)
  93. tr_args = TrainingArguments(
  94. output_dir=output_dir,
  95. num_train_epochs=epochs,
  96. per_device_train_batch_size=batch_size,
  97. learning_rate=learning_rate,
  98. save_strategy="epoch",
  99. logging_steps=10,
  100. fp16=True,
  101. optim="adamw_torch",
  102. remove_unused_columns=False,
  103. report_to="none",
  104. )
  105. all_callbacks = callbacks if callbacks else [_ProgressCallback(job_id)]
  106. trainer = Trainer(
  107. model=self._model,
  108. args=tr_args,
  109. train_dataset=hf_dataset,
  110. data_collator=collate_fn,
  111. callbacks=all_callbacks,
  112. )
  113. try:
  114. trainer.train()
  115. self._model.save_pretrained(output_dir)
  116. self._processor.save_pretrained(output_dir)
  117. logger.info(f"Multimodal training completed for job {job_id}")
  118. except Exception as e:
  119. logger.error(f"Multimodal training failed for job {job_id}: {e}")
  120. raise
  121. return output_dir
  122. def get_model_info(self, model_id: str) -> dict[str, Any]:
  123. model_dir = settings.models_dir / model_id.replace("/", "_")
  124. config_path = model_dir / "config.json"
  125. if config_path.exists():
  126. with open(config_path) as f:
  127. config = json.load(f)
  128. return {
  129. "model_type": config.get("model_type", "multimodal"),
  130. "context_length": config.get("max_position_embeddings", 2048),
  131. "hidden_size": config.get("hidden_size", 0),
  132. "num_layers": config.get("num_hidden_layers", 0),
  133. }
  134. return {"model_type": "multimodal", "context_length": 4096}
  135. class _ProgressCallback:
  136. def __init__(self, job_id: str):
  137. self.job_id = job_id
  138. def on_log(self, args, state, control, logs=None, **kwargs):
  139. if logs and "loss" in logs:
  140. import asyncio
  141. asyncio.create_task(
  142. send_progress(self.job_id, epoch=int(state.epoch or 0), step=state.global_step,
  143. total_steps=state.max_steps or 0, loss=logs["loss"], learning_rate=logs.get("learning_rate", 0))
  144. )
  145. def on_epoch_end(self, args, state, control, **kwargs):
  146. import asyncio
  147. asyncio.create_task(send_epoch_done(self.job_id, epoch=int(state.epoch or 0), eval_loss=None, eval_accuracy=None))
  148. def on_train_end(self, args, state, control, **kwargs):
  149. import asyncio
  150. asyncio.create_task(send_completed(self.job_id, total_time_seconds=getattr(state, "train_runtime", 0),
  151. adapter_path=str(settings.adapters_dir / self.job_id)))
  152. def on_train_begin(self, args, state, control, **kwargs): pass
  153. def on_step_end(self, args, state, control, **kwargs): pass
  154. def on_evaluate(self, args, state, control, metrics=None, **kwargs): pass
  155. def on_save(self, args, state, control, **kwargs): pass
  156. def on_predict(self, args, state, control, metrics=None, **kwargs): pass
  157. def on_init_end(self, args, state, control, **kwargs): pass
  158. def on_epoch_begin(self, args, state, control, **kwargs): pass
  159. from app.core.websocket import send_completed, send_epoch_done, send_progress
  160. multimodal_engine = MultimodalEngine()