train_get.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import cv2
  2. import tqdm
  3. import wandb
  4. import torch
  5. import numpy as np
  6. import albumentations
  7. from block.val_get import val_get
  8. from block.model_ema import model_ema
  9. from block.lr_get import adam, lr_adjust
  10. '''
  11. 处理训练过程
  12. '''
  13. def train_get(args, data_dict, model_dict, loss):
  14. # 加载模型
  15. model = model_dict['model'].to(args.device, non_blocking=args.latch)
  16. print(model)
  17. # 学习率
  18. optimizer = adam(args.regularization, args.r_value, model.parameters(), lr=args.lr_start, betas=(0.937, 0.999))
  19. optimizer.load_state_dict(model_dict['optimizer_state_dict']) if model_dict['optimizer_state_dict'] else None
  20. step_epoch = len(data_dict['train']) // args.batch // args.device_number * args.device_number # 每轮的步数
  21. print(len(data_dict['train']) // args.batch)
  22. print(step_epoch)
  23. optimizer_adjust = lr_adjust(args, step_epoch, model_dict['epoch_finished']) # 学习率调整函数
  24. optimizer = optimizer_adjust(optimizer) # 学习率初始化
  25. # 使用平均指数移动(EMA)调整参数(不能将ema放到args中,否则会导致模型保存出错)
  26. ema = model_ema(model) if args.ema else None
  27. if args.ema:
  28. ema.updates = model_dict['ema_updates']
  29. # 数据集
  30. train_dataset = torch_dataset(args, 'train', data_dict['train'], data_dict['class'])
  31. train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) if args.distributed else None
  32. train_shuffle = False if args.distributed else True # 分布式设置sampler后shuffle要为False
  33. train_dataloader = torch.utils.data.DataLoader(train_dataset, batch_size=args.batch, shuffle=train_shuffle,
  34. drop_last=True, pin_memory=args.latch, num_workers=args.num_worker,
  35. sampler=train_sampler)
  36. # 验证集不对图像进行处理
  37. val_dataset = torch_dataset(args, 'test', data_dict['test'], data_dict['class'])
  38. val_sampler = None # 分布式时数据合在主GPU上进行验证
  39. val_batch = args.batch // args.device_number # 分布式验证时batch要减少为一个GPU的量
  40. val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=val_batch, shuffle=False,
  41. drop_last=False, pin_memory=args.latch, num_workers=args.num_worker,
  42. sampler=val_sampler)
  43. # 分布式初始化
  44. model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank],
  45. output_device=args.local_rank) if args.distributed else model
  46. # wandb
  47. if args.wandb and args.local_rank == 0:
  48. wandb_image_list = [] # 记录所有的wandb_image最后一起添加(最多添加args.wandb_image_num张)
  49. epoch_base = model_dict['epoch_finished'] + 1 # 新的一轮要+1
  50. for epoch in range(epoch_base, args.epoch + 1): # 训练
  51. print(f'\n-----------------------第{epoch}轮-----------------------') if args.local_rank == 0 else None
  52. model.train()
  53. train_loss = 0 # 记录损失
  54. if args.local_rank == 0: # tqdm
  55. tqdm_show = tqdm.tqdm(total=step_epoch)
  56. for index, (image_batch, true_batch) in enumerate(train_dataloader):
  57. if args.wandb and args.local_rank == 0 and len(wandb_image_list) < args.wandb_image_num:
  58. wandb_image_batch = (image_batch * 255).cpu().numpy().astype(np.uint8).transpose(0, 2, 3, 1)
  59. image_batch = image_batch.to(args.device, non_blocking=args.latch)
  60. true_batch = true_batch.to(args.device, non_blocking=args.latch)
  61. if args.amp:
  62. with torch.cuda.amp.autocast():
  63. pred_batch = model(image_batch)
  64. loss_batch = loss(pred_batch, true_batch)
  65. args.amp.scale(loss_batch).backward()
  66. args.amp.step(optimizer)
  67. args.amp.update()
  68. optimizer.zero_grad()
  69. else:
  70. pred_batch = model(image_batch)
  71. loss_batch = loss(pred_batch, true_batch)
  72. loss_batch.backward()
  73. optimizer.step()
  74. optimizer.zero_grad()
  75. # 调整参数,ema.updates会自动+1
  76. ema.update(model) if args.ema else None
  77. # 记录损失
  78. train_loss += loss_batch.item()
  79. # 调整学习率
  80. optimizer = optimizer_adjust(optimizer)
  81. # tqdm
  82. if args.local_rank == 0:
  83. tqdm_show.set_postfix({'train_loss': loss_batch.item(),
  84. 'lr': optimizer.param_groups[0]['lr']}) # 添加显示
  85. tqdm_show.update(args.device_number) # 更新进度条
  86. # wandb
  87. if args.wandb and args.local_rank == 0 and epoch == 0 and len(wandb_image_list) < args.wandb_image_num:
  88. cls = true_batch.cpu().numpy().tolist()
  89. for i in range(len(wandb_image_batch)): # 遍历每一张图片
  90. image = wandb_image_batch[i]
  91. text = ['{:.0f}'.format(_) for _ in cls[i]]
  92. text = text[0] if len(text) == 1 else '--'.join(text)
  93. image = np.ascontiguousarray(image) # 将数组的内存变为连续存储(cv2画图的要求)
  94. cv2.putText(image, text, (30, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
  95. wandb_image = wandb.Image(image)
  96. wandb_image_list.append(wandb_image)
  97. if len(wandb_image_list) == args.wandb_image_num:
  98. break
  99. # tqdm
  100. if args.local_rank == 0:
  101. tqdm_show.close()
  102. # 计算平均损失
  103. train_loss /= index + 1
  104. if args.local_rank == 0:
  105. print(f'\n| 训练 | train_loss:{train_loss:.4f} | lr:{optimizer.param_groups[0]["lr"]:.6f} |\n')
  106. # 清理显存空间
  107. del image_batch, true_batch, pred_batch, loss_batch
  108. torch.cuda.empty_cache()
  109. # 验证
  110. if args.local_rank == 0: # 分布式时只验证一次
  111. # val_loss, accuracy, precision, recall, m_ap = val_get(args, val_dataloader, model, loss, ema,
  112. # len(data_dict['test']))
  113. val_loss, accuracy = val_get(args, val_dataloader, model, loss, ema, len(data_dict['test']))
  114. # 保存
  115. if args.local_rank == 0: # 分布式时只保存一次
  116. model_dict['model'] = model.module if args.distributed else model
  117. model_dict['epoch_finished'] = epoch
  118. model_dict['optimizer_state_dict'] = optimizer.state_dict()
  119. model_dict['ema_updates'] = ema.updates if args.ema else model_dict['ema_updates']
  120. model_dict['class'] = data_dict['class']
  121. model_dict['train_loss'] = train_loss
  122. model_dict['val_loss'] = val_loss
  123. model_dict['val_accuracy'] = accuracy
  124. # model_dict['val_precision'] = precision
  125. # model_dict['val_recall'] = recall
  126. # model_dict['val_m_ap'] = m_ap
  127. torch.save(model_dict, args.save_path_last if not args.prune else 'prune_last.pt') # 保存最后一次训练的模型
  128. # if m_ap > 0.5 and m_ap > model_dict['standard']:
  129. # model_dict['standard'] = m_ap
  130. # save_path = args.save_path if not args.prune else args.prune_save
  131. # torch.save(model_dict, save_path) # 保存最佳模型
  132. # print(f'| 保存最佳模型:{save_path} | val_m_ap:{m_ap:.4f} |')
  133. if accuracy > 0.5 and accuracy > model_dict['standard']:
  134. model_dict['standard'] = accuracy
  135. save_path = args.save_path if not args.prune else args.prune_save
  136. torch.save(model_dict, save_path) # 保存最佳模型
  137. print(f'| 保存最佳模型:{save_path} | accuracy:{(100 * accuracy):.4f}% |')
  138. # wandb
  139. if args.wandb:
  140. wandb_log = {}
  141. if epoch == 0:
  142. wandb_log.update({f'image/train_image': wandb_image_list})
  143. # wandb_log.update({'metric/train_loss': train_loss,
  144. # 'metric/val_loss': val_loss,
  145. # 'metric/val_m_ap': m_ap,
  146. # 'metric/val_accuracy': accuracy,
  147. # 'metric/val_precision': precision,
  148. # 'metric/val_recall': recall})
  149. wandb_log.update({'metric/train_loss': train_loss,
  150. 'metric/val_loss': val_loss,
  151. 'metric/val_accuracy': accuracy})
  152. args.wandb_run.log(wandb_log)
  153. torch.distributed.barrier() if args.distributed else None # 分布式时每轮训练后让所有GPU进行同步,快的GPU会在此等待
  154. class torch_dataset(torch.utils.data.Dataset):
  155. def __init__(self, args, tag, data, class_name):
  156. self.tag = tag
  157. self.data = data
  158. self.class_name = class_name
  159. self.noise_probability = args.noise
  160. self.noise = albumentations.Compose([
  161. albumentations.GaussianBlur(blur_limit=(5, 5), p=0.2),
  162. albumentations.GaussNoise(var_limit=(10.0, 30.0), p=0.2),], )
  163. self.transform = albumentations.Compose([
  164. albumentations.LongestMaxSize(args.input_size),
  165. albumentations.PadIfNeeded(min_height=args.input_size, min_width=args.input_size,
  166. border_mode=cv2.BORDER_CONSTANT, value=(128, 128, 128))])
  167. self.rgb_mean = (0.406, 0.456, 0.485)
  168. self.rgb_std = (0.225, 0.224, 0.229)
  169. def __len__(self):
  170. return len(self.data)
  171. def __getitem__(self, index):
  172. image = cv2.imread(self.data[index][0]) # 读取图片
  173. if self.tag == 'train' and torch.rand(1) < self.noise_probability: # 使用数据加噪
  174. image = self.noise(image=image)['image']
  175. image = self.transform(image=image)['image'] # 缩放和填充图片
  176. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # 转为RGB通道
  177. image = self._image_deal(image) # 归一化、转换为tensor、调维度
  178. label = torch.tensor(self.data[index][1], dtype=torch.float32) # 转换为tensor
  179. return image, label
  180. def _image_deal(self, image): # 归一化、转换为tensor、调维度
  181. image = torch.tensor(image / 255, dtype=torch.float32).permute(2, 0, 1)
  182. return image