model_get.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import os
  2. import torch
  3. choice_dict = {
  4. 'yolov7_cls': 'model_prepare(args).yolov7_cls()',
  5. # 'timm_model': 'model_prepare(args).timm_model()',
  6. 'Alexnet': 'model_prepare(args).Alexnet()',
  7. 'badnet': 'model_prepare(args).badnet()',
  8. 'GoogleNet': 'model_prepare(args).GoogleNet()',
  9. 'mobilenetv2': 'model_prepare(args).mobilenetv2()',
  10. 'resnet': 'model_prepare(args).resnet()',
  11. 'VGG19': 'model_prepare(args).VGG19()',
  12. 'efficientnet': 'model_prepare(args).EfficientNetV2_S()'
  13. }
  14. def model_get(args):
  15. if os.path.exists(args.weight): # 优先加载已有模型继续训练
  16. model_dict = torch.load(args.weight, map_location='cpu')
  17. else: # 新建模型
  18. if args.prune: # 模型剪枝
  19. model_dict = torch.load(args.prune_weight, map_location='cpu')
  20. model = model_dict['model']
  21. model = prune(args, model)
  22. elif args.timm:
  23. # model = model_prepare(args).timm_model()
  24. model = eval(choice_dict['timm_model'])
  25. else:
  26. model = eval(choice_dict[args.model])
  27. model_dict = {}
  28. model_dict['model'] = model
  29. model_dict['epoch_finished'] = 0 # 已训练的轮数
  30. model_dict['optimizer_state_dict'] = None # 学习率参数
  31. model_dict['ema_updates'] = 0 # ema参数
  32. model_dict['standard'] = 0 # 评价指标
  33. return model_dict
  34. def prune(args, model):
  35. # 记录BN层权重
  36. # Debugging output
  37. BatchNorm2d_weight = []
  38. for module in model.modules():
  39. if isinstance(module, torch.nn.BatchNorm2d):
  40. BatchNorm2d_weight.append(module.weight.data.clone())
  41. BatchNorm2d_weight_abs = torch.cat(BatchNorm2d_weight, dim=0).abs()
  42. weight_len = len(BatchNorm2d_weight)
  43. # 记录权重与BN层编号的关系
  44. BatchNorm2d_id = []
  45. for i in range(weight_len):
  46. BatchNorm2d_id.extend([i for _ in range(len(BatchNorm2d_weight[i]))])
  47. id_all = torch.tensor(BatchNorm2d_id)
  48. # 筛选
  49. value, index = torch.sort(BatchNorm2d_weight_abs, dim=0, descending=True)
  50. boundary = int(len(index) * args.prune_ratio)
  51. prune_index = index[0:boundary] # 保留参数的下标
  52. prune_index, _ = torch.sort(prune_index, dim=0, descending=False)
  53. prune_id = id_all[prune_index]
  54. # 将保留参数的下标放到每层中
  55. index_list = [[] for _ in range(weight_len)]
  56. for i in range(len(prune_index)):
  57. index_list[prune_id[i]].append(prune_index[i])
  58. # 将每层保留参数的下标换算成相对下标
  59. record_len = 0
  60. for i in range(weight_len):
  61. index_list[i] = torch.tensor(index_list[i])
  62. index_list[i] -= record_len
  63. if len(index_list[i]) == 0: # 存在整层都被减去的情况,至少保留一层
  64. index_list[i] = torch.argmax(BatchNorm2d_weight[i], dim=0).unsqueeze(0)
  65. record_len += len(BatchNorm2d_weight[i])
  66. # 创建剪枝后的模型
  67. args.prune_num = [len(_) for _ in index_list]
  68. prune_model = eval(choice_dict[args.model])
  69. # BN层权重赋值和部分conv权重赋值
  70. index = 0
  71. for module, prune_module in zip(model.modules(), prune_model.modules()):
  72. if isinstance(module, torch.nn.Conv2d): # 更新部分Conv2d层权重
  73. print(f"处理 Conv2d 层,索引:{index},权重形状:{module.weight.data.shape}")
  74. if index > 0 and index - 1 < len(index_list):
  75. # 打印 index_list 状态
  76. print(f"当前层前一层索引列表(index_list[{index - 1}]):{index_list[index - 1]}")
  77. # 检查是否索引越界
  78. if index_list[index - 1].max().item() < module.weight.data.shape[1]: # 检查最大索引是否小于输入通道数
  79. weight = module.weight.data.clone()
  80. if index < len(index_list):
  81. weight = weight[:, index_list[index - 1], :, :]
  82. if prune_module.weight.data.shape == weight.shape:
  83. prune_module.weight.data = weight
  84. else:
  85. print("索引越界,跳过当前层的处理")
  86. elif index == 0:
  87. weight = module.weight.data.clone()[index_list[index]]
  88. if prune_module.weight.data.shape == weight.shape:
  89. prune_module.weight.data = weight
  90. if isinstance(module, torch.nn.BatchNorm2d):
  91. print(f"更新 BatchNorm2d 层,索引:{index},权重形状:{module.weight.data.shape}")
  92. if index < len(index_list) and len(index_list[index]) > 0:
  93. expected_size = module.weight.data.size(0)
  94. actual_size = len(index_list[index])
  95. print(f"期望的大小:{expected_size}, 实际保留的大小:{actual_size}")
  96. if actual_size == expected_size:
  97. prune_module.weight.data = module.weight.data.clone()[index_list[index]]
  98. prune_module.bias.data = module.bias.data.clone()[index_list[index]]
  99. prune_module.running_mean = module.running_mean.clone()[index_list[index]]
  100. prune_module.running_var = module.running_var.clone()[index_list[index]]
  101. else:
  102. print("警告: 剪枝后的大小与期望的 BatchNorm2d 层大小不匹配")
  103. index += 1
  104. return prune_model
  105. class model_prepare:
  106. def __init__(self, args):
  107. self.args = args
  108. # def timm_model(self):
  109. # from model.timm_model import timm_model
  110. # model = timm_model(self.args)
  111. # return model
  112. def yolov7_cls(self):
  113. from model.yolov7_cls import yolov7_cls
  114. model = yolov7_cls(self.args)
  115. return model
  116. def Alexnet(self):
  117. from model.Alexnet import Alexnet
  118. model = Alexnet(self.args.input_channels, self.args.output_num, self.args.input_size)
  119. return model
  120. def badnet(self):
  121. from model.badnet import BadNet
  122. model = BadNet(self.args.input_channels, self.args.output_num)
  123. return model
  124. def GoogleNet(self):
  125. from model.GoogleNet import GoogLeNet
  126. model = GoogLeNet(self.args.input_channels, self.args.output_num)
  127. return model
  128. def mobilenetv2(self):
  129. from model.mobilenetv2 import MobileNetV2
  130. model = MobileNetV2(self.args.input_channels, self.args.output_num)
  131. return model
  132. def resnet(self):
  133. from model.resnet import ResNet18
  134. model = ResNet18(self.args.input_channels, self.args.output_num)
  135. return model
  136. def VGG19(self):
  137. from model.VGG19 import VGG19
  138. model = VGG19()
  139. return model
  140. def EfficientNetV2_S(self):
  141. from model.efficientnet import EfficientNetV2_S
  142. model = EfficientNetV2_S(self.args.input_channels, self.args.output_num)
  143. return model