trainer_utils.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 re
  12. import math
  13. import numpy as np
  14. import torch
  15. import torch.distributed as dist
  16. from torch.nn.parallel import DistributedDataParallel
  17. from torch.utils.data import Sampler
  18. from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification
  19. from model.model_minimind import MiniMindForCausalLM
  20. # ======== 模型参数量 ========
  21. def get_model_params(model, config):
  22. total = sum(p.numel() for p in model.parameters()) / 1e6
  23. n_routed = getattr(config, 'n_routed_experts', getattr(config, 'num_experts', 0))
  24. n_active = getattr(config, 'num_experts_per_tok', 0)
  25. n_shared = getattr(config, 'n_shared_experts', 0)
  26. expert = sum(p.numel() for n, p in model.named_parameters() if 'mlp.experts.0.' in n) / 1e6
  27. shared_expert = sum(p.numel() for n, p in model.named_parameters() if 'mlp.shared_experts.0.' in n) / 1e6
  28. base = total - (expert * n_routed) - (shared_expert * n_shared)
  29. active = base + (expert * n_active) + (shared_expert * n_shared)
  30. if active < total: Logger(f'Model Params: {total:.2f}M-A{active:.2f}M')
  31. else: Logger(f'Model Params: {total:.2f}M')
  32. # ======== 主进程判断 ========
  33. def is_main_process():
  34. return not dist.is_initialized() or dist.get_rank() == 0
  35. # ======== 日志 ========
  36. def Logger(content):
  37. if is_main_process():
  38. print(content)
  39. # ======== 学习率 ========
  40. def get_lr(current_step, total_steps, lr, warmup_ratio=0.0):
  41. warmup = max(1, int(warmup_ratio * total_steps)) if warmup_ratio > 0 else 0
  42. if current_step < warmup:
  43. return lr * (current_step + 1) / warmup
  44. angle = math.pi * (current_step - warmup) / max(1, total_steps - warmup)
  45. return lr * (0.1 + 0.45 * (1 + math.cos(angle)))
  46. # ======== 分布式初始化 ========
  47. def init_distributed_mode():
  48. if int(os.environ.get("RANK", -1)) == -1:
  49. return 0 # 非DDP模式
  50. dist.init_process_group(backend="nccl")
  51. local_rank = int(os.environ["LOCAL_RANK"])
  52. torch.cuda.set_device(local_rank)
  53. return local_rank
  54. # ======== 随机种子 ========
  55. def setup_seed(seed: int):
  56. random.seed(seed)
  57. np.random.seed(seed)
  58. torch.manual_seed(seed)
  59. torch.cuda.manual_seed(seed)
  60. torch.cuda.manual_seed_all(seed)
  61. torch.backends.cudnn.deterministic = True
  62. torch.backends.cudnn.benchmark = False
  63. # ======== 断点保存与续训 ========
  64. def lm_checkpoint(lm_config, weight='full_sft', model=None, optimizer=None, epoch=0, step=0, wandb=None, save_dir='../checkpoints', **kwargs):
  65. os.makedirs(save_dir, exist_ok=True)
  66. moe_path = '_moe' if lm_config.use_moe else ''
  67. ckp_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}.pth'
  68. resume_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}_resume.pth'
  69. if model is not None:
  70. raw_model = model.module if isinstance(model, DistributedDataParallel) else model
  71. raw_model = getattr(raw_model, '_orig_mod', raw_model)
  72. state_dict = {k: v.cpu() for k, v in raw_model.state_dict().items()}
  73. ckp_tmp = ckp_path + '.tmp'
  74. torch.save({k: v.half() for k, v in state_dict.items()}, ckp_tmp)
  75. os.replace(ckp_tmp, ckp_path)
  76. wandb_id = None
  77. if wandb:
  78. if hasattr(wandb, 'get_run'):
  79. run = wandb.get_run()
  80. wandb_id = getattr(run, 'id', None) if run else None
  81. else:
  82. wandb_id = getattr(wandb, 'id', None)
  83. resume_data = {
  84. 'model': state_dict,
  85. 'optimizer': optimizer.state_dict(),
  86. 'epoch': epoch,
  87. 'step': step,
  88. 'world_size': dist.get_world_size() if dist.is_initialized() else 1,
  89. 'wandb_id': wandb_id
  90. }
  91. for key, value in kwargs.items():
  92. if value is not None:
  93. if hasattr(value, 'state_dict'):
  94. raw_value = value.module if isinstance(value, DistributedDataParallel) else value
  95. raw_value = getattr(raw_value, '_orig_mod', raw_value)
  96. resume_data[key] = raw_value.state_dict()
  97. else:
  98. resume_data[key] = value
  99. resume_tmp = resume_path + '.tmp'
  100. torch.save(resume_data, resume_tmp)
  101. os.replace(resume_tmp, resume_path)
  102. del state_dict, resume_data
  103. torch.cuda.empty_cache()
  104. else: # 加载模式
  105. if os.path.exists(resume_path):
  106. ckp_data = torch.load(resume_path, map_location='cpu')
  107. saved_ws = ckp_data.get('world_size', 1)
  108. current_ws = dist.get_world_size() if dist.is_initialized() else 1
  109. if saved_ws != current_ws:
  110. ckp_data['step'] = ckp_data['step'] * saved_ws // current_ws
  111. Logger(f'GPU数量变化({saved_ws}→{current_ws}),step已自动转换为{ckp_data["step"]}')
  112. return ckp_data
  113. return None
  114. # ======== 模型初始化 ========
  115. def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', save_dir='../out', device='cuda'):
  116. tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
  117. model = MiniMindForCausalLM(lm_config)
  118. if from_weight!= 'none':
  119. moe_suffix = '_moe' if lm_config.use_moe else ''
  120. weight_path = f'{save_dir}/{from_weight}_{lm_config.hidden_size}{moe_suffix}.pth'
  121. weights = torch.load(weight_path, map_location=device)
  122. model.load_state_dict(weights, strict=False)
  123. get_model_params(model, lm_config)
  124. Logger(f'Trainable Params: {sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6:.3f}M')
  125. return model.to(device), tokenizer
  126. # ======== 跳过批次采样器 ========
  127. class SkipBatchSampler(Sampler):
  128. def __init__(self, sampler, batch_size, skip_batches=0):
  129. self.sampler = sampler
  130. self.batch_size = batch_size
  131. self.skip_batches = skip_batches
  132. def __iter__(self):
  133. batch = []
  134. skipped = 0
  135. for idx in self.sampler:
  136. batch.append(idx)
  137. if len(batch) == self.batch_size:
  138. if skipped < self.skip_batches:
  139. skipped += 1
  140. batch = []
  141. continue
  142. yield batch
  143. batch = []
  144. if len(batch) > 0 and skipped >= self.skip_batches:
  145. yield batch
  146. def __len__(self):
  147. total_batches = (len(self.sampler) + self.batch_size - 1) // self.batch_size
  148. return max(0, total_batches - self.skip_batches)
  149. # ======== 奖励模型 ========
  150. class LMForRewardModel:
  151. def __init__(self, model_path, device="cuda", dtype=torch.float16):
  152. self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
  153. self.model = AutoModel.from_pretrained(model_path, torch_dtype=dtype, trust_remote_code=True)
  154. self.model = self.model.to(device).eval()
  155. self.device = device
  156. @torch.no_grad()
  157. def get_score(self, messages, response):
  158. history_text = "\n".join([f"{m['role']}: {m['content']}" for m in messages[:-1]])
  159. last_query = messages[-1]['content'] if messages else ""
  160. message_context = f"{history_text}\n以上是对话历史。我的新问题是:\n{last_query}" if history_text else last_query
  161. eval_messages = [
  162. {"role": "user", "content": message_context},
  163. {"role": "assistant", "content": response}
  164. ]
  165. score = self.model.get_score(self.tokenizer, eval_messages)
  166. return max(min(score, 3.0), -3.0)
  167. # ======== 数学表达式安全求值 ========
  168. def safe_math_eval(expression):
  169. """对模型生成的数学表达式求值:支持 + - * / // % **、math 白名单函数与 pi/e/tau 常量。"""
  170. def pow_guard(base, exp): # 幂运算统一走这里,拦截 9**9**9 / 10**99999 这类把进程算死的输入
  171. if abs(exp) > 1e4 or (abs(base) > 1 and abs(exp) * math.log10(abs(base)) > 100): raise ValueError('幂运算结果过大')
  172. return base ** exp
  173. def resolve(node): # 同时兼容 sqrt(4) 与 math.sqrt(4) 两种写法
  174. if isinstance(node, ast.Name): return node.id
  175. if isinstance(node, ast.Attribute) and getattr(node.value, 'id', '') == 'math': return node.attr
  176. def walk(node):
  177. if isinstance(node, ast.Constant) and type(node.value) in (int, float): return node.value
  178. name = resolve(node)
  179. if name in consts: return consts[name]
  180. if isinstance(node, ast.UnaryOp): return unary_ops[type(node.op)](walk(node.operand))
  181. if isinstance(node, ast.BinOp): return bin_ops[type(node.op)](walk(node.left), walk(node.right))
  182. if isinstance(node, ast.Call) and not node.keywords: return funcs[resolve(node.func)](*map(walk, node.args))
  183. raise ValueError(f'不支持的表达式语法: {type(node).__name__}')
  184. consts = {'pi': math.pi, 'e': math.e, 'tau': math.tau}
  185. funcs = {'pow': pow_guard, **{n: getattr(math, n) for n in 'sqrt exp log log2 log10 sin cos tan asin acos atan atan2 sinh cosh tanh floor ceil trunc fabs fmod hypot gcd degrees radians'.split()}}
  186. bin_ops = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod, ast.Pow: pow_guard}
  187. unary_ops = {ast.UAdd: operator.pos, ast.USub: operator.neg}
  188. chars = str.maketrans({'^': '**', '×': '*', '÷': '/', '−': '-', '²': '**2', '³': '**3', '(': '(', ')': ')'})
  189. expr = str(expression).translate(chars).strip()
  190. if not expr or len(expr) > 512: raise ValueError('表达式为空或过长')
  191. try:
  192. return walk(ast.parse(expr, mode='eval').body)
  193. except (KeyError, SyntaxError, TypeError):
  194. raise ValueError('不支持的表达式语法') from None
  195. # ======== 重复惩罚 ========
  196. def rep_penalty(text, n=3, cap=0.5):
  197. cjk = ("\u3007\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af"
  198. "\U00020000-\U0002ee5f\U0002f800-\U0002fa1f\U00030000-\U0003347f")
  199. toks = re.findall(rf"[{cjk}]|[^\W{cjk}]+|[^\w\s]", text.lower())
  200. grams = [tuple(toks[i:i + n]) for i in range(len(toks) - n + 1)]
  201. return min(cap, (len(grams) - len(set(grams))) * cap * 2 / len(grams)) if grams else 0.0