trainer_utils.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. """
  2. 训练工具函数集合
  3. """
  4. import gc
  5. import os
  6. import random
  7. import math
  8. import numpy as np
  9. import torch
  10. import torch.distributed as dist
  11. from torch.utils.data import Sampler
  12. from transformers import AutoTokenizer
  13. from model.model_minimind import MiniMindForCausalLM
  14. def is_main_process():
  15. return not dist.is_initialized() or dist.get_rank() == 0
  16. def Logger(content):
  17. if is_main_process():
  18. print(content)
  19. def get_lr(current_step, total_steps, lr):
  20. min_lr = lr / 10
  21. return min_lr + 0.5 * (lr - min_lr) * (1 + math.cos(math.pi * current_step / total_steps))
  22. def init_distributed_mode():
  23. if int(os.environ.get("RANK", -1)) == -1:
  24. return 0 # 非DDP模式
  25. dist.init_process_group(backend="nccl")
  26. local_rank = int(os.environ["LOCAL_RANK"])
  27. torch.cuda.set_device(local_rank)
  28. return local_rank
  29. def setup_seed(seed: int):
  30. random.seed(seed)
  31. np.random.seed(seed)
  32. torch.manual_seed(seed)
  33. torch.cuda.manual_seed(seed)
  34. torch.cuda.manual_seed_all(seed)
  35. torch.backends.cudnn.deterministic = True
  36. torch.backends.cudnn.benchmark = False
  37. def lm_checkpoint(lm_config, weight='full_sft', model=None, optimizer=None, epoch=0, step=0, wandb=None, save_dir='../checkpoints', **kwargs):
  38. os.makedirs(save_dir, exist_ok=True)
  39. moe_path = '_moe' if lm_config.use_moe else ''
  40. ckp_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}.pth'
  41. resume_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}_resume.pth'
  42. if model is not None:
  43. from torch.nn.parallel import DistributedDataParallel
  44. state_dict = model.module.state_dict() if isinstance(model, DistributedDataParallel) else model.state_dict()
  45. state_dict = {k: v.half().cpu() for k, v in state_dict.items()}
  46. ckp_tmp = ckp_path + '.tmp'
  47. torch.save(state_dict, ckp_tmp)
  48. os.replace(ckp_tmp, ckp_path)
  49. wandb_id = None
  50. if wandb:
  51. if hasattr(wandb, 'get_run'):
  52. run = wandb.get_run()
  53. wandb_id = getattr(run, 'id', None) if run else None
  54. else:
  55. wandb_id = getattr(wandb, 'id', None)
  56. resume_data = {
  57. 'model': state_dict,
  58. 'optimizer': optimizer.state_dict(),
  59. 'epoch': epoch,
  60. 'step': step,
  61. 'world_size': dist.get_world_size() if dist.is_initialized() else 1,
  62. 'wandb_id': wandb_id
  63. }
  64. for key, value in kwargs.items():
  65. if value is not None:
  66. if hasattr(value, 'state_dict'):
  67. if isinstance(value, DistributedDataParallel):
  68. resume_data[key] = value.module.state_dict()
  69. else:
  70. resume_data[key] = value.state_dict()
  71. else:
  72. resume_data[key] = value
  73. resume_tmp = resume_path + '.tmp'
  74. torch.save(resume_data, resume_tmp)
  75. os.replace(resume_tmp, resume_path)
  76. del state_dict, resume_data
  77. gc.collect()
  78. torch.cuda.empty_cache()
  79. else: # 加载模式
  80. if os.path.exists(resume_path):
  81. ckp_data = torch.load(resume_path, map_location='cpu')
  82. saved_ws = ckp_data.get('world_size', 1)
  83. current_ws = dist.get_world_size() if dist.is_initialized() else 1
  84. if saved_ws != current_ws:
  85. ckp_data['step'] = ckp_data['step'] * saved_ws // current_ws
  86. Logger(f'GPU数量变化({saved_ws}→{current_ws}),step已自动转换为{ckp_data["step"]}')
  87. return ckp_data
  88. return None
  89. def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', save_dir='../out', device='cuda'):
  90. tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
  91. model = MiniMindForCausalLM(lm_config)
  92. if from_weight!= 'none':
  93. moe_suffix = '_moe' if lm_config.use_moe else ''
  94. weight_path = f'{save_dir}/{from_weight}_{lm_config.hidden_size}{moe_suffix}.pth'
  95. weights = torch.load(weight_path, map_location=device)
  96. model.load_state_dict(weights, strict=False)
  97. Logger(f'所加载Model可训练参数:{sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6:.3f} 百万')
  98. return model.to(device), tokenizer
  99. class SkipBatchSampler(Sampler):
  100. def __init__(self, sampler, batch_size, skip_batches=0):
  101. self.sampler = sampler
  102. self.batch_size = batch_size
  103. self.skip_batches = skip_batches
  104. def __iter__(self):
  105. batch = []
  106. skipped = 0
  107. for idx in self.sampler:
  108. batch.append(idx)
  109. if len(batch) == self.batch_size:
  110. if skipped < self.skip_batches:
  111. skipped += 1
  112. batch = []
  113. continue
  114. yield batch
  115. batch = []
  116. if len(batch) > 0 and skipped >= self.skip_batches:
  117. yield batch
  118. def __len__(self):
  119. total_batches = (len(self.sampler) + self.batch_size - 1) // self.batch_size
  120. return max(0, total_batches - self.skip_batches)