错误1:

error: OpenCV(4.10.0) :-1: error: (-5:Bad argument) in function 'warpAffine'
> Overload resolution failed:
>  - Can't parse 'dsize'. Sequence item with index 0 has a wrong type
>  - Can't parse 'dsize'. Sequence item with index 0 has a wrong type

torch类型 不能直接放入openCV操作,必须转成numpy

错误2:

torch模型推理时,报错StopIteration 异常,具体是在调用 next(self.parameters()) 时触发的

因为在 torch 中,self.parameters() 是一个生成器,用于迭代模型中的所有可训练参数

需要:

我们不训练,需要用 with torch.no_grad(): 或者@torch.no_grad() 包装一下 

错误3:

  File "/home/gmq/project/gmq_env/lib/python3.8/site-packages/torch/nn/parallel/scatter_gather.py", line 100, in gather_map
    return type(out)(map(gather_map, zip(*outputs)))
TypeError: 'float' object is not iterable

需要 执行 model.eval() 将所有层级的 model.training全部设为False

错误4:

模型推理错误,完全失效

在使用 strict=False 加载模型权重时,虽然允许部分键不匹配,不会报错缺乏匹配的参数key

模型是分布式训练的,使用了nn.DataParallel(model) 来包裹模型,然后直接保存的模型。

在model.load_state_dict(, strict=False)会因为不匹配参数key,导致无法加载,从而模型推理完全错误。

需要去除参数key的module.前缀:

# 1. 在加载模型时指定 map_location 为 cpu
checkpoint = torch.load('exp/OCID-VLG_multiple/CROG_multiple_R50/best_iou_model.pth', map_location=torch.device('cpu'))
# 2. 去除 DataParallel 包装添加的 "module." 前缀
state_dict = checkpoint['state_dict']
if list(state_dict.keys())[0].startswith('module.'):
    state_dict = {k[7:]: v for k, v in state_dict.items()}
# 3. 加载模型权重
model.load_state_dict(state_dict, strict=True)

Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐