trainer_utils.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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.utils.data import Sampler
  14. from transformers import AutoTokenizer
  15. from model.model_minimind import MiniMindForCausalLM
  16. def get_model_params(model, config):
  17. total = sum(p.numel() for p in model.parameters()) / 1e6
  18. if getattr(config, 'use_moe', False):
  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. Logger(f'Model Params: {total:.2f}M-A{active:.2f}M')
  27. else:
  28. Logger(f'Model Params: {total:.2f}M')
  29. def is_main_process():
  30. return not dist.is_initialized() or dist.get_rank() == 0
  31. def Logger(content):
  32. if is_main_process():
  33. print(content)
  34. def get_lr(current_step, total_steps, lr):
  35. return lr*(0.1 + 0.45*(1 + math.cos(math.pi * current_step / total_steps)))
  36. def init_distributed_mode():
  37. if int(os.environ.get("RANK", -1)) == -1:
  38. return 0 # 非DDP模式
  39. dist.init_process_group(backend="nccl")
  40. local_rank = int(os.environ["LOCAL_RANK"])
  41. torch.cuda.set_device(local_rank)
  42. return local_rank
  43. def setup_seed(seed: int):
  44. random.seed(seed)
  45. np.random.seed(seed)
  46. torch.manual_seed(seed)
  47. torch.cuda.manual_seed(seed)
  48. torch.cuda.manual_seed_all(seed)
  49. torch.backends.cudnn.deterministic = True
  50. torch.backends.cudnn.benchmark = False
  51. def lm_checkpoint(lm_config, weight='full_sft', model=None, optimizer=None, epoch=0, step=0, wandb=None, save_dir='../checkpoints', **kwargs):
  52. os.makedirs(save_dir, exist_ok=True)
  53. moe_path = '_moe' if lm_config.use_moe else ''
  54. ckp_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}.pth'
  55. resume_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}_resume.pth'
  56. if model is not None:
  57. from torch.nn.parallel import DistributedDataParallel
  58. state_dict = model.module.state_dict() if isinstance(model, DistributedDataParallel) else 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. if isinstance(value, DistributedDataParallel):
  82. resume_data[key] = value.module.state_dict()
  83. else:
  84. resume_data[key] = value.state_dict()
  85. else:
  86. resume_data[key] = value
  87. resume_tmp = resume_path + '.tmp'
  88. torch.save(resume_data, resume_tmp)
  89. os.replace(resume_tmp, resume_path)
  90. del state_dict, resume_data
  91. torch.cuda.empty_cache()
  92. else: # 加载模式
  93. if os.path.exists(resume_path):
  94. ckp_data = torch.load(resume_path, map_location='cpu')
  95. saved_ws = ckp_data.get('world_size', 1)
  96. current_ws = dist.get_world_size() if dist.is_initialized() else 1
  97. if saved_ws != current_ws:
  98. ckp_data['step'] = ckp_data['step'] * saved_ws // current_ws
  99. Logger(f'GPU数量变化({saved_ws}→{current_ws}),step已自动转换为{ckp_data["step"]}')
  100. return ckp_data
  101. return None
  102. def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', save_dir='../out', device='cuda'):
  103. tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
  104. model = MiniMindForCausalLM(lm_config)
  105. if from_weight!= 'none':
  106. moe_suffix = '_moe' if lm_config.use_moe else ''
  107. weight_path = f'{save_dir}/{from_weight}_{lm_config.hidden_size}{moe_suffix}.pth'
  108. weights = torch.load(weight_path, map_location=device)
  109. model.load_state_dict(weights, strict=False)
  110. get_model_params(model, lm_config)
  111. Logger(f'Trainable Params: {sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6:.3f}M')
  112. return model.to(device), tokenizer
  113. class SkipBatchSampler(Sampler):
  114. def __init__(self, sampler, batch_size, skip_batches=0):
  115. self.sampler = sampler
  116. self.batch_size = batch_size
  117. self.skip_batches = skip_batches
  118. def __iter__(self):
  119. batch = []
  120. skipped = 0
  121. for idx in self.sampler:
  122. batch.append(idx)
  123. if len(batch) == self.batch_size:
  124. if skipped < self.skip_batches:
  125. skipped += 1
  126. batch = []
  127. continue
  128. yield batch
  129. batch = []
  130. if len(batch) > 0 and skipped >= self.skip_batches:
  131. yield batch
  132. def __len__(self):
  133. total_batches = (len(self.sampler) + self.batch_size - 1) // self.batch_size
  134. return max(0, total_batches - self.skip_batches)