trainer_utils.py 4.9 KB

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