text_engine.py 15 KB

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