vision_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 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. 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 = AutoImageProcessor.from_pretrained(local_path, trust_remote_code=True)
  26. self._model = AutoModelForImageClassification.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 vision 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", "q_proj", "v_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.IMAGE_CLS,
  44. )
  45. async def preprocess_dataset(
  46. self, dataset_path: str, output_path: str, **kwargs: Any
  47. ) -> str:
  48. """图像数据集预处理(提取 image_path + label)。"""
  49. from app.preprocessors import preprocess_file
  50. processed = preprocess_file(dataset_path, output_path, "sft", "raw")
  51. logger.info(f"Preprocessed {len(processed)} vision 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 DataCollatorWithPadding, Trainer, TrainingArguments
  63. from datasets import Dataset as HFDataset
  64. # Load and preprocess data
  65. data = []
  66. with open(dataset_path, "r", encoding="utf-8") as f:
  67. for line in f:
  68. line = line.strip()
  69. if line:
  70. data.append(json.loads(line))
  71. def transform(examples):
  72. images = []
  73. labels = []
  74. for item in examples:
  75. if "image_path" in item and Path(item["image_path"]).exists():
  76. from PIL import Image
  77. images.append(self._processor(Image.open(item["image_path"]).convert("RGB"))["pixel_values"])
  78. labels.append(int(item.get("label", 0)))
  79. elif "text" in item:
  80. # fallback: use text as label for classification
  81. labels.append(item.get("label", 0))
  82. if images:
  83. return {"pixel_values": images, "labels": labels}
  84. return {"pixel_values": [], "labels": []}
  85. hf_dataset = HFDataset.from_list(data)
  86. hf_dataset.set_transform(transform)
  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=DataCollatorWithPadding(self._processor),
  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"Vision training completed for job {job_id}")
  118. except Exception as e:
  119. logger.error(f"Vision 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", "vision"),
  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": "vision", "context_length": 2048}
  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. vision_engine = VisionEngine()