trainer_utils.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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 random
  9. import math
  10. import numpy as np
  11. import torch
  12. import torch.distributed as dist
  13. from torch.nn.parallel import DistributedDataParallel
  14. from torch.utils.data import Sampler
  15. from transformers import AutoTokenizer, AutoModel, AutoModelForSequenceClassification
  16. from model.model_minimind import MiniMindForCausalLM
  17. def get_model_params(model, config):
  18. total = sum(p.numel() for p in model.parameters()) / 1e6
  19. n_routed = getattr(config, 'n_routed_experts', getattr(config, 'num_experts', 0))
  20. n_active = getattr(config, 'num_experts_per_tok', 0)
  21. n_shared = getattr(config, 'n_shared_experts', 0)
  22. expert = sum(p.numel() for n, p in model.named_parameters() if 'mlp.experts.0.' in n) / 1e6
  23. shared_expert = sum(p.numel() for n, p in model.named_parameters() if 'mlp.shared_experts.0.' in n) / 1e6
  24. base = total - (expert * n_routed) - (shared_expert * n_shared)
  25. active = base + (expert * n_active) + (shared_expert * n_shared)
  26. if active < total: Logger(f'Model Params: {total:.2f}M-A{active:.2f}M')
  27. else: Logger(f'Model Params: {total:.2f}M')
  28. def is_main_process():
  29. return not dist.is_initialized() or dist.get_rank() == 0
  30. def Logger(content):
  31. if is_main_process():
  32. print(content)
  33. def get_lr(current_step, total_steps, lr):
  34. return lr*(0.1 + 0.45*(1 + math.cos(math.pi * current_step / total_steps)))
  35. def init_distributed_mode():
  36. if int(os.environ.get("RANK", -1)) == -1:
  37. return 0 # 非DDP模式
  38. dist.init_process_group(backend="nccl")
  39. local_rank = int(os.environ["LOCAL_RANK"])
  40. torch.cuda.set_device(local_rank)
  41. return local_rank
  42. def setup_seed(seed: int):
  43. random.seed(seed)
  44. np.random.seed(seed)
  45. torch.manual_seed(seed)
  46. torch.cuda.manual_seed(seed)
  47. torch.cuda.manual_seed_all(seed)
  48. torch.backends.cudnn.deterministic = True
  49. torch.backends.cudnn.benchmark = False
  50. def lm_checkpoint(lm_config, weight='full_sft', model=None, optimizer=None, epoch=0, step=0, wandb=None, save_dir='../checkpoints', **kwargs):
  51. os.makedirs(save_dir, exist_ok=True)
  52. moe_path = '_moe' if lm_config.use_moe else ''
  53. ckp_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}.pth'
  54. resume_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}_resume.pth'
  55. if model is not None:
  56. raw_model = model.module if isinstance(model, DistributedDataParallel) else model
  57. raw_model = getattr(raw_model, '_orig_mod', raw_model)
  58. state_dict = raw_model.state_dict()
  59. state_dict = {k: v.half().cpu() for k, v in state_dict.items()}
  60. ckp_tmp = ckp_path + '.tmp'
  61. torch.save(state_dict, ckp_tmp)
  62. os.replace(ckp_tmp, ckp_path)
  63. wandb_id = None
  64. if wandb:
  65. if hasattr(wandb, 'get_run'):
  66. run = wandb.get_run()
  67. wandb_id = getattr(run, 'id', None) if run else None
  68. else:
  69. wandb_id = getattr(wandb, 'id', None)
  70. resume_data = {
  71. 'model': state_dict,
  72. 'optimizer': optimizer.state_dict(),
  73. 'epoch': epoch,
  74. 'step': step,
  75. 'world_size': dist.get_world_size() if dist.is_initialized() else 1,
  76. 'wandb_id': wandb_id
  77. }
  78. for key, value in kwargs.items():
  79. if value is not None:
  80. if hasattr(value, 'state_dict'):
  81. raw_value = value.module if isinstance(value, DistributedDataParallel) else value
  82. raw_value = getattr(raw_value, '_orig_mod', raw_value)
  83. resume_data[key] = raw_value.state_dict()
  84. else:
  85. resume_data[key] = value
  86. resume_tmp = resume_path + '.tmp'
  87. torch.save(resume_data, resume_tmp)
  88. os.replace(resume_tmp, resume_path)
  89. del state_dict, resume_data
  90. torch.cuda.empty_cache()
  91. else: # 加载模式
  92. if os.path.exists(resume_path):
  93. ckp_data = torch.load(resume_path, map_location='cpu')
  94. saved_ws = ckp_data.get('world_size', 1)
  95. current_ws = dist.get_world_size() if dist.is_initialized() else 1
  96. if saved_ws != current_ws:
  97. ckp_data['step'] = ckp_data['step'] * saved_ws // current_ws
  98. Logger(f'GPU数量变化({saved_ws}→{current_ws}),step已自动转换为{ckp_data["step"]}')
  99. return ckp_data
  100. return None
  101. def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', save_dir='../out', device='cuda'):
  102. tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
  103. model = MiniMindForCausalLM(lm_config)
  104. if from_weight!= 'none':
  105. moe_suffix = '_moe' if lm_config.use_moe else ''
  106. weight_path = f'{save_dir}/{from_weight}_{lm_config.hidden_size}{moe_suffix}.pth'
  107. weights = torch.load(weight_path, map_location=device)
  108. model.load_state_dict(weights, strict=False)
  109. get_model_params(model, lm_config)
  110. Logger(f'Trainable Params: {sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6:.3f}M')
  111. return model.to(device), tokenizer
  112. class SkipBatchSampler(Sampler):
  113. def __init__(self, sampler, batch_size, skip_batches=0):
  114. self.sampler = sampler
  115. self.batch_size = batch_size
  116. self.skip_batches = skip_batches
  117. def __iter__(self):
  118. batch = []
  119. skipped = 0
  120. for idx in self.sampler:
  121. batch.append(idx)
  122. if len(batch) == self.batch_size:
  123. if skipped < self.skip_batches:
  124. skipped += 1
  125. batch = []
  126. continue
  127. yield batch
  128. batch = []
  129. if len(batch) > 0 and skipped >= self.skip_batches:
  130. yield batch
  131. def __len__(self):
  132. total_batches = (len(self.sampler) + self.batch_size - 1) // self.batch_size
  133. return max(0, total_batches - self.skip_batches)
  134. class LMForRewardModel:
  135. def __init__(self, model_path, device="cuda", dtype=torch.float16):
  136. self.tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
  137. self.model = AutoModel.from_pretrained(model_path, torch_dtype=dtype, trust_remote_code=True)
  138. self.model = self.model.to(device).eval()
  139. self.device = device
  140. @torch.no_grad()
  141. def get_score(self, messages, response):
  142. history_text = "\n".join([f"{m['role']}: {m['content']}" for m in messages[:-1]])
  143. last_query = messages[-1]['content'] if messages else ""
  144. message_context = f"{history_text}\n以上是对话历史。我的新问题是:\n{last_query}" if history_text else last_query
  145. eval_messages = [
  146. {"role": "user", "content": message_context},
  147. {"role": "assistant", "content": response}
  148. ]
  149. score = self.model.get_score(self.tokenizer, eval_messages)
  150. return max(min(score, 3.0), -3.0)