multimodal_engine.py 7.4 KB

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