虚假的冻结层
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)
...