trainer_utils.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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, warmup_frac=0.0):
  36. # warmup_frac=0(默认)时与原实现逐值相同。需要 warmup 的场景可以传入一个比例,
  37. # 前 warmup_frac*total_steps 步把 lr 线性升到满值,其后在剩余步数上走原来的余弦。
  38. if warmup_frac > 0:
  39. warmup_steps = max(1, int(warmup_frac * total_steps))
  40. if current_step < warmup_steps:
  41. return lr * (current_step + 1) / warmup_steps
  42. current_step -= warmup_steps
  43. total_steps = max(1, total_steps - warmup_steps)
  44. return lr*(0.1 + 0.45*(1 + math.cos(math.pi * current_step / total_steps)))
  45. def init_distributed_mode():
  46. if int(os.environ.get("RANK", -1)) == -1:
  47. return 0 # 非DDP模式
  48. dist.init_process_group(backend="nccl")
  49. local_rank = int(os.environ["LOCAL_RANK"])
  50. torch.cuda.set_device(local_rank)
  51. return local_rank
  52. def setup_seed(seed: int):
  53. random.seed(seed)
  54. np.random.seed(seed)
  55. torch.manual_seed(seed)
  56. torch.cuda.manual_seed(seed)
  57. torch.cuda.manual_seed_all(seed)
  58. torch.backends.cudnn.deterministic = True
  59. torch.backends.cudnn.benchmark = False
  60. def lm_checkpoint(lm_config, weight='full_sft', model=None, optimizer=None, epoch=0, step=0, wandb=None, save_dir='../checkpoints', **kwargs):
  61. os.makedirs(save_dir, exist_ok=True)
  62. moe_path = '_moe' if lm_config.use_moe else ''
  63. ckp_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}.pth'
  64. resume_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}_resume.pth'
  65. if model is not None:
  66. raw_model = model.module if isinstance(model, DistributedDataParallel) else model
  67. raw_model = getattr(raw_model, '_orig_mod', raw_model)
  68. state_dict = raw_model.state_dict()
  69. state_dict = {k: v.half().cpu() for k, v in state_dict.items()}
  70. ckp_tmp = ckp_path + '.tmp'
  71. torch.save(state_dict, ckp_tmp)
  72. os.replace(ckp_tmp, ckp_path)
  73. wandb_id = None
  74. if wandb:
  75. if hasattr(wandb, 'get_run'):
  76. run = wandb.get_run()
  77. wandb_id = getattr(run, 'id', None) if run else None
  78. else:
  79. wandb_id = getattr(wandb, 'id', None)
  80. resume_data = {
  81. 'model': state_dict,
  82. 'optimizer': optimizer.state_dict(),
  83. 'epoch': epoch,
  84. 'step': step,
  85. 'world_size': dist.get_world_size() if dist.is_initialized() else 1,
  86. 'wandb_id': wandb_id
  87. }
  88. for key, value in kwargs.items():
  89. if value is not None:
  90. if hasattr(value, 'state_dict'):
  91. raw_value = value.module if isinstance(value, DistributedDataParallel) else value
  92. raw_value = getattr(raw_value, '_orig_mod', raw_value)
  93. resume_data[key] = raw_value.state_dict()
  94. else:
  95. resume_data[key] = value
  96. resume_tmp = resume_path + '.tmp'
  97. torch.save(resume_data, resume_tmp)
  98. os.replace(resume_tmp, resume_path)
  99. del state_dict, resume_data
  100. torch.cuda.empty_cache()
  101. else: # 加载模式
  102. if os.path.exists(resume_path):
  103. ckp_data = torch.load(resume_path, map_location='cpu')
  104. saved_ws = ckp_data.get('world_size', 1)
  105. current_ws = dist.get_world_size() if dist.is_initialized() else 1
  106. if saved_ws != current_ws:
  107. ckp_data['step'] = ckp_data['step'] * saved_ws // current_ws
  108. Logger(f'GPU数量变化({saved_ws}→{current_ws}),step已自动转换为{ckp_data["step"]}')
  109. return ckp_data
  110. return None
  111. def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', save_dir='../out', device='cuda'):
  112. tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
  113. model = MiniMindForCausalLM(lm_config)
  114. if from_weight!= 'none':
  115. moe_suffix = '_moe' if lm_config.use_moe else ''
  116. weight_path = f'{save_dir}/{from_weight}_{lm_config.hidden_size}{moe_suffix}.pth'
  117. weights = torch.load(weight_path, map_location=device)
  118. model.load_state_dict(weights, strict=False)
  119. get_model_params(model, lm_config)
  120. Logger(f'Trainable Params: {sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6:.3f}M')
  121. return model.to(device), tokenizer
  122. class SkipBatchSampler(Sampler):
  123. def __init__(self, sampler, batch_size, skip_batches=0):
  124. self.sampler = sampler
  125. self.batch_size = batch_size
  126. self.skip_batches = skip_batches
  127. def __iter__(self):
  128. batch = []
  129. skipped = 0
  130. for idx in self.sampler:
  131. batch.append(idx)
  132. if len(batch) == self.batch_size:
  133. if skipped < self.skip_batches:
  134. skipped += 1
  135. batch = []
  136. continue
  137. yield batch
  138. batch = []
  139. if len(batch) > 0 and skipped >= self.skip_batches:
  140. yield batch
  141. def __len__(self):
  142. total_batches = (len(self.sampler) + self.batch_size - 1) // self.batch_size
  143. return max(0, total_batches - self.skip_batches)
  144. class LMForRewardModel:
  145. def __init__(self, model_path, device="cuda", dtype=torch.float16):
  146. self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
  147. self.model = AutoModel.from_pretrained(model_path, torch_dtype=dtype, trust_remote_code=True)
  148. self.model = self.model.to(device).eval()
  149. self.device = device
  150. @torch.no_grad()
  151. def get_score(self, messages, response):
  152. history_text = "\n".join([f"{m['role']}: {m['content']}" for m in messages[:-1]])
  153. last_query = messages[-1]['content'] if messages else ""
  154. message_context = f"{history_text}\n以上是对话历史。我的新问题是:\n{last_query}" if history_text else last_query
  155. eval_messages = [
  156. {"role": "user", "content": message_context},
  157. {"role": "assistant", "content": response}
  158. ]
  159. score = self.model.get_score(self.tokenizer, eval_messages)
  160. return max(min(score, 3.0), -3.0)
  161. # ===== 数学表达式安全求值:替代 eval,只放行算术运算与 math 白名单(长度上限 512) =====
  162. def safe_math_eval(expression):
  163. """对模型生成的数学表达式求值:支持 + - * / // % **、math 白名单函数与 pi/e/tau 常量。"""
  164. def pow_guard(base, exp): # 幂运算统一走这里,拦截 9**9**9 / 10**99999 这类把进程算死的输入
  165. if abs(exp) > 1e4 or (abs(base) > 1 and abs(exp) * math.log10(abs(base)) > 100): raise ValueError('幂运算结果过大')
  166. return base ** exp
  167. def resolve(node): # 同时兼容 sqrt(4) 与 math.sqrt(4) 两种写法
  168. if isinstance(node, ast.Name): return node.id
  169. if isinstance(node, ast.Attribute) and getattr(node.value, 'id', '') == 'math': return node.attr
  170. def walk(node):
  171. if isinstance(node, ast.Constant) and type(node.value) in (int, float): return node.value
  172. name = resolve(node)
  173. if name in consts: return consts[name]
  174. if isinstance(node, ast.UnaryOp): return unary_ops[type(node.op)](walk(node.operand))
  175. if isinstance(node, ast.BinOp): return bin_ops[type(node.op)](walk(node.left), walk(node.right))
  176. if isinstance(node, ast.Call) and not node.keywords: return funcs[resolve(node.func)](*map(walk, node.args))
  177. raise ValueError(f'不支持的表达式语法: {type(node).__name__}')
  178. consts = {'pi': math.pi, 'e': math.e, 'tau': math.tau}
  179. 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()}}
  180. 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}
  181. unary_ops = {ast.UAdd: operator.pos, ast.USub: operator.neg}
  182. chars = str.maketrans({'^': '**', '×': '*', '÷': '/', '−': '-', '²': '**2', '³': '**3', '(': '(', ')': ')'})
  183. expr = str(expression).translate(chars).strip()
  184. if not expr or len(expr) > 512: raise ValueError('表达式为空或过长')
  185. try:
  186. return walk(ast.parse(expr, mode='eval').body)
  187. except (KeyError, SyntaxError, TypeError):
  188. raise ValueError('不支持的表达式语法') from None