YOLOv8冻结层的迁移学习 全网首发

虚假的冻结层

from ultralytics import YOLO

model = YOLO('yolov8x.pt')
data = '/home/tm/fyjx/FangTeDatasets/Datasets/data.yaml'

# for k, v in model.model.named_parameters():
#     print(k)
freeze = 10
freeze = [f'model.{x}.' for x in range(freeze)]  # layers to freeze
for k, v in model.model.named_parameters():
    v.requires_grad = True  # train all layers
    if any(x in k for x in freeze):
        print(f'freezing {k}')
        v.requires_grad = False

model.train(data = data, epochs = 50, batch = 8, save = True, device = 4)

model.train在调用时会创建trainer类,请看vcr:

self.trainer.model = self.trainer.get_model(weights=self.model if self.ckpt else None, cfg=self.model.yaml)

此时的模型配置更新了,冻结了个p

真正的冻结层

YOLO 提供了丰富的回调函数, 我们在创建trainer后冻结层, 在训练程序开始时调用函数冻结真正的model, 那就是trainer.model

from ultralytics import YOLO

model = YOLO('yolov8x.pt')
data = '/app/Datasets/data.yaml'

def freeze_model(trainer):
    # Retrieve the batch data
    model = trainer.model
    print('Befor Freeze')
    for k, v in model.named_parameters():
        print('\t', k,'\t', v.requires_grad)
        
        
    freeze = 10
    freeze = [f'model.{x}.' for x in range(freeze)]  # layers to freeze
    for k, v in model.named_parameters():
        v.requires_grad = True  # train all layers
        if any(x in k for x in freeze):
            print(f'freezing {k}')
            v.requires_grad = False
    print('After Freeze')
    for k, v in model.named_parameters():
        print('\t', k,'\t', v.requires_grad)
        

model.add_callback("on_pretrain_routine_start", freeze_model)

model.train(data = data, epochs = 50, batch = 32, save = True)


多卡训练时报错

RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing loss. You can enable unused parameter detection by passing the keyword argument `find_unused_parameters=True` to `torch.nn.parallel.DistributedDataParallel`, and by
making sure all `forward` function outputs participate in calculating loss.
If you already have done the above, then the distributed data parallel module wasn't able to locate the output tensors in the return value of your module's `forward` function. Please include the loss function and the structure of the return value of `forward` of your module when reporting this issue (e.g. list, dict, iterable).
Parameter indices which did not receive grad for rank 1: 102
 In addition, you can set the environment variable TORCH_DISTRIBUTED_DEBUG to either INFO or DETAIL to print out information about which particular parameters did not receive gradient on this rank as part of this error

表示无法获取所有层的 loss 梯度

修改文件: ultralytics/yolo/engine/trainer.py

添加 find_unused_parameters=True

	def _setup_train(self, world_size):
        """
        Builds dataloaders and optimizer on correct rank process.
        """
       ...
        if world_size > 1:
            self.model = DDP(self.model, device_ids=[RANK], find_unused_parameters=True)
        ...
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值