pytorch 模型保存与加载 cpu转GPU

Posted sereasuesue

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pytorch 模型保存与加载 cpu转GPU相关的知识,希望对你有一定的参考价值。

model.eval() 的重要性,在2)中最后用到了model.eval(),是因为,只有在执行该命令后,"dropout层"及"batch normalization层"才会进入 evalution 模态. 而在"训练(training)模态"与"评估(evalution)模态"下,这两层有不同的表现形式.

模态字典(state_dict)的保存(model是一个网络结构类的对象)

1.1)仅保存学习到的参数,用以下命令

    torch.save(model.state_dict(), PATH)

1.2)加载model.state_dict,用以下命令

    model = TheModelClass(*args, **kwargs)
    model.load_state_dict(torch.load(PATH))
    model.eval()

    备注:model.load_state_dict的操作对象是 一个具体的对象,而不能是文件名

2.1)保存整个model的状态,用以下命令

    torch.save(model,PATH)

2.2)加载整个model的状态,用以下命令:

          # Model class must be defined somewhere

    model = torch.load(PATH)

    model.eval()

state_dict 是一个python的字典格式,以字典的格式存储,然后以字典的格式被加载,而且只加载key匹配的项

如何仅加载某一层的训练的到的参数(某一层的state)

If you want to load parameters from one layer to another, but some keys do not match, simply change the name of the parameter keys in the state_dict that you are loading to match the keys in the model that you are loading into.

conv1_weight_state = torch.load('./model_state_dict.pt')['conv1.weight']

 CPU转GPU记录

1.查看可用设备是GPU还是CPU

将模型传入GPU

    device1 = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model = RNN()
    print(device1)
    print(model)
    model.to(device1)

2.          criterion = nn.BCEWithLogitsLoss()
            criterion.to(device)

3.将传入的模型参数放入GPU

待完善

以上是关于pytorch 模型保存与加载 cpu转GPU的主要内容,如果未能解决你的问题,请参考以下文章

[深度学习] Pytorch—— 多/单GPUCPU,训练保存加载模型参数问题

[Pytorch]Pytorch 保存模型与加载模型(转)

保存和加载 Pytorch 模型检查点以进行推理不起作用

如何将经过 gpu 训练的模型加载到 cpu 中?

PyTorch笔记: GPU上训练的模型加载到CPU/错误处理Attempting to deserialize object on a CUDA device but torch.cuda.is_a

使用 cpu 与 gpu 进行训练的 pytorch 模型精度之间的巨大差异