text_engine.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import os
  2. # 禁用 FlashAttention 和 FLA,解决沐曦显卡共享内存不足问题
  3. os.environ["PYTORCH_NO_FLASH"] = "1"
  4. os.environ["FLASH_ATTENTION_ENABLED"] = "0"
  5. os.environ["USE_FLASH_ATTENTION"] = "0"
  6. os.environ["TORCH_FLASH_ATTN"] = "0"
  7. import asyncio
  8. import json
  9. from pathlib import Path
  10. from typing import Any
  11. from app.config import get_settings
  12. from app.core.logging import logger
  13. from app.engines.base import BaseEngine
  14. settings = get_settings()
  15. class TextEngine(BaseEngine):
  16. """文本模型训练引擎 (LLaMA/Qwen/ChatGLM 等因果语言模型)。"""
  17. def __init__(self):
  18. self._tokenizer = None
  19. self._model = None
  20. async def load_model(self, model_id: str, **kwargs: Any) -> None:
  21. """下载并加载基础模型。"""
  22. import torch
  23. from transformers import AutoModelForCausalLM, AutoTokenizer
  24. # 优先从数据库获取实际路径(兼容 ModelScope 下载的目录结构)
  25. from app.services.model_service import resolve_model_path
  26. model_path = await resolve_model_path(model_id)
  27. if model_path:
  28. local_path = model_path
  29. else:
  30. local_path = str(settings.models_dir / model_id.replace("/", "_"))
  31. # 如果本地没有,从 HF 下载
  32. if not (Path(local_path) / "config.json").exists():
  33. from huggingface_hub import snapshot_download
  34. snapshot_download(
  35. repo_id=model_id,
  36. local_dir=local_path,
  37. local_dir_use_symlinks=False,
  38. )
  39. quantization = kwargs.get("quantization", None)
  40. # 日志:检查 GPU 状态
  41. logger.info(f"CUDA available: {torch.cuda.is_available()}")
  42. logger.info(f"CUDA device count: {torch.cuda.device_count()}")
  43. if torch.cuda.is_available():
  44. for i in range(torch.cuda.device_count()):
  45. logger.info(f"GPU {i}: {torch.cuda.get_device_name(i)}")
  46. logger.info(f"GPU {i} memory: {torch.cuda.get_device_properties(i).total_memory / (1024**3):.2f} GB")
  47. else:
  48. logger.warning("No GPU detected! Training will run on CPU.")
  49. max_memory = {i: "4GB" for i in range(torch.cuda.device_count())} if torch.cuda.is_available() else None
  50. load_kwargs: dict[str, Any] = {
  51. "torch_dtype": torch.float16,
  52. "device_map": "auto",
  53. "low_cpu_mem_usage": True,
  54. "use_safetensors": True,
  55. "max_memory": max_memory,
  56. "attn_implementation": "sdpa",
  57. }
  58. if quantization == "4bit" or quantization == "qlora":
  59. load_kwargs["load_in_4bit"] = True
  60. load_kwargs["bnb_4bit_quant_type"] = "nf4"
  61. load_kwargs["bnb_4bit_use_double_quant"] = True
  62. load_kwargs["bnb_4bit_compute_dtype"] = torch.float16
  63. elif quantization == "8bit":
  64. load_kwargs["load_in_8bit"] = True
  65. self._tokenizer = AutoTokenizer.from_pretrained(local_path, trust_remote_code=True)
  66. if self._tokenizer.pad_token is None:
  67. self._tokenizer.pad_token = self._tokenizer.eos_token
  68. self._model = AutoModelForCausalLM.from_pretrained(local_path, **load_kwargs)
  69. logger.info(f"Loaded model: {model_id}")
  70. def get_peft_config(self, method: str, params: dict[str, Any]) -> Any:
  71. """根据 PEFT 方法返回对应的配置对象。"""
  72. from app.peft import (
  73. build_adalora_config,
  74. build_ia3_config,
  75. build_lora_config,
  76. build_prefix_tuning_config,
  77. build_qlora_config,
  78. )
  79. builders = {
  80. "lora": build_lora_config,
  81. "qlora": build_qlora_config,
  82. "ia3": build_ia3_config,
  83. "adalora": build_adalora_config,
  84. "prefix_tuning": build_prefix_tuning_config,
  85. }
  86. builder = builders.get(method, build_lora_config)
  87. return builder(params)
  88. async def preprocess_dataset(
  89. self,
  90. dataset_path: str,
  91. output_path: str,
  92. task_type: str = "sft",
  93. template: str = "alpaca",
  94. **kwargs: Any,
  95. ) -> str:
  96. """将数据集预处理为训练格式。"""
  97. from app.preprocessors import preprocess_file
  98. processed = preprocess_file(dataset_path, output_path, task_type, template)
  99. logger.info(f"Preprocessed {len(processed)} samples for {task_type}/{template}")
  100. return output_path
  101. async def train(
  102. self,
  103. job_id: str,
  104. dataset_path: str,
  105. peft_config: Any,
  106. training_args: dict[str, Any],
  107. callbacks: list | None = None,
  108. ) -> str:
  109. """执行训练。"""
  110. from peft import get_peft_model
  111. from transformers import DataCollatorForSeq2Seq, TrainingArguments
  112. task_type = training_args.get("task_type", "sft")
  113. epochs = training_args.get("epochs", 3)
  114. batch_size = training_args.get("batch_size", 4)
  115. gradient_accumulation = training_args.get("gradient_accumulation", 4)
  116. learning_rate = training_args.get("learning_rate", 2e-4)
  117. max_seq_length = training_args.get("max_seq_length", 2048)
  118. warmup_ratio = training_args.get("warmup_ratio", 0.05)
  119. save_strategy = training_args.get("save_strategy", "epoch")
  120. deepspeed_config = training_args.get("deepspeed", None)
  121. dataset = self._tokenize_dataset(dataset_path, max_seq_length)
  122. self._model = get_peft_model(self._model, peft_config)
  123. self._model.print_trainable_parameters()
  124. output_dir = str(settings.adapters_dir / job_id)
  125. tr_args = TrainingArguments(
  126. output_dir=output_dir,
  127. num_train_epochs=epochs,
  128. per_device_train_batch_size=batch_size,
  129. gradient_accumulation_steps=gradient_accumulation,
  130. learning_rate=learning_rate,
  131. warmup_ratio=warmup_ratio,
  132. save_strategy=save_strategy,
  133. logging_strategy="steps",
  134. logging_steps=10,
  135. fp16=True,
  136. optim="adamw_torch",
  137. remove_unused_columns=False,
  138. report_to="none",
  139. gradient_checkpointing=False,
  140. dataloader_num_workers=0,
  141. dataloader_pin_memory=False,
  142. **({"deepspeed": deepspeed_config} if deepspeed_config else {}),
  143. )
  144. # 本地模式用 WebSocket 回调,远程模式用传入的文件日志回调
  145. all_callbacks = callbacks if callbacks else [_ProgressCallback(job_id)]
  146. if task_type == "sft":
  147. from transformers import Trainer
  148. trainer = Trainer(
  149. model=self._model,
  150. args=tr_args,
  151. train_dataset=dataset,
  152. data_collator=DataCollatorForSeq2Seq(self._tokenizer),
  153. callbacks=all_callbacks,
  154. )
  155. else:
  156. from trl import (
  157. DPOConfig,
  158. DPOTrainer,
  159. KTOConfig,
  160. KTOTrainer,
  161. ORPOConfig,
  162. ORPOTrainer,
  163. )
  164. base_trainer_kwargs = dict(
  165. output_dir=output_dir,
  166. num_train_epochs=epochs,
  167. per_device_train_batch_size=batch_size,
  168. gradient_accumulation_steps=gradient_accumulation,
  169. learning_rate=learning_rate,
  170. warmup_ratio=warmup_ratio,
  171. save_strategy=save_strategy,
  172. logging_steps=10,
  173. fp16=True,
  174. report_to="none",
  175. )
  176. if task_type == "dpo":
  177. trainer = DPOTrainer(
  178. model=self._model,
  179. args=DPOConfig(**base_trainer_kwargs),
  180. train_dataset=dataset,
  181. processing_class=self._tokenizer,
  182. )
  183. elif task_type == "orpo":
  184. trainer = ORPOTrainer(
  185. model=self._model,
  186. args=ORPOConfig(**base_trainer_kwargs),
  187. train_dataset=dataset,
  188. processing_class=self._tokenizer,
  189. )
  190. elif task_type == "kto":
  191. trainer = KTOTrainer(
  192. model=self._model,
  193. args=KTOConfig(**base_trainer_kwargs),
  194. train_dataset=dataset,
  195. processing_class=self._tokenizer,
  196. )
  197. else:
  198. trainer = Trainer(
  199. model=self._model,
  200. args=tr_args,
  201. train_dataset=dataset,
  202. data_collator=DataCollatorForSeq2Seq(self._tokenizer),
  203. callbacks=all_callbacks,
  204. )
  205. try:
  206. trainer.train()
  207. self._model.save_pretrained(output_dir)
  208. self._tokenizer.save_pretrained(output_dir)
  209. logger.info(f"Training completed for job {job_id}")
  210. except Exception as e:
  211. logger.error(f"Training failed for job {job_id}: {e}")
  212. raise
  213. return output_dir
  214. def get_model_info(self, model_id: str) -> dict[str, Any]:
  215. """读取模型配置信息。"""
  216. import json
  217. from pathlib import Path
  218. # 同步查找模型路径(兼容 HF 和 ModelScope)
  219. candidates = [
  220. settings.models_dir / model_id.replace("/", "_"),
  221. settings.models_dir / model_id,
  222. ]
  223. config_path = None
  224. for p in candidates:
  225. if (p / "config.json").exists():
  226. config_path = p / "config.json"
  227. break
  228. if not config_path:
  229. # 最后尝试扫描
  230. model_name = model_id.split("/")[-1]
  231. for cp in settings.models_dir.rglob("config.json"):
  232. if model_name in str(cp.parent):
  233. config_path = cp
  234. break
  235. if config_path.exists():
  236. with open(config_path) as f:
  237. config = json.load(f)
  238. return {
  239. "model_type": config.get("model_type", "causal_lm"),
  240. "context_length": config.get("max_position_embeddings", config.get("max_sequence_length", 2048)),
  241. "hidden_size": config.get("hidden_size", 0),
  242. "num_layers": config.get("num_hidden_layers", 0),
  243. }
  244. return {"model_type": "causal_lm", "context_length": 2048}
  245. def _tokenize_dataset(self, dataset_path: str, max_seq_length: int):
  246. """Tokenize 处理后的 JSONL 数据集。"""
  247. from datasets import Dataset as HFDataset
  248. data = []
  249. with open(dataset_path, "r", encoding="utf-8") as f:
  250. for line in f:
  251. line = line.strip()
  252. if line:
  253. item = json.loads(line)
  254. # 确保 prompt 和 completion 是字符串
  255. if "prompt" in item:
  256. if isinstance(item["prompt"], (list, dict)):
  257. item["prompt"] = json.dumps(item["prompt"], ensure_ascii=False)
  258. item["prompt"] = str(item["prompt"])
  259. if "completion" in item:
  260. if isinstance(item["completion"], (list, dict)):
  261. item["completion"] = json.dumps(item["completion"], ensure_ascii=False)
  262. item["completion"] = str(item["completion"])
  263. data.append(item)
  264. hf_dataset = HFDataset.from_list(data)
  265. def tokenize_fn(batch):
  266. def _to_str(v):
  267. if isinstance(v, (list, dict)):
  268. return json.dumps(v, ensure_ascii=False)
  269. return str(v) if v is not None else ""
  270. raw_prompts = batch.get("prompt", [])
  271. raw_completions = batch.get("completion", [])
  272. prompts = [_to_str(v) for v in raw_prompts]
  273. completions = [_to_str(v) for v in raw_completions]
  274. if not prompts:
  275. return {"input_ids": [], "attention_mask": [], "labels": []}
  276. full_texts = [f"{p}\n{c}" for p, c in zip(prompts, completions)]
  277. tokenized = self._tokenizer(
  278. full_texts, truncation=True, max_length=max_seq_length, padding=False,
  279. )
  280. tokenized["labels"] = list(tokenized["input_ids"])
  281. return tokenized
  282. tokenized_dataset = hf_dataset.map(
  283. tokenize_fn,
  284. batched=True,
  285. remove_columns=["prompt", "completion"],
  286. )
  287. return tokenized_dataset
  288. class _ProgressCallback:
  289. """自定义训练进度回调,通过 WebSocket 发送进度。"""
  290. def __init__(self, job_id: str):
  291. self.job_id = job_id
  292. def on_log(self, args, state, control, logs=None, **kwargs):
  293. if logs and "loss" in logs:
  294. asyncio.create_task(
  295. send_progress(
  296. self.job_id,
  297. epoch=int(state.epoch or 0),
  298. step=state.global_step,
  299. total_steps=state.max_steps or 0,
  300. loss=logs["loss"],
  301. learning_rate=logs.get("learning_rate", 0),
  302. )
  303. )
  304. def on_epoch_end(self, args, state, control, **kwargs):
  305. asyncio.create_task(
  306. send_epoch_done(self.job_id, epoch=int(state.epoch or 0), eval_loss=None, eval_accuracy=None)
  307. )
  308. def on_train_end(self, args, state, control, **kwargs):
  309. asyncio.create_task(
  310. send_completed(
  311. self.job_id,
  312. total_time_seconds=getattr(state, "train_runtime", 0),
  313. adapter_path=str(settings.adapters_dir / self.job_id),
  314. )
  315. )
  316. def on_train_begin(self, args, state, control, **kwargs):
  317. pass
  318. def on_step_begin(self, args, state, control, **kwargs):
  319. pass
  320. def on_step_end(self, args, state, control, **kwargs):
  321. pass
  322. def on_evaluate(self, args, state, control, metrics=None, **kwargs):
  323. pass
  324. def on_save(self, args, state, control, **kwargs):
  325. pass
  326. def on_predict(self, args, state, control, metrics=None, **kwargs):
  327. pass
  328. def on_init_end(self, args, state, control, **kwargs):
  329. pass
  330. def on_epoch_begin(self, args, state, control, **kwargs):
  331. pass
  332. # 全局单例
  333. text_engine = TextEngine()