加载模型出现 RuntimeError: Error(s) in loading state_dict for Model: Missing key(s) in state_dict

今天准备加载一个模型来测试的时候发现了一个问题,加载总是失败,报错是RuntimeError: Error(s) in loading state_dict for Model: Missing key(s) in state_dict "convd1.0.weight", "convd1.0.bias", "convd1.1.weight"  。咋一看,难道是因为我取值的问题,然后debug了一下,发现我的state_dict是符合要求的,但是为什么出现加载不了?

问题代码

    model = m.Model()
    checkpoint = torch.load("ckpts/cdnn/model.tar",map_location='cpu')
    state_dict  = checkpoint['state_dict']
    # print(state_dict)
    model.load_state_dict(state_dict)

问题的现象

原因  

加载使用模型时和训练模型时的环境不一致,这个模型是用GPU训练的,我本是使用的是CPU,所以会有些问题

解决办法

将load_state_dict(state_dict) 改成  model.load_state_dict(state_dict, False)

分析

 def load_state_dict(self, state_dict, strict=True):
        r"""Copies parameters and buffers from :attr:`state_dict` into
        this module and its descendants. If :attr:`strict` is ``True``, then
        the keys of :attr:`state_dict` must exactly match the keys returned
        by this module's :meth:`~torch.nn.Module.state_dict` function.

        Arguments:
            state_dict (dict): a dict containing parameters and
                persistent buffers.
            strict (bool, optional): whether to strictly enforce that the keys
                in :attr:`state_dict` match the keys returned by this module's
                :meth:`~torch.nn.Module.state_dict` function. Default: ``True``

上面是load_state_dict方法参数的官方说明 strict  参数默认是true,他的含义是 是否严格要求state_dict中的键与该模块的键返回的键匹配

这行代码生效的原理详见load_state_dict中的一段代码

        if strict:
            error_msg = ''
            if len(unexpected_keys) > 0:
                error_msgs.insert(
                    0, 'Unexpected key(s) in state_dict: {}. '.format(
                        ', '.join('"{}"'.format(k) for k in unexpected_keys)))
            if len(missing_keys) > 0:
                error_msgs.insert(
                    0, 'Missing key(s) in state_dict: {}. '.format(
                        ', '.join('"{}"'.format(k) for k in missing_keys)))

        if len(error_msgs) > 0:
            raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
                               self.__class__.__name__, "\n\t".join(error_msgs)))

就是说,如果strict 置为false那么就可以忽略掉报错,请注意是忽略哦!!!

看了这段代码后,我觉得一脸懵逼, 这个属性意思的理解是不是要让我们定义的Model中的键与我们加载模型里面的键严格一致,按理说,这个不是一定要严格一致的吗?不然不匹配乱加载那不是乱套了,但是很神奇的一件事情就是pytorch这个方法设计了一个开关,你可以选择关闭,忽略掉这个异常,不清楚这个是否会影响我们加载的模型的效果,我要验证下!

以上是我的胡乱猜想,望大神们批评指教!

猜你喜欢

转载自blog.csdn.net/binbinczsohu/article/details/107943806