trainer_utils.py 5.0 KB

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