trainer_utils.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. def is_main_process():
  12. return not dist.is_initialized() or dist.get_rank() == 0
  13. def Logger(content):
  14. if is_main_process():
  15. print(content)
  16. def get_lr(current_step, total_steps, lr):
  17. return lr / 10 + 0.5 * lr * (1 + math.cos(math.pi * current_step / total_steps))
  18. def init_distributed_mode():
  19. if int(os.environ.get("RANK", -1)) == -1:
  20. return 0 # 非DDP模式
  21. dist.init_process_group(backend="nccl")
  22. local_rank = int(os.environ["LOCAL_RANK"])
  23. torch.cuda.set_device(local_rank)
  24. return local_rank
  25. def setup_seed(seed: int):
  26. random.seed(seed)
  27. np.random.seed(seed)
  28. torch.manual_seed(seed)
  29. torch.cuda.manual_seed(seed)
  30. torch.cuda.manual_seed_all(seed)
  31. torch.backends.cudnn.deterministic = True
  32. torch.backends.cudnn.benchmark = False
  33. def lm_checkpoint(lm_config, weight='full_sft', model=None, optimizer=None, epoch=0, step=0, wandb=None, save_dir='../checkpoints', **kwargs):
  34. os.makedirs(save_dir, exist_ok=True)
  35. moe_path = '_moe' if lm_config.use_moe else ''
  36. ckp_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}.pth'
  37. resume_path = f'{save_dir}/{weight}_{lm_config.hidden_size}{moe_path}_resume.pth'
  38. if model is not None:
  39. from torch.nn.parallel import DistributedDataParallel
  40. state_dict = model.module.state_dict() if isinstance(model, DistributedDataParallel) else model.state_dict()
  41. ckp_tmp = ckp_path + '.tmp'
  42. torch.save({k: v.half() for k, v in state_dict.items()}, ckp_tmp)
  43. os.replace(ckp_tmp, ckp_path)
  44. wandb_id = None
  45. if wandb:
  46. if hasattr(wandb, 'get_run'):
  47. run = wandb.get_run()
  48. wandb_id = getattr(run, 'id', None) if run else None
  49. else:
  50. wandb_id = getattr(wandb, 'id', None)
  51. resume_data = {
  52. 'model': state_dict,
  53. 'optimizer': optimizer.state_dict(),
  54. 'epoch': epoch,
  55. 'step': step,
  56. 'world_size': dist.get_world_size() if dist.is_initialized() else 1,
  57. 'wandb_id': wandb_id
  58. }
  59. for key, value in kwargs.items():
  60. if value is not None:
  61. if hasattr(value, 'state_dict'):
  62. if isinstance(value, DistributedDataParallel):
  63. resume_data[key] = value.module.state_dict()
  64. else:
  65. resume_data[key] = value.state_dict()
  66. else:
  67. resume_data[key] = value
  68. resume_tmp = resume_path + '.tmp'
  69. torch.save(resume_data, resume_tmp)
  70. os.replace(resume_tmp, resume_path)
  71. else: # 加载模式
  72. if os.path.exists(resume_path):
  73. ckp_data = torch.load(resume_path, map_location='cpu')
  74. saved_ws = ckp_data.get('world_size', 1)
  75. current_ws = dist.get_world_size() if dist.is_initialized() else 1
  76. if saved_ws != current_ws:
  77. ckp_data['step'] = ckp_data['step'] * saved_ws // current_ws
  78. Logger(f'GPU数量变化({saved_ws}→{current_ws}),step已自动转换为{ckp_data["step"]}')
  79. return ckp_data
  80. return None
  81. def init_model(lm_config, from_weight='pretrain', tokenizer_path='../model', save_dir='../out', device='cuda'):
  82. from transformers import AutoTokenizer
  83. from model.model_minimind import MiniMindForCausalLM
  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)