trainer_utils.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. """
  2. 训练工具函数集合
  3. """
  4. import os
  5. import sys
  6. __package__ = "trainer"
  7. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  8. import ast
  9. import operator
  10. import random
  11. import math
  12. import numpy as np
  13. import torch
  14. import torch.distributed as dist
  15. from torch.nn.parallel import DistributedDataParallel
  16. from torch.utils.data import Sampler
  17. from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification
  18. from model.model_minimind import MiniMindForCausalLM
  19. def get_model_params(model, config):
  20. total = sum(p.numel() for p in model.parameters()) / 1e6
  21. n_routed = getattr(config, 'n_routed_experts', getattr(config, 'num_experts', 0))
  22. n_active = getattr(config, 'num_experts_per_tok', 0)
  23. n_shared = getattr(config, 'n_shared_experts', 0)
  24. expert = sum(p.numel() for n, p in model.named_parameters() if 'mlp.experts.0.' in n) / 1e6
  25. shared_expert = sum(p.numel() for n, p in model.named_parameters() if 'mlp.shared_experts.0.' in n) / 1e6
  26. base = total - (expert * n_routed) - (shared_expert * n_shared)
  27. active = base + (expert * n_active) + (shared_expert * n_shared)
  28. if active < total: Logger(f'Model Params: {total:.2f}M-A{active:.2f}M')
  29. else: Logger(f'Model Params: {total:.2f}M')
  30. def is_main_process():
  31. return not dist.is_initialized() or dist.get_rank() == 0
  32. def Logger(content):
  33. if is_main_process():
  34. print(content)
  35. def get_lr(current_step, total_steps, lr):
  36. return lr*(0.1 + 0.45*(1 + math.cos(math.pi * current_step / total_steps)))
  37. def init_distributed_mode():
  38. if int(os.environ.get("RANK", -1)) == -1:
  39. return 0 # 非DDP模式
  40. dist.init_process_group(backend="nccl")
  41. local_rank = int(os.environ["LOCAL_RANK"])
  42. torch.cuda.set_device(local_rank)
  43. return local_rank
  44. def setup_seed(seed: int):
  45. random.seed(seed)
  46. np.random.seed(seed)
  47. torch.manual_seed(seed)
  48. torch.cuda.manual_seed(seed)
  49. torch.cuda.manual_seed_all(seed)
  50. torch.backends.cudnn.deterministic = True
  51. torch.backends.cudnn.benchmark = False
  52. def lm_checkpoint(lm_config, weight='full_sft', model=None, optimizer=None, epoch=0, step=0, wandb=None, save_dir='../checkpoints', **kwargs):
  53. os.makedirs(save_dir, exist_ok=True)
  54. moe_path = '_moe' if lm_config.use_moe else ''
  55. ckp_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}.pth'
  56. resume_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}_resume.pth'
  57. if model is not None:
  58. raw_model = model.module if isinstance(model, DistributedDataParallel) else model
  59. raw_model = getattr(raw_model, '_orig_mod', raw_model)
  60. state_dict = raw_model.state_dict()
  61. state_dict = {k: v.half().cpu() for k, v in state_dict.items()}
  62. ckp_tmp = ckp_path + '.tmp'
  63. torch.save(state_dict, ckp_tmp)
  64. os.replace(ckp_tmp, ckp_path)
  65. wandb_id = None
  66. if wandb:
  67. if hasattr(wandb, 'get_run'):
  68. run = wandb.get_run()
  69. wandb_id = getattr(run, 'id', None) if run else None
  70. else:
  71. wandb_id = getattr(wandb, 'id', None)
  72. resume_data = {
  73. 'model': state_dict,
  74. 'optimizer': optimizer.state_dict(),
  75. 'epoch': epoch,
  76. 'step': step,
  77. 'world_size': dist.get_world_size() if dist.is_initialized() else 1,
  78. 'wandb_id': wandb_id
  79. }
  80. for key, value in kwargs.items():
  81. if value is not None:
  82. if hasattr(value, 'state_dict'):
  83. raw_value = value.module if isinstance(value, DistributedDataParallel) else value
  84. raw_value = getattr(raw_value, '_orig_mod', raw_value)
  85. resume_data[key] = raw_value.state_dict()
  86. else:
  87. resume_data[key] = value
  88. resume_tmp = resume_path + '.tmp'
  89. torch.save(resume_data, resume_tmp)
  90. os.replace(resume_tmp, resume_path)
  91. del state_dict, resume_data
  92. torch.cuda.empty_cache()
  93. else: # 加载模式
  94. if os.path.exists(resume_path):
  95. ckp_data = torch.load(resume_path, map_location='cpu')
  96. saved_ws = ckp_data.get('world_size', 1)
  97. current_ws = dist.get_world_size() if dist.is_initialized() else 1
  98. if saved_ws != current_ws:
  99. ckp_data['step'] = ckp_data['step'] * saved_ws // current_ws
  100. Logger(f'GPU数量变化({saved_ws}→{current_ws}),step已自动转换为{ckp_data["step"]}')
  101. return ckp_data
  102. return None
  103. def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', save_dir='../out', device='cuda'):
  104. tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
  105. model = MiniMindForCausalLM(lm_config)
  106. if from_weight!= 'none':
  107. moe_suffix = '_moe' if lm_config.use_moe else ''
  108. weight_path = f'{save_dir}/{from_weight}_{lm_config.hidden_size}{moe_suffix}.pth'
  109. weights = torch.load(weight_path, map_location=device)
  110. model.load_state_dict(weights, strict=False)
  111. get_model_params(model, lm_config)
  112. Logger(f'Trainable Params: {sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6:.3f}M')
  113. return model.to(device), tokenizer
  114. class SkipBatchSampler(Sampler):
  115. def __init__(self, sampler, batch_size, skip_batches=0):
  116. self.sampler = sampler
  117. self.batch_size = batch_size
  118. self.skip_batches = skip_batches
  119. def __iter__(self):
  120. batch = []
  121. skipped = 0
  122. for idx in self.sampler:
  123. batch.append(idx)
  124. if len(batch) == self.batch_size:
  125. if skipped < self.skip_batches:
  126. skipped += 1
  127. batch = []
  128. continue
  129. yield batch
  130. batch = []
  131. if len(batch) > 0 and skipped >= self.skip_batches:
  132. yield batch
  133. def __len__(self):
  134. total_batches = (len(self.sampler) + self.batch_size - 1) // self.batch_size
  135. return max(0, total_batches - self.skip_batches)
  136. class LMForRewardModel:
  137. def __init__(self, model_path, device="cuda", dtype=torch.float16):
  138. self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
  139. self.model = AutoModel.from_pretrained(model_path, torch_dtype=dtype, trust_remote_code=True)
  140. self.model = self.model.to(device).eval()
  141. self.device = device
  142. @torch.no_grad()
  143. def get_score(self, messages, response):
  144. history_text = "\n".join([f"{m['role']}: {m['content']}" for m in messages[:-1]])
  145. last_query = messages[-1]['content'] if messages else ""
  146. message_context = f"{history_text}\n以上是对话历史。我的新问题是:\n{last_query}" if history_text else last_query
  147. eval_messages = [
  148. {"role": "user", "content": message_context},
  149. {"role": "assistant", "content": response}
  150. ]
  151. score = self.model.get_score(self.tokenizer, eval_messages)
  152. return max(min(score, 3.0), -3.0)
  153. # ===== 数学表达式安全求值(替代 eval,避免执行模型生成的任意代码) =====
  154. _MATH_FUNCS = {name: getattr(math, name) for name in (
  155. 'sqrt', 'pow', 'exp', 'log', 'log2', 'log10', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'atan2',
  156. 'sinh', 'cosh', 'tanh', 'floor', 'ceil', 'trunc', 'fabs', 'fmod', 'hypot', 'gcd', 'degrees', 'radians'
  157. )}
  158. _MATH_CONSTS = {'pi': math.pi, 'e': math.e, 'tau': math.tau}
  159. _BIN_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv,
  160. ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod, ast.Pow: operator.pow}
  161. _UNARY_OPS = {ast.UAdd: operator.pos, ast.USub: operator.neg}
  162. _MAX_EXPR_LEN, _MAX_EXP, _MAX_DIGITS = 512, 1e4, 100 # 表达式长度 / 指数 / 结果位数上限
  163. def _check_pow(base, exp): # 防止 9**9**9 这类表达式把进程算死
  164. if abs(exp) > _MAX_EXP or (abs(base) > 1 and abs(exp) * math.log10(abs(base)) > _MAX_DIGITS):
  165. raise ValueError('幂运算结果过大')
  166. def _resolve_name(node): # 同时兼容 sqrt(4) 与 math.sqrt(4) 两种写法
  167. if isinstance(node, ast.Name): return node.id
  168. if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id == 'math': return node.attr
  169. return None
  170. def _eval_ast(node):
  171. if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool):
  172. return node.value
  173. if isinstance(node, (ast.Name, ast.Attribute)) and _resolve_name(node) in _MATH_CONSTS:
  174. return _MATH_CONSTS[_resolve_name(node)]
  175. if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY_OPS:
  176. return _UNARY_OPS[type(node.op)](_eval_ast(node.operand))
  177. if isinstance(node, ast.BinOp) and type(node.op) in _BIN_OPS:
  178. left, right = _eval_ast(node.left), _eval_ast(node.right)
  179. if isinstance(node.op, ast.Pow): _check_pow(left, right)
  180. return _BIN_OPS[type(node.op)](left, right)
  181. if isinstance(node, ast.Call) and _resolve_name(node.func) in _MATH_FUNCS and not node.keywords:
  182. name, args = _resolve_name(node.func), [_eval_ast(arg) for arg in node.args]
  183. if name == 'pow' and len(args) == 2: _check_pow(*args)
  184. return _MATH_FUNCS[name](*args)
  185. raise ValueError(f'不支持的表达式语法: {type(node).__name__}')
  186. def safe_math_eval(expression):
  187. """对模型生成的数学表达式求值:只放行算术运算与 math 白名单函数,不执行任意代码。"""
  188. expr = str(expression).replace('^', '**').replace('×', '*').replace('÷', '/').replace('−', '-')
  189. expr = expr.replace('²', '**2').replace('³', '**3').replace('(', '(').replace(')', ')').strip()
  190. if not expr or len(expr) > _MAX_EXPR_LEN: raise ValueError('表达式为空或过长')
  191. return _eval_ast(ast.parse(expr, mode='eval').body)