text_engine.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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. # CUDA_VISIBLE_DEVICES 由 docker exec 层设置(remote_executor.py),此处不再覆盖
  13. # 单 GPU 模式: "3" (物理 GPU 3 → 逻辑 cuda:0)
  14. # 多 GPU 模式: "2,3" (物理 GPU 2,3 → 逻辑 cuda:0,1)
  15. # 启用 MPS 多进程服务,允许与 VLLM 共享 GPU
  16. os.environ["MACA_MPS_MODE"] = "1"
  17. import asyncio
  18. import json
  19. import logging
  20. from pathlib import Path
  21. from typing import Any
  22. from types import SimpleNamespace
  23. # 确定数据目录:优先用 DATA_DIR 环境变量,否则从 .env 文件读取,最后兜底
  24. def _resolve_data_dir() -> Path:
  25. v = os.environ.get("DATA_DIR") or os.environ.get("COMPUTE_NODE_REMOTE_DATA_DIR")
  26. if v:
  27. return Path(v)
  28. # 从 .env 文件读取 DATA_DIR(pydantic-settings 加载 .env 但不导出到 os.environ)
  29. env_file = Path(__file__).resolve().parent.parent.parent / ".env"
  30. if env_file.exists():
  31. for line in env_file.read_text():
  32. if line.strip().startswith("DATA_DIR="):
  33. return Path(line.split("=", 1)[1].strip())
  34. return Path("/root/Fine-tuning/backend/data")
  35. _data_dir = _resolve_data_dir()
  36. settings = SimpleNamespace(
  37. data_dir=_data_dir,
  38. processed_dir=_data_dir / "processed",
  39. adapters_dir=_data_dir / "adapters",
  40. models_dir=_data_dir / "models",
  41. )
  42. logger = logging.getLogger(__name__)
  43. from app.engines.base import BaseEngine
  44. class TextEngine(BaseEngine):
  45. """文本模型训练引擎 (LLaMA/Qwen/ChatGLM 等因果语言模型)。"""
  46. def __init__(self):
  47. self._tokenizer = None
  48. self._model = None
  49. async def load_model(self, model_id: str, **kwargs: Any) -> None:
  50. """下载并加载基础模型。GPU 加载超时直接报错。"""
  51. import torch
  52. from transformers import AutoModelForCausalLM, AutoTokenizer
  53. # 远程节点不查数据库,直接扫描本地模型目录
  54. local_path = str(settings.models_dir / model_id.replace("/", "_"))
  55. # 如果本地没有,从 HF 下载
  56. if not (Path(local_path) / "config.json").exists():
  57. ms_path = settings.models_dir / model_id
  58. if (ms_path / "config.json").exists():
  59. local_path = str(ms_path)
  60. else:
  61. from huggingface_hub import snapshot_download
  62. snapshot_download(
  63. repo_id=model_id,
  64. local_dir=local_path,
  65. local_dir_use_symlinks=False,
  66. )
  67. quantization = kwargs.get("quantization", None)
  68. gpu_timeout = int(os.environ.get("GPU_LOAD_TIMEOUT", "30"))
  69. # 记录 GPU 状态
  70. logger.info(f"CUDA available: {torch.cuda.is_available()}")
  71. logger.info(f"CUDA device count: {torch.cuda.device_count()}")
  72. if torch.cuda.is_available():
  73. for i in range(torch.cuda.device_count()):
  74. logger.info(f"GPU {i}: {torch.cuda.get_device_name(i)}")
  75. logger.info(f"GPU {i} memory: {torch.cuda.get_device_properties(i).total_memory / (1024**3):.2f} GB")
  76. else:
  77. raise RuntimeError("No GPU detected! Training requires GPU.")
  78. # DDP 模式: LOCAL_RANK 由 torchrun 设置;单 GPU 模式默认为 0
  79. local_rank = int(os.environ.get("LOCAL_RANK", "0"))
  80. device_map = {"": local_rank}
  81. load_kwargs: dict[str, Any] = {
  82. "dtype": torch.float16,
  83. "device_map": device_map,
  84. "low_cpu_mem_usage": True,
  85. "use_safetensors": True,
  86. "attn_implementation": "sdpa",
  87. }
  88. if quantization == "4bit" or quantization == "qlora":
  89. # 沐曦 GPU 不支持 bitsandbytes/HQQ,直接 fp16 + LoRA
  90. load_kwargs["torch_dtype"] = torch.float16
  91. logger.info("4-bit quantization not supported on this GPU; "
  92. "falling back to fp16 + LoRA")
  93. elif quantization == "8bit":
  94. # 沐曦 GPU 不支持 bitsandbytes,直接 fp16 + LoRA
  95. load_kwargs["torch_dtype"] = torch.float16
  96. logger.info("8-bit quantization not supported on this GPU; "
  97. "falling back to fp16 + LoRA")
  98. self._tokenizer = AutoTokenizer.from_pretrained(local_path, trust_remote_code=True)
  99. if self._tokenizer.pad_token is None:
  100. self._tokenizer.pad_token = self._tokenizer.eos_token
  101. # GPU 加载:用超时包装,避免 MetaX 驱动无限重试卡死
  102. model_load_result = [None]
  103. load_error = [None]
  104. def _load_on_gpu():
  105. try:
  106. model_load_result[0] = AutoModelForCausalLM.from_pretrained(local_path, **load_kwargs)
  107. except Exception as e:
  108. load_error[0] = e
  109. load_thread = __import__("threading").Thread(target=_load_on_gpu, daemon=True)
  110. load_thread.start()
  111. load_thread.join(timeout=gpu_timeout)
  112. if load_thread.is_alive():
  113. raise RuntimeError(
  114. f"GPU model loading timed out after {gpu_timeout}s. "
  115. f"This is usually caused by GPU resource conflict (e.g., VLLM occupying the GPU). "
  116. f"Set GPU_LOAD_TIMEOUT env var to adjust timeout."
  117. )
  118. if load_error[0] is not None:
  119. raise RuntimeError(f"GPU model loading failed: {load_error[0]}")
  120. self._model = model_load_result[0]
  121. logger.info(f"Loaded model on GPU: {model_id}")
  122. def get_peft_config(self, method: str, params: dict[str, Any]) -> Any:
  123. """根据 PEFT 方法返回对应的配置对象。"""
  124. from app.peft import (
  125. build_adalora_config,
  126. build_lora_config,
  127. build_qlora_config,
  128. )
  129. builders = {
  130. "lora": build_lora_config,
  131. "qlora": build_qlora_config,
  132. "adalora": build_adalora_config,
  133. }
  134. builder = builders.get(method, build_lora_config)
  135. return builder(params)
  136. async def preprocess_dataset(
  137. self,
  138. dataset_path: str,
  139. output_path: str,
  140. task_type: str = "sft",
  141. template: str = "alpaca",
  142. **kwargs: Any,
  143. ) -> str:
  144. """将数据集预处理为训练格式。"""
  145. from app.preprocessors import preprocess_file
  146. processed = preprocess_file(dataset_path, output_path, task_type, template)
  147. logger.info(f"Preprocessed {len(processed)} samples for {task_type}/{template}")
  148. return output_path
  149. async def train(
  150. self,
  151. job_id: str,
  152. dataset_path: str,
  153. peft_config: Any,
  154. training_args: dict[str, Any],
  155. callbacks: list | None = None,
  156. ) -> str:
  157. """执行训练。"""
  158. from peft import get_peft_model
  159. from transformers import DataCollatorForSeq2Seq, TrainingArguments
  160. # 防御 JSON 反序列化时 null → None:dict.get 的 default 只在 key 不存在时生效,
  161. # 如果 key 存在但值为 None(来自前端传 null 或 JSON 中写了 null),仍返回 None。
  162. # 用 `if v is None` 显式兜底,确保后续算术运算不会 TypeError。
  163. task_type = training_args.get("task_type", "sft")
  164. if task_type is None:
  165. task_type = "sft"
  166. epochs = training_args.get("epochs", 3)
  167. if epochs is None:
  168. epochs = 3
  169. batch_size = training_args.get("batch_size", 4)
  170. if batch_size is None:
  171. batch_size = 4
  172. gradient_accumulation = training_args.get("gradient_accumulation", 4)
  173. if gradient_accumulation is None:
  174. gradient_accumulation = 4
  175. learning_rate = training_args.get("learning_rate", 2e-4)
  176. if learning_rate is None:
  177. learning_rate = 2e-4
  178. max_seq_length = training_args.get("max_seq_length", 2048)
  179. if max_seq_length is None:
  180. max_seq_length = 2048
  181. warmup_ratio = training_args.get("warmup_ratio", 0.05)
  182. if warmup_ratio is None:
  183. warmup_ratio = 0.05
  184. save_strategy = training_args.get("save_strategy", "epoch")
  185. if save_strategy is None:
  186. save_strategy = "epoch"
  187. deepspeed_config = training_args.get("deepspeed", None)
  188. # DDP 支持
  189. local_rank = int(os.environ.get("LOCAL_RANK", "0"))
  190. world_size = int(os.environ.get("WORLD_SIZE", "1"))
  191. is_ddp = world_size > 1
  192. # SFT 需要预先 tokenize;DPO/PPO 各自处理数据
  193. if task_type == "sft":
  194. dataset = self._tokenize_dataset(dataset_path, max_seq_length)
  195. elif task_type == "dpo":
  196. dataset = self._load_dataset_dpo(dataset_path)
  197. else:
  198. dataset = None # PPO 在后面单独处理
  199. # 计算总步数(DDP 模式下 Trainer 自动按 world_size 分发数据)
  200. if dataset is not None:
  201. dataset_len = len(dataset)
  202. else:
  203. # PPO: 从文件行数估算
  204. with open(dataset_path, "r", encoding="utf-8") as f:
  205. dataset_len = sum(1 for line in f if line.strip())
  206. effective_batch = batch_size * gradient_accumulation * world_size
  207. max_steps = max(1, (dataset_len * epochs) // effective_batch)
  208. # AdaLoRA 要求 total_step > 0(通过属性名判断而非 isinstance,避免导入路径问题)
  209. if hasattr(peft_config, "init_r") and hasattr(peft_config, "target_r"):
  210. peft_config.total_step = max_steps
  211. # PPO 需要先用 AutoModelForCausalLMWithValueHead 包装,再应用 PEFT(后面单独处理)
  212. if task_type != "ppo":
  213. self._model = get_peft_model(self._model, peft_config)
  214. self._model.print_trainable_parameters()
  215. output_dir = str(settings.adapters_dir / job_id)
  216. tr_args = TrainingArguments(
  217. output_dir=output_dir,
  218. num_train_epochs=epochs,
  219. max_steps=max_steps,
  220. per_device_train_batch_size=batch_size,
  221. gradient_accumulation_steps=gradient_accumulation,
  222. learning_rate=learning_rate,
  223. warmup_ratio=warmup_ratio,
  224. save_strategy=save_strategy,
  225. logging_strategy="steps",
  226. logging_steps=10,
  227. fp16=True,
  228. optim="adamw_torch",
  229. remove_unused_columns=False,
  230. report_to="none",
  231. gradient_checkpointing=True,
  232. dataloader_num_workers=4,
  233. dataloader_pin_memory=False,
  234. local_rank=local_rank if is_ddp else -1,
  235. ddp_find_unused_parameters=False if is_ddp else None,
  236. **({"deepspeed": deepspeed_config} if deepspeed_config else {}),
  237. )
  238. # 本地模式用 WebSocket 回调,远程模式用传入的文件日志回调
  239. # 用 is None 判断而非 falsy,因为 DDP 非 rank 0 传入空列表 [],不需要进度回调
  240. all_callbacks = callbacks if callbacks is not None else [_ProgressCallback(job_id)]
  241. if task_type == "sft":
  242. from transformers import Trainer
  243. trainer = Trainer(
  244. model=self._model,
  245. args=tr_args,
  246. train_dataset=dataset,
  247. data_collator=DataCollatorForSeq2Seq(self._tokenizer),
  248. callbacks=all_callbacks,
  249. )
  250. elif task_type == "dpo":
  251. from copy import deepcopy
  252. # 兼容旧版 transformers(缺少 MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
  253. import transformers.models.auto.modeling_auto as _ma
  254. if not hasattr(_ma, "MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES"):
  255. _ma.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = {}
  256. from trl import DPOConfig, DPOTrainer
  257. # 兼容旧版 transformers:Trainer.__init__ 不接受 tokenizer/processing_class
  258. from transformers import Trainer as _HFTrainer
  259. _orig_trainer_init = _HFTrainer.__init__
  260. if not getattr(_HFTrainer, "_patched_kwargs", False):
  261. def _patched_trainer_init(self, *args, **kwargs):
  262. kwargs.pop("tokenizer", None)
  263. kwargs.pop("processing_class", None)
  264. _orig_trainer_init(self, *args, **kwargs)
  265. _HFTrainer.__init__ = _patched_trainer_init
  266. _HFTrainer._patched_kwargs = True
  267. # 兼容:新版 transformers Trainer 调用 get_batch_samples(epoch_iterator, num_batches, device)
  268. # 但 TRL 0.9.6 的签名是 get_batch_samples(model, batch),参数语义不同
  269. if not getattr(DPOTrainer, "_patched_gbs", False):
  270. _orig_gbs = DPOTrainer.get_batch_samples
  271. def _patched_gbs(self, epoch_iterator, num_batches, device=None):
  272. batch = next(epoch_iterator)
  273. if device:
  274. batch = {k: v.to(device) if hasattr(v, "to") else v for k, v in batch.items()}
  275. _orig_gbs(self, self.model, batch)
  276. num_items = len(batch.get("input_ids", batch.get("prompt_input_ids", [])))
  277. return [batch], num_items
  278. DPOTrainer.get_batch_samples = _patched_gbs
  279. DPOTrainer._patched_gbs = True
  280. # 修复 Qwen tokenizer bug:tokenize 后 input_ids 末尾可能追加 None
  281. # 导致 DPODataCollatorWithPadding 中 torch.tensor([...None...], dtype=int64) 报错
  282. # 参考: https://github.com/huggingface/trl/issues/1073
  283. #
  284. # 注意:不能用 types.MethodType 绑定到实例上,因为 Python 的特殊方法查找
  285. # (如 obj() → type(obj).__call__(obj))会跳过实例属性,直接查类。
  286. # 必须在类级别替换 __call__。
  287. _tok_cls = type(self._tokenizer)
  288. if not getattr(_tok_cls, "_patched_none_filter", False):
  289. _orig_cls_call = _tok_cls.__call__
  290. def _call_filter_none(cls_self, *args, **kwargs):
  291. result = _orig_cls_call(cls_self, *args, **kwargs)
  292. if isinstance(result, dict) and "input_ids" in result:
  293. ids = result["input_ids"]
  294. if isinstance(ids, list) and ids:
  295. if isinstance(ids[0], list):
  296. result["input_ids"] = [
  297. [x for x in seq if x is not None] for seq in ids
  298. ]
  299. else:
  300. result["input_ids"] = [x for x in ids if x is not None]
  301. return result
  302. _tok_cls.__call__ = _call_filter_none
  303. _tok_cls._patched_none_filter = True
  304. logger.info(f"Patched {_tok_cls.__name__}.__call__ to filter None from input_ids (Qwen workaround)")
  305. # 显式创建 reference model 并冻结,避免 AdaLora 多 adapter 冲突
  306. ref_model = deepcopy(self._model)
  307. ref_model.eval()
  308. for param in ref_model.parameters():
  309. param.requires_grad = False
  310. # 将 ref_model 上的 PEFT adapter 设为推理模式
  311. # AdaLora 只允许 1 个可训练 adapter,policy model 已有 1 个
  312. if hasattr(ref_model, "set_adapter"):
  313. try:
  314. ref_model.set_adapter("default", inference_mode=True)
  315. except Exception:
  316. pass
  317. elif hasattr(ref_model, "peft_config"):
  318. for adapter_name in list(ref_model.peft_config.keys()):
  319. try:
  320. ref_model.peft_config[adapter_name].inference_mode = True
  321. except Exception:
  322. pass
  323. base_trainer_kwargs = dict(
  324. output_dir=output_dir,
  325. num_train_epochs=epochs,
  326. max_steps=max_steps,
  327. per_device_train_batch_size=batch_size,
  328. gradient_accumulation_steps=gradient_accumulation,
  329. learning_rate=learning_rate,
  330. warmup_ratio=warmup_ratio,
  331. save_strategy=save_strategy,
  332. logging_steps=10,
  333. fp16=True,
  334. report_to="none",
  335. remove_unused_columns=False,
  336. dataloader_num_workers=0,
  337. dataloader_pin_memory=False,
  338. max_length=max_seq_length,
  339. max_prompt_length=max_seq_length // 2,
  340. )
  341. trainer = DPOTrainer(
  342. model=self._model,
  343. ref_model=ref_model,
  344. args=DPOConfig(**base_trainer_kwargs),
  345. train_dataset=dataset,
  346. tokenizer=self._tokenizer,
  347. )
  348. elif task_type == "ppo":
  349. import torch
  350. from trl import AutoModelForCausalLMWithValueHead, PPOConfig, PPOTrainer
  351. ppo_epochs = training_args.get("ppo_epochs", 4)
  352. vf_coef = training_args.get("vf_coef", 0.1)
  353. kl_coef = training_args.get("kl_coef", 0.2)
  354. response_length = training_args.get("response_length", 512)
  355. reward_model_path = training_args.get("reward_model_path")
  356. reward_type = training_args.get("reward_type", "heuristic")
  357. # PPO 专用:仅 tokenize prompt
  358. ppo_dataset = self._tokenize_dataset_ppo(dataset_path, max_seq_length, response_length)
  359. # PPO 需要 AutoModelForCausalLMWithValueHead(添加 value head 用于评估动作价值)
  360. # 通过 peft_config 参数让 TRL 内部处理 PEFT 包装,返回的对象是 PreTrainedModelWrapper
  361. # 不能用 get_peft_model(会产生 PeftModel,PPOTrainer 不认)
  362. self._model = AutoModelForCausalLMWithValueHead.from_pretrained(
  363. self._model, peft_config=peft_config,
  364. )
  365. if hasattr(self._model, "print_trainable_parameters"):
  366. self._model.print_trainable_parameters()
  367. # TRL 0.9.x PPOConfig 只接受 PPO 专用参数,不支持 HuggingFace Trainer 参数
  368. # mini_batch_size 必须满足:batch_size % (mini_batch_size * gradient_accumulation_steps) == 0
  369. ppo_config = PPOConfig(
  370. learning_rate=learning_rate,
  371. batch_size=batch_size,
  372. mini_batch_size=1,
  373. gradient_accumulation_steps=gradient_accumulation,
  374. ppo_epochs=ppo_epochs,
  375. vf_coef=vf_coef,
  376. init_kl_coef=kl_coef,
  377. )
  378. # ref_model=None 让 PPOTrainer 自动创建冻结的 reference model(用于 KL 惩罚)
  379. trainer = PPOTrainer(
  380. config=ppo_config,
  381. model=self._model,
  382. ref_model=None,
  383. tokenizer=self._tokenizer,
  384. dataset=ppo_dataset,
  385. )
  386. dataloader = trainer.dataloader
  387. total_steps = len(dataloader) * epochs
  388. step_count = 0
  389. for epoch in range(epochs):
  390. for batch in dataloader:
  391. step_count += 1
  392. query_tensors = batch["input_ids"]
  393. # 生成回答
  394. response_tensors = []
  395. for query in query_tensors:
  396. query_tensor = torch.tensor(query).unsqueeze(0).to(self._model.device)
  397. gen_output = self._model.generate(
  398. query_tensor,
  399. max_new_tokens=response_length,
  400. do_sample=True,
  401. top_p=0.9,
  402. temperature=0.7,
  403. )
  404. response_tensors.append(gen_output[0][query_tensor.shape[-1]:])
  405. # 解码文本用于奖励计算
  406. responses_text = [
  407. self._tokenizer.decode(r, skip_special_tokens=True)
  408. for r in response_tensors
  409. ]
  410. prompts_text = [
  411. self._tokenizer.decode(q, skip_special_tokens=True)
  412. for q in query_tensors
  413. ]
  414. # 计算奖励
  415. if reward_type == "model" and reward_model_path:
  416. from transformers import AutoModelForSequenceClassification
  417. reward_model = AutoModelForSequenceClassification.from_pretrained(
  418. reward_model_path, device_map={"": 0}
  419. )
  420. reward_inputs = [p + r for p, r in zip(prompts_text, responses_text)]
  421. tokenized = self._tokenizer(
  422. reward_inputs, return_tensors="pt", padding=True, truncation=True
  423. ).to(self._model.device)
  424. with torch.no_grad():
  425. rewards = reward_model(**tokenized).logits.squeeze(-1).tolist()
  426. else:
  427. rewards = _compute_heuristic_reward(prompts_text, responses_text)
  428. reward_tensors = [torch.tensor(r, device=self._model.device) for r in rewards]
  429. # PPO 更新
  430. stats = trainer.step(query_tensors, response_tensors, reward_tensors)
  431. # 报告进度
  432. if step_count % 10 == 0:
  433. for cb in (all_callbacks or []):
  434. if hasattr(cb, "on_log"):
  435. cb.on_log(
  436. SimpleNamespace(),
  437. SimpleNamespace(
  438. epoch=epoch, global_step=step_count, max_steps=total_steps
  439. ),
  440. None,
  441. logs={
  442. "loss": stats.get("ppo/loss/total", 0),
  443. "learning_rate": stats.get("ppo/learning_rate", learning_rate),
  444. },
  445. )
  446. os.makedirs(output_dir, exist_ok=True)
  447. self._model.save_pretrained(output_dir)
  448. self._tokenizer.save_pretrained(output_dir)
  449. logger.info(f"PPO training completed for job {job_id}")
  450. return output_dir
  451. else:
  452. raise ValueError(f"Unsupported task_type: {task_type}. Supported: sft, dpo, ppo")
  453. try:
  454. trainer.train()
  455. self._model.save_pretrained(output_dir)
  456. self._tokenizer.save_pretrained(output_dir)
  457. logger.info(f"Training completed for job {job_id}")
  458. except Exception as e:
  459. logger.error(f"Training failed for job {job_id}: {e}")
  460. raise
  461. return output_dir
  462. def get_model_info(self, model_id: str) -> dict[str, Any]:
  463. """读取模型配置信息。"""
  464. import json
  465. from pathlib import Path
  466. # 同步查找模型路径(兼容 HF 和 ModelScope)
  467. candidates = [
  468. settings.models_dir / model_id.replace("/", "_"),
  469. settings.models_dir / model_id,
  470. ]
  471. config_path = None
  472. for p in candidates:
  473. if (p / "config.json").exists():
  474. config_path = p / "config.json"
  475. break
  476. if not config_path:
  477. # 最后尝试扫描
  478. model_name = model_id.split("/")[-1]
  479. for cp in settings.models_dir.rglob("config.json"):
  480. if model_name in str(cp.parent):
  481. config_path = cp
  482. break
  483. if config_path.exists():
  484. with open(config_path) as f:
  485. config = json.load(f)
  486. return {
  487. "model_type": config.get("model_type", "causal_lm"),
  488. "context_length": config.get("max_position_embeddings", config.get("max_sequence_length", 2048)),
  489. "hidden_size": config.get("hidden_size", 0),
  490. "num_layers": config.get("num_hidden_layers", 0),
  491. }
  492. return {"model_type": "causal_lm", "context_length": 2048}
  493. def _tokenize_dataset_ppo(self, dataset_path: str, max_seq_length: int, response_length: int):
  494. """Tokenize PPO 数据集:仅 prompt(模型在训练中自己生成回答)。"""
  495. from datasets import Dataset as HFDataset
  496. data = []
  497. with open(dataset_path, "r", encoding="utf-8") as f:
  498. for line in f:
  499. line = line.strip()
  500. if line:
  501. item = json.loads(line)
  502. if "prompt" not in item:
  503. item["prompt"] = item.get("question", item.get("query", item.get("text", item.get("input", ""))))
  504. if isinstance(item["prompt"], (list, dict)):
  505. item["prompt"] = json.dumps(item["prompt"], ensure_ascii=False)
  506. item["prompt"] = str(item["prompt"])
  507. data.append(item)
  508. hf_dataset = HFDataset.from_list(data)
  509. def tokenize_fn(batch):
  510. raw_prompts = batch.get("prompt", [])
  511. prompts = [str(v) if v is not None else "" for v in raw_prompts]
  512. # 仅 tokenize prompt,预留 response_length 空间给生成的回答
  513. tokenized = self._tokenizer(
  514. prompts,
  515. truncation=True,
  516. max_length=max_seq_length - response_length,
  517. padding=False,
  518. )
  519. return tokenized
  520. tokenized_dataset = hf_dataset.map(
  521. tokenize_fn,
  522. batched=True,
  523. remove_columns=hf_dataset.column_names,
  524. )
  525. return tokenized_dataset
  526. def _tokenize_dataset(self, dataset_path: str, max_seq_length: int):
  527. """Tokenize 处理后的 JSONL 数据集。"""
  528. from datasets import Dataset as HFDataset
  529. data = []
  530. with open(dataset_path, "r", encoding="utf-8") as f:
  531. for line in f:
  532. line = line.strip()
  533. if line:
  534. item = json.loads(line)
  535. # 兼容多种列名 → 统一映射为 prompt / completion
  536. if "prompt" not in item:
  537. item["prompt"] = item.get("question", item.get("query", item.get("text", item.get("input", ""))))
  538. if "completion" not in item:
  539. item["completion"] = item.get("answer", item.get("response", item.get("target", item.get("output", ""))))
  540. # 确保 prompt 和 completion 是字符串
  541. if isinstance(item["prompt"], (list, dict)):
  542. item["prompt"] = json.dumps(item["prompt"], ensure_ascii=False)
  543. item["prompt"] = str(item["prompt"])
  544. if isinstance(item["completion"], (list, dict)):
  545. item["completion"] = json.dumps(item["completion"], ensure_ascii=False)
  546. item["completion"] = str(item["completion"])
  547. data.append(item)
  548. hf_dataset = HFDataset.from_list(data)
  549. def tokenize_fn(batch):
  550. def _to_str(v):
  551. if isinstance(v, (list, dict)):
  552. return json.dumps(v, ensure_ascii=False)
  553. return str(v) if v is not None else ""
  554. raw_prompts = batch.get("prompt", [])
  555. raw_completions = batch.get("completion", [])
  556. prompts = [_to_str(v) for v in raw_prompts]
  557. completions = [_to_str(v) for v in raw_completions]
  558. if not prompts:
  559. return {"input_ids": [], "attention_mask": [], "labels": []}
  560. full_texts = [f"{p}\n{c}" for p, c in zip(prompts, completions)]
  561. tokenized = self._tokenizer(
  562. full_texts, truncation=True, max_length=max_seq_length, padding=False,
  563. )
  564. tokenized["labels"] = list(tokenized["input_ids"])
  565. return tokenized
  566. tokenized_dataset = hf_dataset.map(
  567. tokenize_fn,
  568. batched=True,
  569. remove_columns=["prompt", "completion"],
  570. )
  571. return tokenized_dataset
  572. def _load_dataset_dpo(self, dataset_path: str):
  573. """加载 DPO 数据集,保留 prompt/chosen/rejected 原始文本,由 DPOTrainer 内部 tokenize。"""
  574. from datasets import Dataset as HFDataset
  575. data = []
  576. with open(dataset_path, "r", encoding="utf-8") as f:
  577. for line in f:
  578. line = line.strip()
  579. if line:
  580. item = json.loads(line)
  581. prompt = item.get("prompt", item.get("instruction", item.get("input", "")))
  582. chosen = item.get("chosen", item.get("positive", ""))
  583. rejected = item.get("rejected", item.get("negative", ""))
  584. if prompt and chosen and rejected:
  585. data.append({
  586. "prompt": str(prompt),
  587. "chosen": str(chosen),
  588. "rejected": str(rejected),
  589. })
  590. if not data:
  591. raise ValueError(
  592. "DPO dataset is empty after parsing. "
  593. "Check that each record contains non-empty prompt/chosen/rejected fields."
  594. )
  595. return HFDataset.from_list(data)
  596. try:
  597. from transformers import TrainerCallback as _TrainerCallbackBase
  598. except ImportError:
  599. _TrainerCallbackBase = object # 151 主节点无 transformers,仅做占位
  600. class _ProgressCallback(_TrainerCallbackBase):
  601. """自定义训练进度回调,通过 WebSocket 发送进度。"""
  602. def __init__(self, job_id: str):
  603. super().__init__()
  604. self.job_id = job_id
  605. def on_log(self, args, state, control, logs=None, **kwargs):
  606. if logs and "loss" in logs:
  607. asyncio.create_task(
  608. send_progress(
  609. self.job_id,
  610. epoch=int(state.epoch or 0),
  611. step=state.global_step,
  612. total_steps=state.max_steps or 0,
  613. loss=logs["loss"],
  614. learning_rate=logs.get("learning_rate", 0),
  615. )
  616. )
  617. def on_epoch_end(self, args, state, control, **kwargs):
  618. asyncio.create_task(
  619. send_epoch_done(self.job_id, epoch=int(state.epoch or 0), eval_loss=None, eval_accuracy=None)
  620. )
  621. def on_train_end(self, args, state, control, **kwargs):
  622. asyncio.create_task(
  623. send_completed(
  624. self.job_id,
  625. total_time_seconds=getattr(state, "train_runtime", 0),
  626. adapter_path=str(settings.adapters_dir / self.job_id),
  627. )
  628. )
  629. # 全局单例
  630. text_engine = TextEngine()
  631. def _compute_heuristic_reward(prompts: list[str], responses: list[str]) -> list[float]:
  632. """启发式奖励函数:无需额外奖励模型即可用于 PPO 训练。
  633. 评分维度:长度合理性 + 非空 + 重复度惩罚。
  634. """
  635. rewards = []
  636. for _prompt, response in zip(prompts, responses):
  637. reward = 0.0
  638. resp_len = len(response.split())
  639. # 长度评分:20-200 词为佳
  640. if 20 <= resp_len <= 200:
  641. reward += 0.5
  642. elif resp_len < 5:
  643. reward -= 1.0
  644. elif resp_len > 500:
  645. reward -= 0.5
  646. # 非空奖励
  647. if response.strip():
  648. reward += 0.2
  649. # 重复度惩罚(trigram 重复率过高)
  650. words = response.split()
  651. if len(words) > 10:
  652. trigrams = set(tuple(words[i:i+3]) for i in range(len(words) - 2))
  653. if len(trigrams) < len(words) * 0.3:
  654. reward -= 0.5
  655. rewards.append(reward)
  656. return rewards