remote_train.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. """远程训练入口脚本 — 在算力节点上执行。
  2. 不依赖 app.config / app.core.logging,避免引入 pydantic-settings / sqlalchemy 等额外包。
  3. """
  4. import asyncio
  5. import json
  6. import os
  7. import re
  8. import sys
  9. import time
  10. import traceback
  11. from datetime import datetime, timezone
  12. from pathlib import Path
  13. # 禁用 FlashAttention
  14. os.environ["PYTORCH_NO_FLASH"] = "1"
  15. os.environ["FLASH_ATTENTION_ENABLED"] = "0"
  16. # 解决 PyTorch 显存碎片化问题(避免 reserved unallocated 占用大量显存)
  17. os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
  18. # 禁用 torch.compile,避免 fork 大量 inductor worker 进程
  19. os.environ["PT2_COMPILE"] = "0"
  20. os.environ["TORCHINDUCTOR_MAX_WORKERS"] = "1"
  21. # 限制训练只用 GPU 3(GPU 0/1 被 VLLM 占用,GPU 2 已占用)
  22. # CUDA_VISIBLE_DEVICES 将 3 映射为容器内的 cuda:0
  23. # device_map 中使用相对编号 0(即物理 GPU 3)
  24. os.environ["CUDA_VISIBLE_DEVICES"] = "3"
  25. # 启用 MPS 多进程服务,允许与 VLLM 共享 GPU
  26. os.environ["MACA_MPS_MODE"] = "1"
  27. # Triton 编译缓存 — 持久化编译产物,避免每次训练都重新编译
  28. os.environ["TRITON_CACHE_DIR"] = "/root/Fine-tuning/backend/data/.triton_cache"
  29. os.environ["TRITON_HOME"] = "/root/Fine-tuning/backend/data/.triton_cache"
  30. # 减少 Triton 编译时的冗余输出
  31. os.environ["MLIR_ENABLE_DUMP"] = "0"
  32. os.environ["TRITON_INTERPRET"] = "0"
  33. _progress_log_file = None
  34. # 直接从环境变量读取配置,避免引入 pydantic-settings
  35. _DATA_DIR = Path(os.environ.get("COMPUTE_NODE_REMOTE_DATA_DIR", "/root/Fine-tuning/backend/data"))
  36. _PROCESSED_DIR = _DATA_DIR / "processed"
  37. _ADAPTERS_DIR = _DATA_DIR / "adapters"
  38. _MODELS_DIR = _DATA_DIR / "models"
  39. def _remote_log(msg: str):
  40. """打印到 stderr(即远程训练日志 /tmp/train_{job_id}.log)。"""
  41. print(f"[remote_train] {msg}", file=sys.stderr)
  42. def _init_log_file(job_id: str):
  43. """初始化进度日志文件(通过 SSHFS 共享给主节点读取)。"""
  44. global _progress_log_file
  45. log_dir = _DATA_DIR / "logs"
  46. log_dir.mkdir(parents=True, exist_ok=True)
  47. _progress_log_file = log_dir / f"{job_id}.jsonl"
  48. _write_log(type="start", job_id=job_id)
  49. def _write_log(**kwargs):
  50. """追加一行 JSON 到共享日志文件。"""
  51. if _progress_log_file:
  52. entry = {"ts": datetime.now(timezone.utc).isoformat(), **kwargs}
  53. with open(_progress_log_file, "a", encoding="utf-8") as f:
  54. f.write(json.dumps(entry, ensure_ascii=False) + "\n")
  55. f.flush()
  56. class FileProgressCallback:
  57. """HuggingFace Trainer 回调 — 写进度到共享日志文件。
  58. 只实现关心的回调,其余通过 __getattr__ 自动忽略。
  59. """
  60. def __init__(self, job_id: str):
  61. self.job_id = job_id
  62. def on_step_end(self, args, state, control, **kwargs):
  63. """每步结束记录进度,便于观察训练是否在推进。"""
  64. _write_log(type="step", step=state.global_step,
  65. total_steps=state.max_steps or 0,
  66. epoch=round(state.epoch or 0, 2))
  67. if state.global_step % 5 == 0 or state.global_step <= 3:
  68. _remote_log(f"Step {state.global_step}/{state.max_steps} done (epoch {state.epoch:.2f})")
  69. def on_log(self, args, state, control, logs=None, **kwargs):
  70. if logs and "loss" in logs:
  71. _write_log(type="progress", epoch=int(state.epoch or 0),
  72. step=state.global_step, total_steps=state.max_steps or 0,
  73. loss=round(logs["loss"], 4),
  74. learning_rate=round(logs.get("learning_rate", 0), 8))
  75. def on_epoch_begin(self, args, state, control, **kwargs):
  76. _write_log(type="epoch_begin", epoch=int(state.epoch or 0))
  77. def on_epoch_end(self, args, state, control, metrics=None, **kwargs):
  78. _write_log(type="epoch_done", epoch=int(state.epoch or 0),
  79. eval_loss=metrics.get("eval_loss") if metrics and hasattr(metrics, "get") else None,
  80. eval_accuracy=metrics.get("eval_accuracy") if metrics and hasattr(metrics, "get") else None)
  81. def on_train_end(self, args, state, control, **kwargs):
  82. _write_log(type="completed", total_time_seconds=getattr(state, "train_runtime", 0),
  83. adapter_path=args.output_dir)
  84. def on_train_begin(self, args, state, control, **kwargs):
  85. _write_log(type="status", status="training")
  86. def on_save(self, args, state, control, **kwargs):
  87. _write_log(type="save", step=state.global_step)
  88. def on_evaluate(self, args, state, control, metrics=None, **kwargs):
  89. if metrics:
  90. _write_log(type="evaluate", epoch=int(state.epoch or 0),
  91. eval_loss=metrics.get("eval_loss"),
  92. eval_accuracy=metrics.get("eval_accuracy"))
  93. def __getattr__(self, name):
  94. """Trainer 期望其他回调方法存在,返回一个空函数自动忽略。"""
  95. return lambda *args, **kwargs: None
  96. async def run_training(job_id: str, model_id: str, model_type: str, dataset_path: str, config: dict):
  97. """执行单个训练任务(远程调用入口)。"""
  98. _init_log_file(job_id)
  99. _remote_log(f"=== Training job started: {job_id} ===")
  100. _remote_log(f"model_id={model_id}, model_type={model_type}")
  101. _remote_log(f"dataset_path={dataset_path}")
  102. _remote_log(f"config={json.dumps(config, ensure_ascii=False)[:200]}")
  103. try:
  104. # dataset_path 由主节点直接传入
  105. if not dataset_path or not Path(dataset_path).exists():
  106. raise FileNotFoundError(f"Dataset not found: {dataset_path}")
  107. _remote_log(f"Dataset file exists: {dataset_path}")
  108. _write_log(type="status", status="preprocessing")
  109. _remote_log("Step 1: Preprocessing dataset...")
  110. # 预处理
  111. processed_path = str(_PROCESSED_DIR / f"{job_id}_processed.jsonl")
  112. task_type = config.get("task_type", "sft")
  113. template = config.get("dataset_template", "auto")
  114. _remote_log(f" task_type={task_type}, template={template}")
  115. _remote_log(f" output_path={processed_path}")
  116. # 选择引擎
  117. _remote_log(f" Selecting engine for model_type={model_type}...")
  118. if model_type == "vision":
  119. from app.engines.vision_engine import vision_engine
  120. engine = vision_engine
  121. elif model_type == "multimodal":
  122. from app.engines.multimodal_engine import multimodal_engine
  123. engine = multimodal_engine
  124. else:
  125. from app.engines.text_engine import text_engine
  126. engine = text_engine
  127. _remote_log(f" Engine loaded: {engine.__class__.__name__}")
  128. peft_method = config.get("peft_method", "lora")
  129. _remote_log(f" PEFT method: {peft_method}")
  130. _remote_log(" Running preprocess_dataset...")
  131. await engine.preprocess_dataset(dataset_path, processed_path, task_type=task_type, template=template)
  132. _remote_log(f" Preprocessing done, output: {processed_path}")
  133. _write_log(type="status", status="loading_model")
  134. _remote_log(f"Step 2: Loading model: {model_id}...")
  135. # 加载模型
  136. quantization_mode = "4bit" if peft_method == "qlora" else None
  137. _remote_log(f" Quantization: {quantization_mode}")
  138. await engine.load_model(model_id, quantization=quantization_mode)
  139. _remote_log(" Model loaded successfully")
  140. # 构建 PEFT 配置
  141. _remote_log("Step 3: Building PEFT config...")
  142. peft_config = engine.get_peft_config(peft_method, config)
  143. _remote_log(" PEFT config built")
  144. # PPO 训练需要预下载奖励模型
  145. reward_type = config.get("reward_type", "heuristic")
  146. reward_model_path = config.get("reward_model_path")
  147. if reward_type == "model" and reward_model_path:
  148. _remote_log(f"Step 3.5: Pre-downloading reward model: {reward_model_path}...")
  149. reward_local = str(_MODELS_DIR / reward_model_path.replace("/", "_"))
  150. if not (Path(reward_local) / "config.json").exists():
  151. from huggingface_hub import snapshot_download
  152. snapshot_download(
  153. repo_id=reward_model_path,
  154. local_dir=reward_local,
  155. local_dir_use_symlinks=False,
  156. )
  157. _remote_log(f" Reward model downloaded to: {reward_local}")
  158. else:
  159. _remote_log(f" Reward model already exists: {reward_local}")
  160. config["reward_model_path"] = reward_local # 覆盖为本地路径
  161. _write_log(type="status", status="training")
  162. _remote_log("Step 4: Starting training...")
  163. _remote_log("NOTE: First step may take 2-5 minutes due to Triton kernel compilation (autotuning). This is normal.")
  164. _remote_log(f"Total steps: {config.get('epochs', 3)} epochs, batch_size={config.get('batch_size', 8)}")
  165. # 训练 — 传入文件日志回调替代 WebSocket 回调
  166. start_time = time.time()
  167. file_cb = FileProgressCallback(job_id)
  168. adapter_path = await engine.train(
  169. job_id=job_id,
  170. dataset_path=processed_path,
  171. peft_config=peft_config,
  172. training_args=config,
  173. callbacks=[file_cb],
  174. )
  175. elapsed = round(time.time() - start_time, 2)
  176. _write_log(type="completed", adapter_path=str(adapter_path), total_time=elapsed)
  177. _remote_log(f"Remote training completed: {job_id} -> {adapter_path} ({elapsed}s)")
  178. _remote_log(f"=== Training job finished: {job_id} ===")
  179. return adapter_path
  180. except Exception as e:
  181. tb = traceback.format_exc()
  182. _write_log(type="error", message=str(e), traceback=tb)
  183. _remote_log(f"ERROR: {e}")
  184. _remote_log(tb)
  185. _remote_log(f"=== Training job failed: {job_id} ===")
  186. raise
  187. def _patch_fla_shared_memory():
  188. """修复 fla 库 Triton kernel 共享内存溢出问题。
  189. Qwen3.5 等混合架构模型的 Gated Delta Rule 层使用 fla 库的 Triton kernel,
  190. 反向传播时 chunk kernel 的 block size 为 64,需要约 106KB 共享内存,
  191. 但沐曦/部分 NVIDIA GPU 硬件上限仅 64KB(65536 字节),导致 OutOfResources。
  192. 修复方式:精确替换 fla 库中控制 block size 的常量和 kernel 名称,
  193. 避免误改普通代码中的数字字面量。
  194. """
  195. try:
  196. import shutil
  197. # 定位 fla 包
  198. conda_path = '/opt/conda/lib/python3.10/site-packages/fla'
  199. if os.path.isdir(conda_path):
  200. fla_base = conda_path
  201. else:
  202. import site
  203. fla_base = None
  204. for sp in site.getsitepackages() + [site.getusersitepackages() if hasattr(site, 'getusersitepackages') else '']:
  205. candidate = os.path.join(sp, 'fla')
  206. if os.path.isdir(candidate):
  207. fla_base = candidate
  208. break
  209. if not fla_base:
  210. _remote_log("fla package not found, skipping shared memory patch")
  211. return
  212. _remote_log(f"fla package found at: {fla_base}")
  213. # 检查 fla 源码是否被旧版补丁损坏(语法错误)
  214. chunk_py = os.path.join(fla_base, 'ops', 'gated_delta_rule', 'chunk.py')
  215. source_corrupted = False
  216. if os.path.exists(chunk_py):
  217. try:
  218. with open(chunk_py, 'r') as f:
  219. compile(f.read(), chunk_py, 'exec')
  220. except SyntaxError as e:
  221. source_corrupted = True
  222. _remote_log(f"fla source corrupted (SyntaxError: {e}), will reinstall...")
  223. # 幂等检查
  224. marker_path = os.path.join(fla_base, '_PATCHED_SM32')
  225. if os.path.exists(marker_path) and not source_corrupted:
  226. # 检查标记版本:v1 是旧版补丁(用激进正则,已污染源码),需要重装后重新打补丁
  227. with open(marker_path) as mf:
  228. marker_content = mf.read()
  229. if 'v2' in marker_content:
  230. _remote_log("fla shared memory patch v2 already applied, skipping")
  231. to_remove = [k for k in sys.modules if k.startswith('fla')]
  232. for k in to_remove:
  233. del sys.modules[k]
  234. return
  235. else:
  236. source_corrupted = True
  237. _remote_log("Old patch v1 detected, will reinstall fla...")
  238. if source_corrupted:
  239. _remote_log("WARNING: fla source is corrupted (SyntaxError). "
  240. "Please rebuild the container to restore clean source.")
  241. return
  242. patched_files = []
  243. for root, dirs, files in os.walk(fla_base):
  244. for fname in files:
  245. if not fname.endswith('.py'):
  246. continue
  247. fpath = os.path.join(root, fname)
  248. try:
  249. with open(fpath, 'r') as f:
  250. original = f.read()
  251. c = original
  252. changes = []
  253. # 0. 修复 fla/utils.py 中的 maca 设备映射(沐曦 GPU 兼容)
  254. if fname == 'utils.py' and "!= 'hip'" in c:
  255. # 把 maca 也映射到 cuda
  256. c = c.replace(
  257. "device = get_available_device() if get_available_device() != 'hip' else 'cuda'",
  258. "device = get_available_device() if get_available_device() not in ('hip', 'maca') else 'cuda'"
  259. )
  260. changes.append('maca->cuda mapping')
  261. # 1. kernel 函数名后缀: blockdim64 → blockdim32
  262. if 'blockdim64' in c:
  263. c = c.replace('blockdim64', 'blockdim32')
  264. changes.append('blockdim64->blockdim32')
  265. # 2. 精确匹配 fla 中常见的 block size 变量赋值
  266. # BT = 64, BK = 64, BV = 64, chunk_size = 64, BLOCK_SIZE = 64 等
  267. # 用 \b 匹配完整变量名,避免误改其他代码
  268. for var in ['BT', 'BK', 'BV', 'chunk_size', 'BLOCK_SIZE',
  269. 'BLOCK_M', 'BLOCK_N', 'BLOCK_K', 'BLOCK_V',
  270. 'block_size', 'block_m', 'block_n', 'block_k', 'block_v']:
  271. pattern = rf'\b{var}\s*=\s*64\b'
  272. replacement = f'{var} = 32'
  273. new_c = re.sub(pattern, replacement, c)
  274. if new_c != c:
  275. changes.append(f'{var}=64->32')
  276. c = new_c
  277. # 3. Triton autotune 装饰器中的 configs 参数值
  278. # 例如: configs=[..., 64, ...] 或 tl.constexpr = 64
  279. # 只替换 tl.constexpr = 64 的情况
  280. pattern = r'tl\.constexpr\s*=\s*64\b'
  281. new_c = re.sub(pattern, 'tl.constexpr = 32', c)
  282. if new_c != c:
  283. changes.append('tl.constexpr 64->32')
  284. c = new_c
  285. # 4. num_stages 降低(减少流水线阶段,进一步降低共享内存)
  286. pattern = r'num_stages\s*=\s*([3-9]|[1-9]\d+)'
  287. new_c = re.sub(pattern, 'num_stages=1', c)
  288. if new_c != c:
  289. changes.append('num_stages->1')
  290. c = new_c
  291. if c != original:
  292. with open(fpath, 'w') as f:
  293. f.write(c)
  294. patched_files.append(f"{os.path.relpath(fpath, fla_base)}({', '.join(changes)})")
  295. except Exception as e:
  296. _remote_log(f" Warning: failed to patch {fpath}: {e}")
  297. continue
  298. # 清理 __pycache__
  299. cache_count = 0
  300. for root, dirs, files in os.walk(fla_base):
  301. if '__pycache__' in dirs:
  302. shutil.rmtree(os.path.join(root, '__pycache__'), ignore_errors=True)
  303. cache_count += 1
  304. # 清除已缓存的 fla 模块
  305. to_remove = [k for k in sys.modules if k.startswith('fla')]
  306. for k in to_remove:
  307. del sys.modules[k]
  308. # 写入标记文件(幂等),包含版本号 v2
  309. with open(marker_path, 'w') as f:
  310. f.write(f"v2 patched at {datetime.now(timezone.utc).isoformat()}\n")
  311. _remote_log(f"fla shared memory patch done: {len(patched_files)} files, "
  312. f"{cache_count} caches cleared, {len(to_remove)} modules evicted")
  313. for pf in patched_files:
  314. _remote_log(f" patched: {pf}")
  315. except Exception as e:
  316. _remote_log(f"Warning: fla shared memory patch failed: {e}")
  317. import traceback as tb
  318. _remote_log(tb.format_exc())
  319. def main():
  320. """命令行入口:python -m app.engines.remote_train <job_id> <model_id> <model_type> <dataset_path> <config_file>"""
  321. # 在导入任何 fla 模块之前,修补 Triton kernel 共享内存问题
  322. _patch_fla_shared_memory()
  323. if len(sys.argv) < 6:
  324. print("Usage: python -m app.engines.remote_train <job_id> <model_id> <model_type> <dataset_path> <config_file>")
  325. sys.exit(1)
  326. job_id = sys.argv[1]
  327. model_id = sys.argv[2]
  328. model_type = sys.argv[3]
  329. dataset_id = sys.argv[4]
  330. config_path = sys.argv[5]
  331. with open(config_path, encoding="utf-8") as f:
  332. config = json.load(f)
  333. asyncio.run(run_training(job_id, model_id, model_type, dataset_id, config))
  334. if __name__ == "__main__":
  335. main()