vision_engine.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 VisionEngine(BaseEngine):
  9. """视觉模型训练引擎 (ViT/CLIP/图像分类)。"""
  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 AutoImageProcessor, AutoModelForImageClassification
  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 = AutoImageProcessor.from_pretrained(local_path, trust_remote_code=True)
  28. self._model = AutoModelForImageClassification.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 vision 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", "q_proj", "v_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.IMAGE_CLS,
  46. )
  47. async def preprocess_dataset(
  48. self, dataset_path: str, output_path: str, **kwargs: Any
  49. ) -> str:
  50. """图像数据集预处理(提取 image_path + label)。"""
  51. from app.preprocessors import preprocess_file
  52. processed = preprocess_file(dataset_path, output_path, "sft", "raw")
  53. logger.info(f"Preprocessed {len(processed)} vision 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. ) -> str:
  62. from peft import get_peft_model
  63. from transformers import DataCollatorWithPadding, Trainer, TrainingArguments
  64. from datasets import Dataset as HFDataset
  65. # Load and preprocess data
  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 transform(examples):
  73. images = []
  74. labels = []
  75. for item in examples:
  76. if "image_path" in item and Path(item["image_path"]).exists():
  77. from PIL import Image
  78. images.append(self._processor(Image.open(item["image_path"]).convert("RGB"))["pixel_values"])
  79. labels.append(int(item.get("label", 0)))
  80. elif "text" in item:
  81. # fallback: use text as label for classification
  82. labels.append(item.get("label", 0))
  83. if images:
  84. return {"pixel_values": images, "labels": labels}
  85. return {"pixel_values": [], "labels": []}
  86. hf_dataset = HFDataset.from_list(data)
  87. hf_dataset.set_transform(transform)
  88. self._model = get_peft_model(self._model, peft_config)
  89. self._model.print_trainable_parameters()
  90. output_dir = str(settings.adapters_dir / job_id)
  91. epochs = training_args.get("epochs", 3)
  92. batch_size = training_args.get("batch_size", 4)
  93. learning_rate = training_args.get("learning_rate", 2e-4)
  94. tr_args = TrainingArguments(
  95. output_dir=output_dir,
  96. num_train_epochs=epochs,
  97. per_device_train_batch_size=batch_size,
  98. learning_rate=learning_rate,
  99. save_strategy="epoch",
  100. logging_steps=10,
  101. fp16=True,
  102. optim="adamw_torch",
  103. remove_unused_columns=False,
  104. report_to="none",
  105. )
  106. callback = _ProgressCallback(job_id)
  107. trainer = Trainer(
  108. model=self._model,
  109. args=tr_args,
  110. train_dataset=hf_dataset,
  111. data_collator=DataCollatorWithPadding(self._processor),
  112. callbacks=[callback],
  113. )
  114. try:
  115. trainer.train()
  116. self._model.save_pretrained(output_dir)
  117. self._processor.save_pretrained(output_dir)
  118. logger.info(f"Vision training completed for job {job_id}")
  119. except Exception as e:
  120. logger.error(f"Vision training failed for job {job_id}: {e}")
  121. raise
  122. return output_dir
  123. def get_model_info(self, model_id: str) -> dict[str, Any]:
  124. model_dir = settings.models_dir / model_id.replace("/", "_")
  125. config_path = model_dir / "config.json"
  126. if config_path.exists():
  127. with open(config_path) as f:
  128. config = json.load(f)
  129. return {
  130. "model_type": config.get("model_type", "vision"),
  131. "context_length": config.get("max_position_embeddings", 2048),
  132. "hidden_size": config.get("hidden_size", 0),
  133. "num_layers": config.get("num_hidden_layers", 0),
  134. }
  135. return {"model_type": "vision", "context_length": 2048}
  136. class _ProgressCallback:
  137. def __init__(self, job_id: str):
  138. self.job_id = job_id
  139. def on_log(self, args, state, control, logs=None, **kwargs):
  140. if logs and "loss" in logs:
  141. import asyncio
  142. asyncio.create_task(
  143. send_progress(self.job_id, epoch=int(state.epoch or 0), step=state.global_step,
  144. total_steps=state.max_steps or 0, loss=logs["loss"], learning_rate=logs.get("learning_rate", 0))
  145. )
  146. def on_epoch_end(self, args, state, control, **kwargs):
  147. import asyncio
  148. asyncio.create_task(send_epoch_done(self.job_id, epoch=int(state.epoch or 0), eval_loss=None, eval_accuracy=None))
  149. def on_train_end(self, args, state, control, **kwargs):
  150. import asyncio
  151. asyncio.create_task(send_completed(self.job_id, total_time_seconds=getattr(state, "train_runtime", 0),
  152. adapter_path=str(settings.adapters_dir / self.job_id)))
  153. def on_train_begin(self, args, state, control, **kwargs): pass
  154. def on_step_end(self, args, state, control, **kwargs): pass
  155. def on_evaluate(self, args, state, control, metrics=None, **kwargs): pass
  156. def on_save(self, args, state, control, **kwargs): pass
  157. def on_predict(self, args, state, control, metrics=None, **kwargs): pass
  158. from app.core.websocket import send_completed, send_epoch_done, send_progress
  159. vision_engine = VisionEngine()