trainer_utils.py 5.8 KB

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