trainer.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. import os
  2. import time
  3. from datetime import datetime
  4. import cv2
  5. import numpy as np
  6. import torch
  7. from matplotlib import pyplot as plt
  8. from scipy.ndimage import gaussian_filter
  9. from torch.optim.lr_scheduler import ReduceLROnPlateau
  10. from torch.utils.tensorboard import SummaryWriter
  11. from libs.vision_libs.utils import draw_bounding_boxes, draw_keypoints
  12. from models.base.base_model import BaseModel
  13. from models.base.base_trainer import BaseTrainer
  14. from models.config.config_tool import read_yaml
  15. from models.line_detect.line_dataset import LineDataset
  16. import torch.nn.functional as F
  17. from tools import utils
  18. import matplotlib as mpl
  19. cmap = plt.get_cmap("jet")
  20. norm = mpl.colors.Normalize(vmin=0.4, vmax=1.0)
  21. sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
  22. sm.set_array([])
  23. def _loss(losses):
  24. total_loss = 0
  25. for i in losses.keys():
  26. if i != "loss_wirepoint":
  27. total_loss += losses[i]
  28. else:
  29. loss_labels = losses[i]["losses"]
  30. loss_labels_k = list(loss_labels[0].keys())
  31. for j, name in enumerate(loss_labels_k):
  32. loss = loss_labels[0][name].mean()
  33. total_loss += loss
  34. return total_loss
  35. def c(x):
  36. return sm.to_rgba(x)
  37. device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
  38. def draw_ellipses_on_image(image, masks_pred, threshold=0.5, color=(0, 255, 0), thickness=2):
  39. """
  40. 在单张原始图像上绘制从 masks 拟合出的椭圆。
  41. 自动将 masks resize 到 image 的空间尺寸。
  42. Args:
  43. image: Tensor [3, H_img, W_img] —— 原始图像(如 [3, 2000, 2000])
  44. masks_pred: Tensor [N, 1, H_mask, W_mask] or [N, H_mask, W_mask] —— 模型输出 mask(如 [2, 1, 672, 672])
  45. threshold: 二值化阈值
  46. color: BGR color for OpenCV
  47. thickness: ellipse line thickness
  48. Returns:
  49. drawn_image: numpy array [H_img, W_img, 3] in RGB
  50. """
  51. # Step 1: 标准化 masks_pred to [N, H, W]
  52. if masks_pred.ndim == 4:
  53. if masks_pred.shape[1] == 1:
  54. masks_pred = masks_pred.squeeze(1) # [N, 1, H, W] -> [N, H, W]
  55. else:
  56. raise ValueError(f"Expected channel=1 in masks_pred, got shape {masks_pred.shape}")
  57. elif masks_pred.ndim != 3:
  58. raise ValueError(f"masks_pred must be 3D (N, H, W) or 4D (N, 1, H, W), got {masks_pred.shape}")
  59. N, H_mask, W_mask = masks_pred.shape
  60. C, H_img, W_img = image.shape
  61. # Step 2: Resize masks to original image size using bilinear interpolation
  62. masks_resized = F.interpolate(
  63. masks_pred.unsqueeze(1).float(), # [N, 1, H_mask, W_mask]
  64. size=(H_img, W_img),
  65. mode='bilinear',
  66. align_corners=False
  67. ).squeeze(1) # [N, H_img, W_img]
  68. # Step 3: Convert image to numpy RGB
  69. img_tensor = image.detach().cpu()
  70. if img_tensor.max() <= 1.0:
  71. img_np = (img_tensor * 255).byte().numpy() # [3, H, W]
  72. else:
  73. img_np = img_tensor.byte().numpy()
  74. img_rgb = np.transpose(img_np, (1, 2, 0)) # [H, W, 3]
  75. img_out = img_rgb.copy()
  76. # Step 4: Process each mask
  77. for mask in masks_resized:
  78. mask_cpu = mask.detach().cpu()
  79. mask_prob = torch.sigmoid(mask_cpu) if mask_cpu.min() < 0 else mask_cpu
  80. binary = (mask_prob > threshold).numpy().astype(np.uint8) * 255 # [H_img, W_img]
  81. contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  82. if contours:
  83. largest_contour = max(contours, key=cv2.contourArea)
  84. if len(largest_contour) >= 5:
  85. try:
  86. ellipse = cv2.fitEllipse(largest_contour)
  87. img_bgr = cv2.cvtColor(img_out, cv2.COLOR_RGB2BGR)
  88. cv2.ellipse(img_bgr, ellipse, color=color, thickness=thickness)
  89. img_out = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
  90. except cv2.error as e:
  91. print(f"Warning: Failed to fit ellipse: {e}")
  92. return img_out
  93. def fit_circle(points):
  94. """
  95. Fit a circle to a set of points (at least 3).
  96. Args:
  97. points: torch.Tensor 或 numpy array, shape (N, 2)
  98. Returns:
  99. center (cx, cy), radius r
  100. """
  101. # 如果是 torch.Tensor,先转为 numpy
  102. if isinstance(points, torch.Tensor):
  103. if points.dim() == 3:
  104. points = points[0] # 去掉 batch 维度
  105. points = points.detach().cpu().numpy()
  106. if not (isinstance(points, np.ndarray) and points.ndim == 2 and points.shape[1] == 2):
  107. raise ValueError(f"Expected points shape (N, 2), got {points.shape}")
  108. x = points[:, 0].astype(float)
  109. y = points[:, 1].astype(float)
  110. # 确保 A 是二维数组
  111. A = np.column_stack((x, y, np.ones_like(x))) # 使用 column_stack 代替 stack 可能更清晰
  112. b = -(x ** 2 + y ** 2)
  113. try:
  114. sol, residuals, rank, s = np.linalg.lstsq(A, b, rcond=None)
  115. except np.linalg.LinAlgError as e:
  116. print(f"Linear algebra error occurred: {e}")
  117. raise ValueError("Could not fit circle to points.")
  118. D, E, F = sol
  119. cx = -D / 2.0
  120. cy = -E / 2.0
  121. r = np.sqrt(cx ** 2 + cy ** 2 - F)
  122. return (cx, cy), r
  123. # 由低到高蓝黄红
  124. def draw_lines_with_scores(tensor_image, lines, scores, width=3, cmap='viridis'):
  125. """
  126. 根据得分对线段着色并绘制
  127. :param tensor_image: (3, H, W) uint8 图像
  128. :param lines: (N, 2, 2) 每条线 [ [x1,y1], [x2,y2] ]
  129. :param scores: (N,) 每条线的得分,范围 [0, 1]
  130. :param width: 线宽
  131. :param cmap: matplotlib colormap 名称,例如 'viridis', 'jet', 'coolwarm'
  132. :return: (3, H, W) uint8 画好线的图像
  133. """
  134. assert tensor_image.dtype == torch.uint8
  135. assert tensor_image.shape[0] == 3
  136. assert lines.shape[0] == scores.shape[0]
  137. # 准备色图
  138. colormap = plt.get_cmap(cmap)
  139. colors = (colormap(scores.cpu().numpy())[:, :3] * 255).astype('uint8') # 去掉 alpha 通道
  140. # 转为 PIL 画图
  141. image_pil = F.to_pil_image(tensor_image)
  142. draw = ImageDraw.Draw(image_pil)
  143. for line, color in zip(lines, colors):
  144. start = tuple(map(float, line[0][:2].tolist()))
  145. end = tuple(map(float, line[1][:2].tolist()))
  146. draw.line([start, end], fill=tuple(color), width=width)
  147. return (F.to_tensor(image_pil) * 255).to(torch.uint8)
  148. class Trainer(BaseTrainer):
  149. def __init__(self, model=None, **kwargs):
  150. super().__init__(model, device, **kwargs)
  151. self.model = model
  152. # print(f'kwargs:{kwargs}')
  153. self.init_params(**kwargs)
  154. def init_params(self, **kwargs):
  155. if kwargs != {}:
  156. print(f'train_params:{kwargs["train_params"]}')
  157. self.freeze_config = kwargs['train_params']['freeze_params']
  158. print(f'freeze_config:{self.freeze_config}')
  159. self.dataset_path = kwargs['io']['datadir']
  160. self.data_type = kwargs['io']['data_type']
  161. self.batch_size = kwargs['train_params']['batch_size']
  162. self.num_workers = kwargs['train_params']['num_workers']
  163. self.logdir = kwargs['io']['logdir']
  164. self.resume_from = kwargs['train_params']['resume_from']
  165. self.optim = ''
  166. self.train_result_ptath = os.path.join(self.logdir, datetime.now().strftime("%Y%m%d_%H%M%S"))
  167. self.wts_path = os.path.join(self.train_result_ptath, 'weights')
  168. self.tb_path = os.path.join(self.train_result_ptath, 'logs')
  169. self.writer = SummaryWriter(self.tb_path)
  170. self.last_model_path = os.path.join(self.wts_path, 'last.pth')
  171. self.best_train_model_path = os.path.join(self.wts_path, 'best_train.pth')
  172. self.best_val_model_path = os.path.join(self.wts_path, 'best_val.pth')
  173. self.max_epoch = kwargs['train_params']['max_epoch']
  174. self.augmentation= kwargs['train_params']["augmentation"]
  175. def move_to_device(self, data, device):
  176. if isinstance(data, (list, tuple)):
  177. return type(data)(self.move_to_device(item, device) for item in data)
  178. elif isinstance(data, dict):
  179. return {key: self.move_to_device(value, device) for key, value in data.items()}
  180. elif isinstance(data, torch.Tensor):
  181. return data.to(device)
  182. else:
  183. return data # 对于非张量类型的数据不做任何改变
  184. def freeze_params(self, model):
  185. """根据配置冻结模型参数"""
  186. default_config = {
  187. 'backbone': True, # 冻结 backbone
  188. 'rpn': False, # 不冻结 rpn
  189. 'roi_heads': {
  190. 'box_head': False,
  191. 'box_predictor': False,
  192. 'line_head': False,
  193. 'line_predictor': {
  194. 'fc1': False,
  195. 'fc2': {
  196. '0': False,
  197. '2': False,
  198. '4': False
  199. }
  200. }
  201. }
  202. }
  203. # 更新默认配置
  204. default_config.update(self.freeze_config)
  205. config = default_config
  206. print("\n===== Parameter Freezing Configuration =====")
  207. for name, module in model.named_children():
  208. if name in config:
  209. if isinstance(config[name], bool):
  210. for param in module.parameters():
  211. param.requires_grad = not config[name]
  212. print(f"{'Frozen' if config[name] else 'Trainable'} module: {name}")
  213. elif isinstance(config[name], dict):
  214. for subname, submodule in module.named_children():
  215. if subname in config[name]:
  216. if isinstance(config[name][subname], bool):
  217. for param in submodule.parameters():
  218. param.requires_grad = not config[name][subname]
  219. print(
  220. f"{'Frozen' if config[name][subname] else 'Trainable'} submodule: {name}.{subname}")
  221. elif isinstance(config[name][subname], dict):
  222. for subsubname, subsubmodule in submodule.named_children():
  223. if subsubname in config[name][subname]:
  224. for param in subsubmodule.parameters():
  225. param.requires_grad = not config[name][subname][subsubname]
  226. print(
  227. f"{'Frozen' if config[name][subname][subsubname] else 'Trainable'} sub-submodule: {name}.{subname}.{subsubname}")
  228. # 打印参数统计
  229. total_params = sum(p.numel() for p in model.parameters())
  230. trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
  231. print(f"\nTotal Parameters: {total_params:,}")
  232. print(f"Trainable Parameters: {trainable_params:,}")
  233. print(f"Frozen Parameters: {total_params - trainable_params:,}")
  234. def load_best_model(self, model, optimizer, save_path, device):
  235. if os.path.exists(save_path):
  236. checkpoint = torch.load(save_path, map_location=device)
  237. model.load_state_dict(checkpoint['model_state_dict'])
  238. if optimizer is not None:
  239. optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
  240. epoch = checkpoint['epoch']
  241. loss = checkpoint['loss']
  242. print(f"Loaded best model from {save_path} at epoch {epoch} with loss {loss:.4f}")
  243. else:
  244. print(f"No saved model found at {save_path}")
  245. return model, optimizer
  246. def writer_predict_result(self, img, result, epoch,):
  247. img = img.cpu().detach()
  248. im = img.permute(1, 2, 0) # [512, 512, 3]
  249. self.writer.add_image("z-ori", im, epoch, dataformats="HWC")
  250. boxed_image = draw_bounding_boxes((img * 255).to(torch.uint8), result["boxes"],
  251. colors="yellow", width=1)
  252. # plt.imshow(boxed_image.permute(1, 2, 0).detach().cpu().numpy())
  253. # plt.show()
  254. self.writer.add_image("z-obj", boxed_image.permute(1, 2, 0), epoch, dataformats="HWC")
  255. if 'points' in result:
  256. keypoint_img = draw_keypoints(boxed_image, result['points'], colors='red', width=3)
  257. self.writer.add_image("z-output", keypoint_img, epoch)
  258. # print("lines shape:", result['lines'].shape)
  259. if 'lines' in result:
  260. # 用自己写的函数画线段
  261. # line_image = draw_lines(boxed_image, result['lines'], color='red', width=3)
  262. print(f"shape of linescore:{result['lines_scores'].shape}")
  263. scores = result['lines_scores'].mean(dim=1) # shape: [31]
  264. line_image = draw_lines_with_scores((img * 255).to(torch.uint8), result['lines'],scores, width=3, cmap='jet')
  265. self.writer.add_image("z-output_line", line_image.permute(1, 2, 0), epoch, dataformats="HWC")
  266. if 'arcs' in result:
  267. arcs = result['arcs'][0]
  268. # img_rgb = cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
  269. # img_tensor =torch.tensor(img_rgb)
  270. # img_tensor = np.transpose(img_tensor)
  271. self.writer.add_image('z-out-arc', arcs, global_step=epoch)
  272. if 'ins_masks' in result:
  273. # points=result['circles']
  274. # points=points.squeeze(1)
  275. ppp=result['ins_masks']
  276. bbb=result['boxes']
  277. print(f'boxes shape:{bbb.shape}')
  278. print(f'ppp:{ppp.shape}')
  279. ins_masks = result['ins_masks']
  280. ins_masks = ins_masks.squeeze(1)
  281. print(f'ins_masks shape:{ins_masks.shape}')
  282. features = result['features']
  283. circle_image = img.cpu().numpy().transpose((1, 2, 0)) # CHW -> HWC
  284. circle_image = (circle_image * 255).clip(0, 255).astype(np.uint8)
  285. sum_mask = ins_masks.sum(dim=0, keepdim=True)
  286. sum_mask = sum_mask / (sum_mask.max() + 1e-8)
  287. # keypoint_img = draw_keypoints((img * 255).to(torch.uint8), points, colors='red', width=3)
  288. self.writer.add_image('z-ins-masks', sum_mask.squeeze(0), global_step=epoch)
  289. result_imgs = draw_ellipses_on_image(img, ins_masks, threshold=0.5)
  290. self.writer.add_image('z-out-ellipses', result_imgs, dataformats='HWC', global_step= epoch)
  291. features=self.apply_gaussian_blur_to_tensor(features,sigma=3)
  292. self.writer.add_image('z-feature', features, global_step=epoch)
  293. # cv2.imshow('arc', img_rgb)
  294. # cv2.waitKey(1000000)
  295. def normalize_tensor(self,tensor):
  296. """Normalize tensor to [0, 1]"""
  297. min_val = tensor.min()
  298. max_val = tensor.max()
  299. return (tensor - min_val) / (max_val - min_val)
  300. def apply_gaussian_blur_to_tensor(self,feature_map, sigma=3):
  301. """
  302. Apply Gaussian blur to a feature map and convert it into an RGB heatmap.
  303. :param feature_map: Tensor of shape (H, W) or (1, H, W)
  304. :param sigma: Standard deviation for Gaussian kernel
  305. :return: Tensor of shape (3, H, W) representing the RGB heatmap
  306. """
  307. if feature_map.dim() == 3:
  308. if feature_map.shape[0] != 1:
  309. raise ValueError("Only single-channel feature map supported.")
  310. feature_map = feature_map.squeeze(0)
  311. # Normalize to [0, 1]
  312. normalized_feat = self.normalize_tensor(feature_map).cpu().numpy()
  313. # Apply Gaussian blur
  314. blurred_feat = gaussian_filter(normalized_feat, sigma=sigma)
  315. # Convert to colormap (e.g., 'jet')
  316. colormap = plt.get_cmap('jet')
  317. colored = colormap(blurred_feat) # shape: (H, W, 4) RGBA
  318. # Convert to (3, H, W), drop alpha channel
  319. colored_rgb = colored[:, :, :3] # (H, W, 3)
  320. colored_tensor = torch.from_numpy(colored_rgb).permute(2, 0, 1) # (3, H, W)
  321. return colored_tensor.float()
  322. def writer_loss(self, losses, epoch, phase='train'):
  323. try:
  324. for key, value in losses.items():
  325. if key == 'loss_wirepoint':
  326. for subdict in losses['loss_wirepoint']['losses']:
  327. for subkey, subvalue in subdict.items():
  328. self.writer.add_scalar(f'{phase}/loss/{subkey}',
  329. subvalue.item() if hasattr(subvalue, 'item') else subvalue,
  330. epoch)
  331. elif isinstance(value, torch.Tensor):
  332. self.writer.add_scalar(f'{phase}/loss/{key}', value.item(), epoch)
  333. except Exception as e:
  334. print(f"TensorBoard logging error: {e}")
  335. def train_from_cfg(self, model: BaseModel, cfg, freeze_config=None): # 新增:支持传入冻结配置
  336. cfg = read_yaml(cfg)
  337. # print(f'cfg:{cfg}')
  338. # self.freeze_config = freeze_config or {} # 更新冻结配置
  339. self.train(model, **cfg)
  340. def train(self, model, **kwargs):
  341. self.init_params(**kwargs)
  342. dataset_train = LineDataset(dataset_path=self.dataset_path,augmentation=self.augmentation, data_type=self.data_type, dataset_type='train')
  343. dataset_val = LineDataset(dataset_path=self.dataset_path,augmentation=self.augmentation, data_type=self.data_type, dataset_type='val')
  344. train_sampler = torch.utils.data.RandomSampler(dataset_train)
  345. val_sampler = torch.utils.data.RandomSampler(dataset_val)
  346. train_batch_sampler = torch.utils.data.BatchSampler(train_sampler, batch_size=self.batch_size, drop_last=True)
  347. val_batch_sampler = torch.utils.data.BatchSampler(val_sampler, batch_size=self.batch_size, drop_last=True)
  348. train_collate_fn = utils.collate_fn
  349. val_collate_fn = utils.collate_fn
  350. data_loader_train = torch.utils.data.DataLoader(
  351. dataset_train, batch_sampler=train_batch_sampler, num_workers=self.num_workers, collate_fn=train_collate_fn
  352. )
  353. data_loader_val = torch.utils.data.DataLoader(
  354. dataset_val, batch_sampler=val_batch_sampler, num_workers=self.num_workers, collate_fn=val_collate_fn
  355. )
  356. model.to(device)
  357. optimizer = torch.optim.Adam(
  358. filter(lambda p: p.requires_grad, model.parameters()),
  359. lr=kwargs['train_params']['optim']['lr'],
  360. weight_decay=kwargs['train_params']['optim']['weight_decay'],
  361. )
  362. model, optimizer = self.load_best_model(model, optimizer,
  363. r"\\192.168.50.222\share\rlq\weights\250725_arc_res152_best_val.pth",
  364. device)
  365. # scheduler = StepLR(optimizer, step_size=10, gamma=0.1)
  366. scheduler = ReduceLROnPlateau(optimizer, 'min', patience=30)
  367. for epoch in range(self.max_epoch):
  368. print(f"train epoch:{epoch}")
  369. model, epoch_train_loss = self.one_epoch(model, data_loader_train, epoch, optimizer)
  370. scheduler.step(epoch_train_loss)
  371. # ========== Validation ==========
  372. with torch.no_grad():
  373. model, epoch_val_loss = self.one_epoch(model, data_loader_val, epoch, optimizer, phase='val')
  374. scheduler.step(epoch_val_loss)
  375. if epoch==0:
  376. best_train_loss = epoch_train_loss
  377. best_val_loss = epoch_val_loss
  378. self.save_last_model(model,self.last_model_path, epoch, optimizer)
  379. best_train_loss = self.save_best_model(model, self.best_train_model_path, epoch, epoch_train_loss,
  380. best_train_loss,
  381. optimizer)
  382. best_val_loss = self.save_best_model(model, self.best_val_model_path, epoch, epoch_val_loss, best_val_loss,
  383. optimizer)
  384. def one_epoch(self, model, data_loader, epoch, optimizer, phase='train'):
  385. if phase == 'train':
  386. model.train()
  387. if phase == 'val':
  388. model.eval()
  389. total_loss = 0
  390. epoch_step = 0
  391. global_step = epoch * len(data_loader)
  392. for imgs, targets in data_loader:
  393. imgs = self.move_to_device(imgs, device)
  394. targets = self.move_to_device(targets, device)
  395. if phase== 'val':
  396. result,loss_dict = model(imgs, targets)
  397. losses = sum(loss_dict.values())
  398. print(f'val losses:{losses}')
  399. # print(f'val result:{result}')
  400. else:
  401. loss_dict = model(imgs, targets)
  402. losses = sum(loss_dict.values())
  403. print(f'train losses:{losses}')
  404. # loss = _loss(losses)
  405. loss=losses
  406. total_loss += loss.item()
  407. if phase == 'train':
  408. optimizer.zero_grad()
  409. loss.backward()
  410. optimizer.step()
  411. self.writer_loss(loss_dict, global_step, phase=phase)
  412. global_step += 1
  413. if epoch_step == 0 and phase == 'val':
  414. t_start = time.time()
  415. print(f'start to predict:{t_start}')
  416. result = model(self.move_to_device(imgs, self.device))
  417. # print(f'result:{result}')
  418. t_end = time.time()
  419. print(f'predict used:{t_end - t_start}')
  420. self.writer_predict_result(img=imgs[0], result=result[0], epoch=epoch)
  421. epoch_step+=1
  422. avg_loss = total_loss / len(data_loader)
  423. print(f'{phase}/loss epoch{epoch}:{avg_loss:4f}')
  424. self.writer.add_scalar(f'loss/{phase}', avg_loss, epoch)
  425. return model, avg_loss
  426. def save_best_model(self, model, save_path, epoch, current_loss, best_loss, optimizer=None):
  427. os.makedirs(os.path.dirname(save_path), exist_ok=True)
  428. if current_loss <= best_loss:
  429. checkpoint = {
  430. 'epoch': epoch,
  431. 'model_state_dict': model.state_dict(),
  432. 'loss': current_loss
  433. }
  434. if optimizer is not None:
  435. checkpoint['optimizer_state_dict'] = optimizer.state_dict()
  436. torch.save(checkpoint, save_path)
  437. print(f"Saved best model at epoch {epoch} with loss {current_loss:.4f}")
  438. return current_loss
  439. return best_loss
  440. def save_last_model(self, model, save_path, epoch, optimizer=None):
  441. if os.path.exists(f'{self.wts_path}/last.pt'):
  442. os.remove(f'{self.wts_path}/last.pt')
  443. os.makedirs(os.path.dirname(save_path), exist_ok=True)
  444. checkpoint = {
  445. 'epoch': epoch,
  446. 'model_state_dict': model.state_dict(),
  447. }
  448. if optimizer is not None:
  449. checkpoint['optimizer_state_dict'] = optimizer.state_dict()
  450. torch.save(checkpoint, save_path)
  451. if __name__ == '__main__':
  452. print('')