text_engine.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. # 禁用 torch.compile,避免每个任务 fork 几十个 inductor worker
  8. os.environ["PT2_COMPILE"] = "0"
  9. os.environ["TORCHINDUCTOR_MAX_WORKERS"] = "1"
  10. # 解决 PyTorch 显存碎片化问题(避免 reserved unallocated 占用大量显存)
  11. os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
  12. # 限制训练只用 GPU 3(GPU 0/1 被 VLLM 占用,GPU 2 已占用)
  13. # CUDA_VISIBLE_DEVICES 将物理 GPU 3 映射为容器内的 cuda:0
  14. # device_map 中使用相对编号 0(对应物理 GPU 3)
  15. os.environ["CUDA_VISIBLE_DEVICES"] = "3"
  16. # 启用 MPS 多进程服务,允许与 VLLM 共享 GPU
  17. os.environ["MACA_MPS_MODE"] = "1"
  18. import asyncio
  19. import json
  20. import logging
  21. from pathlib import Path
  22. from typing import Any
  23. # 远程训练节点没有 pydantic-settings/数据库,直接用环境变量
  24. from types import SimpleNamespace
  25. _data_dir = Path(os.environ.get("COMPUTE_NODE_REMOTE_DATA_DIR", "/root/Fine-tuning/backend/data"))
  26. settings = SimpleNamespace(
  27. data_dir=_data_dir,
  28. processed_dir=_data_dir / "processed",
  29. adapters_dir=_data_dir / "adapters",
  30. models_dir=_data_dir / "models",
  31. )
  32. logger = logging.getLogger(__name__)
  33. from app.engines.base import BaseEngine
  34. class TextEngine(BaseEngine):
  35. """文本模型训练引擎 (LLaMA/Qwen/ChatGLM 等因果语言模型)。"""
  36. def __init__(self):
  37. self._tokenizer = None
  38. self._model = None
  39. async def load_model(self, model_id: str, **kwargs: Any) -> None:
  40. """下载并加载基础模型。GPU 加载超时直接报错。"""
  41. import torch
  42. from transformers import AutoModelForCausalLM, AutoTokenizer
  43. # 远程节点不查数据库,直接扫描本地模型目录
  44. local_path = str(settings.models_dir / model_id.replace("/", "_"))
  45. # 如果本地没有,从 HF 下载
  46. if not (Path(local_path) / "config.json").exists():
  47. ms_path = settings.models_dir / model_id
  48. if (ms_path / "config.json").exists():
  49. local_path = str(ms_path)
  50. else:
  51. from huggingface_hub import snapshot_download
  52. snapshot_download(
  53. repo_id=model_id,
  54. local_dir=local_path,
  55. local_dir_use_symlinks=False,
  56. )
  57. quantization = kwargs.get("quantization", None)
  58. gpu_timeout = int(os.environ.get("GPU_LOAD_TIMEOUT", "30"))
  59. # 记录 GPU 状态
  60. logger.info(f"CUDA available: {torch.cuda.is_available()}")
  61. logger.info(f"CUDA device count: {torch.cuda.device_count()}")
  62. if torch.cuda.is_available():
  63. for i in range(torch.cuda.device_count()):
  64. logger.info(f"GPU {i}: {torch.cuda.get_device_name(i)}")
  65. logger.info(f"GPU {i} memory: {torch.cuda.get_device_properties(i).total_memory / (1024**3):.2f} GB")
  66. else:
  67. raise RuntimeError("No GPU detected! Training requires GPU.")
  68. # CUDA_VISIBLE_DEVICES=3 已将物理 GPU 3 映射为逻辑 GPU 0
  69. device_map = {"": 0}
  70. load_kwargs: dict[str, Any] = {
  71. "dtype": torch.float16,
  72. "device_map": device_map,
  73. "low_cpu_mem_usage": True,
  74. "use_safetensors": True,
  75. "attn_implementation": "sdpa",
  76. }
  77. if quantization == "4bit" or quantization == "qlora":
  78. # 沐曦 GPU 不支持 bitsandbytes/HQQ,直接 fp16 + LoRA
  79. load_kwargs["torch_dtype"] = torch.float16
  80. logger.info("4-bit quantization not supported on this GPU; "
  81. "falling back to fp16 + LoRA")
  82. elif quantization == "8bit":
  83. from transformers import BitsAndBytesConfig
  84. load_kwargs["quantization_config"] = BitsAndBytesConfig(
  85. load_in_8bit=True,
  86. )
  87. self._tokenizer = AutoTokenizer.from_pretrained(local_path, trust_remote_code=True)
  88. if self._tokenizer.pad_token is None:
  89. self._tokenizer.pad_token = self._tokenizer.eos_token
  90. # GPU 加载:用超时包装,避免 MetaX 驱动无限重试卡死
  91. model_load_result = [None]
  92. load_error = [None]
  93. def _load_on_gpu():
  94. try:
  95. model_load_result[0] = AutoModelForCausalLM.from_pretrained(local_path, **load_kwargs)
  96. except Exception as e:
  97. load_error[0] = e
  98. load_thread = __import__("threading").Thread(target=_load_on_gpu, daemon=True)
  99. load_thread.start()
  100. load_thread.join(timeout=gpu_timeout)
  101. if load_thread.is_alive():
  102. raise RuntimeError(
  103. f"GPU model loading timed out after {gpu_timeout}s. "
  104. f"This is usually caused by GPU resource conflict (e.g., VLLM occupying the GPU). "
  105. f"Set GPU_LOAD_TIMEOUT env var to adjust timeout."
  106. )
  107. if load_error[0] is not None:
  108. raise RuntimeError(f"GPU model loading failed: {load_error[0]}")
  109. self._model = model_load_result[0]
  110. logger.info(f"Loaded model on GPU: {model_id}")
  111. def get_peft_config(self, method: str, params: dict[str, Any]) -> Any:
  112. """根据 PEFT 方法返回对应的配置对象。"""
  113. from app.peft import (
  114. build_adalora_config,
  115. build_lora_config,
  116. build_qlora_config,
  117. )
  118. builders = {
  119. "lora": build_lora_config,
  120. "qlora": build_qlora_config,
  121. "adalora": build_adalora_config,
  122. }
  123. builder = builders.get(method, build_lora_config)
  124. return builder(params)
  125. async def preprocess_dataset(
  126. self,
  127. dataset_path: str,
  128. output_path: str,
  129. task_type: str = "sft",
  130. template: str = "alpaca",
  131. **kwargs: Any,
  132. ) -> str:
  133. """将数据集预处理为训练格式。"""
  134. from app.preprocessors import preprocess_file
  135. processed = preprocess_file(dataset_path, output_path, task_type, template)
  136. logger.info(f"Preprocessed {len(processed)} samples for {task_type}/{template}")
  137. return output_path
  138. async def train(
  139. self,
  140. job_id: str,
  141. dataset_path: str,
  142. peft_config: Any,
  143. training_args: dict[str, Any],
  144. callbacks: list | None = None,
  145. ) -> str:
  146. """执行训练。"""
  147. from peft import get_peft_model
  148. from transformers import DataCollatorForSeq2Seq, TrainingArguments
  149. task_type = training_args.get("task_type", "sft")
  150. epochs = training_args.get("epochs", 3)
  151. batch_size = training_args.get("batch_size", 4)
  152. gradient_accumulation = training_args.get("gradient_accumulation", 4)
  153. learning_rate = training_args.get("learning_rate", 2e-4)
  154. max_seq_length = training_args.get("max_seq_length", 2048)
  155. warmup_ratio = training_args.get("warmup_ratio", 0.05)
  156. save_strategy = training_args.get("save_strategy", "epoch")
  157. deepspeed_config = training_args.get("deepspeed", None)
  158. dataset = self._tokenize_dataset(dataset_path, max_seq_length)
  159. # 计算总步数(AdaLoRA 需要在 get_peft_model 之前设置 total_step)
  160. dataset_len = len(dataset)
  161. max_steps = max(1, (dataset_len * epochs) // (batch_size * gradient_accumulation))
  162. # AdaLoRA 要求 total_step > 0(通过属性名判断而非 isinstance,避免导入路径问题)
  163. if hasattr(peft_config, "init_r") and hasattr(peft_config, "target_r"):
  164. peft_config.total_step = max_steps
  165. self._model = get_peft_model(self._model, peft_config)
  166. self._model.print_trainable_parameters()
  167. output_dir = str(settings.adapters_dir / job_id)
  168. tr_args = TrainingArguments(
  169. output_dir=output_dir,
  170. num_train_epochs=epochs,
  171. max_steps=max_steps,
  172. per_device_train_batch_size=batch_size,
  173. gradient_accumulation_steps=gradient_accumulation,
  174. learning_rate=learning_rate,
  175. warmup_ratio=warmup_ratio,
  176. save_strategy=save_strategy,
  177. logging_strategy="steps",
  178. logging_steps=10,
  179. fp16=True,
  180. optim="adamw_torch",
  181. remove_unused_columns=False,
  182. report_to="none",
  183. gradient_checkpointing=True,
  184. dataloader_num_workers=4,
  185. dataloader_pin_memory=False,
  186. **({"deepspeed": deepspeed_config} if deepspeed_config else {}),
  187. )
  188. # 本地模式用 WebSocket 回调,远程模式用传入的文件日志回调
  189. all_callbacks = callbacks if callbacks else [_ProgressCallback(job_id)]
  190. if task_type == "sft":
  191. from transformers import Trainer
  192. trainer = Trainer(
  193. model=self._model,
  194. args=tr_args,
  195. train_dataset=dataset,
  196. data_collator=DataCollatorForSeq2Seq(self._tokenizer),
  197. callbacks=all_callbacks,
  198. )
  199. elif task_type == "dpo":
  200. from trl import DPOConfig, DPOTrainer
  201. base_trainer_kwargs = dict(
  202. output_dir=output_dir,
  203. num_train_epochs=epochs,
  204. max_steps=max_steps,
  205. per_device_train_batch_size=batch_size,
  206. gradient_accumulation_steps=gradient_accumulation,
  207. learning_rate=learning_rate,
  208. warmup_ratio=warmup_ratio,
  209. save_strategy=save_strategy,
  210. logging_steps=10,
  211. fp16=True,
  212. report_to="none",
  213. dataloader_num_workers=4,
  214. dataloader_pin_memory=False,
  215. )
  216. trainer = DPOTrainer(
  217. model=self._model,
  218. args=DPOConfig(**base_trainer_kwargs),
  219. train_dataset=dataset,
  220. processing_class=self._tokenizer,
  221. )
  222. elif task_type == "ppo":
  223. from transformers import Trainer
  224. logger.warning(
  225. "PPO mode: falling back to SFT Trainer. "
  226. "PPO requires a dedicated reward model setup. "
  227. "Current implementation trains as supervised fine-tuning."
  228. )
  229. trainer = Trainer(
  230. model=self._model,
  231. args=tr_args,
  232. train_dataset=dataset,
  233. data_collator=DataCollatorForSeq2Seq(self._tokenizer),
  234. callbacks=all_callbacks,
  235. )
  236. else:
  237. from transformers import Trainer
  238. raise ValueError(f"Unsupported task_type: {task_type}. Supported: sft, dpo, ppo")
  239. try:
  240. trainer.train()
  241. self._model.save_pretrained(output_dir)
  242. self._tokenizer.save_pretrained(output_dir)
  243. logger.info(f"Training completed for job {job_id}")
  244. except Exception as e:
  245. logger.error(f"Training failed for job {job_id}: {e}")
  246. raise
  247. return output_dir
  248. def get_model_info(self, model_id: str) -> dict[str, Any]:
  249. """读取模型配置信息。"""
  250. import json
  251. from pathlib import Path
  252. # 同步查找模型路径(兼容 HF 和 ModelScope)
  253. candidates = [
  254. settings.models_dir / model_id.replace("/", "_"),
  255. settings.models_dir / model_id,
  256. ]
  257. config_path = None
  258. for p in candidates:
  259. if (p / "config.json").exists():
  260. config_path = p / "config.json"
  261. break
  262. if not config_path:
  263. # 最后尝试扫描
  264. model_name = model_id.split("/")[-1]
  265. for cp in settings.models_dir.rglob("config.json"):
  266. if model_name in str(cp.parent):
  267. config_path = cp
  268. break
  269. if config_path.exists():
  270. with open(config_path) as f:
  271. config = json.load(f)
  272. return {
  273. "model_type": config.get("model_type", "causal_lm"),
  274. "context_length": config.get("max_position_embeddings", config.get("max_sequence_length", 2048)),
  275. "hidden_size": config.get("hidden_size", 0),
  276. "num_layers": config.get("num_hidden_layers", 0),
  277. }
  278. return {"model_type": "causal_lm", "context_length": 2048}
  279. def _tokenize_dataset(self, dataset_path: str, max_seq_length: int):
  280. """Tokenize 处理后的 JSONL 数据集。"""
  281. from datasets import Dataset as HFDataset
  282. data = []
  283. with open(dataset_path, "r", encoding="utf-8") as f:
  284. for line in f:
  285. line = line.strip()
  286. if line:
  287. item = json.loads(line)
  288. # 兼容多种列名 → 统一映射为 prompt / completion
  289. if "prompt" not in item:
  290. item["prompt"] = item.get("question", item.get("query", item.get("text", item.get("input", ""))))
  291. if "completion" not in item:
  292. item["completion"] = item.get("answer", item.get("response", item.get("target", item.get("output", ""))))
  293. # 确保 prompt 和 completion 是字符串
  294. if isinstance(item["prompt"], (list, dict)):
  295. item["prompt"] = json.dumps(item["prompt"], ensure_ascii=False)
  296. item["prompt"] = str(item["prompt"])
  297. if isinstance(item["completion"], (list, dict)):
  298. item["completion"] = json.dumps(item["completion"], ensure_ascii=False)
  299. item["completion"] = str(item["completion"])
  300. data.append(item)
  301. hf_dataset = HFDataset.from_list(data)
  302. def tokenize_fn(batch):
  303. def _to_str(v):
  304. if isinstance(v, (list, dict)):
  305. return json.dumps(v, ensure_ascii=False)
  306. return str(v) if v is not None else ""
  307. raw_prompts = batch.get("prompt", [])
  308. raw_completions = batch.get("completion", [])
  309. prompts = [_to_str(v) for v in raw_prompts]
  310. completions = [_to_str(v) for v in raw_completions]
  311. if not prompts:
  312. return {"input_ids": [], "attention_mask": [], "labels": []}
  313. full_texts = [f"{p}\n{c}" for p, c in zip(prompts, completions)]
  314. tokenized = self._tokenizer(
  315. full_texts, truncation=True, max_length=max_seq_length, padding=False,
  316. )
  317. tokenized["labels"] = list(tokenized["input_ids"])
  318. return tokenized
  319. tokenized_dataset = hf_dataset.map(
  320. tokenize_fn,
  321. batched=True,
  322. remove_columns=["prompt", "completion"],
  323. )
  324. return tokenized_dataset
  325. class _ProgressCallback:
  326. """自定义训练进度回调,通过 WebSocket 发送进度。"""
  327. def __init__(self, job_id: str):
  328. self.job_id = job_id
  329. def on_log(self, args, state, control, logs=None, **kwargs):
  330. if logs and "loss" in logs:
  331. asyncio.create_task(
  332. send_progress(
  333. self.job_id,
  334. epoch=int(state.epoch or 0),
  335. step=state.global_step,
  336. total_steps=state.max_steps or 0,
  337. loss=logs["loss"],
  338. learning_rate=logs.get("learning_rate", 0),
  339. )
  340. )
  341. def on_epoch_end(self, args, state, control, **kwargs):
  342. asyncio.create_task(
  343. send_epoch_done(self.job_id, epoch=int(state.epoch or 0), eval_loss=None, eval_accuracy=None)
  344. )
  345. def on_train_end(self, args, state, control, **kwargs):
  346. asyncio.create_task(
  347. send_completed(
  348. self.job_id,
  349. total_time_seconds=getattr(state, "train_runtime", 0),
  350. adapter_path=str(settings.adapters_dir / self.job_id),
  351. )
  352. )
  353. def on_train_begin(self, args, state, control, **kwargs):
  354. pass
  355. def on_step_begin(self, args, state, control, **kwargs):
  356. pass
  357. def on_step_end(self, args, state, control, **kwargs):
  358. pass
  359. def on_evaluate(self, args, state, control, metrics=None, **kwargs):
  360. pass
  361. def on_save(self, args, state, control, **kwargs):
  362. pass
  363. def on_predict(self, args, state, control, metrics=None, **kwargs):
  364. pass
  365. def on_init_end(self, args, state, control, **kwargs):
  366. pass
  367. def on_epoch_begin(self, args, state, control, **kwargs):
  368. pass
  369. # 全局单例
  370. text_engine = TextEngine()