tzdwindows_7 2024-01-20 16:03 采纳率: 50%
浏览 48
已结题

在Visual Studio 202中使用PyTorch(libtorch)库遇到save函数报错C2679

我Visual Studio 2022尝试使用PyTorch(libtorch)库中的torch::save(model, actual_model_path);保存模型
在编译过程中我的Visual Studio 2022一直提示我的save函数有错误(C2679)
save函数的代码:

template <typename Value, typename... SaveToArgs>
void save(const Value& value, SaveToArgs&&... args) {
  serialize::OutputArchive archive(std::make_shared<jit::CompilationUnit>());
  archive << value;
  archive.save_to(std::forward<SaveToArgs>(args)...);
}

我调用的函数

int trainModel(const torch::Tensor& mfcc, const std::string& model_path, int num_steps) {
/*.....*/
std::unique_ptr<Tacotron2> model = std::make_unique<Tacotron2>();
/*.....*/
    torch::save(model, actual_model_path);
    return 0;
}

我使用的平台是:Windows x64
开发平台: Visual Studio 2022
开发平台配置: Release x64
PyTorch(libtorch)的版本是:cudnn-windows-x86_64-8.9.7.29_cuda12-archive
具体错误信息

> 严重性    代码    说明    项目    文件    行    禁止显示状态
错误    C2679    二元“<<”: 没有找到接受“const Value”类型的右操作数的运算符(或没有可接受的转换)
        with
        [
            Value=std::unique_ptr<Tacotron2,std::default_delete<Tacotron2>>
        ]
  archive << value;
  ^    MeloClone    D:\libtorch\include\torch\csrc\api\include\torch\serialize.h    50    

我尝试过将torch::save(model, actual_model_path);修改为 torch::save(model, actual_model_path);的方法并不行
又尝试将std::unique_ptr model = std::make_unique();修改为Tacotron2
rawModel = new Tacotron2();也不行

  • 写回答

3条回答 默认 最新

  • tzdwindows_7 2024-01-22 14:54
    关注

    修改代码

    torch::save(model, actual_model_path);
    
    
    ```为
    ```c++
    try {
            torch::jit::script::Module jit_model;
    
            // 直接加载模型参数
            for (const auto& pair : model->named_parameters()) {
                jit_model.register_parameter(pair.key(), pair.value(), false);
            }
    
            // 保存模型
            jit_model.save(model_path);
        }
        catch (const c10::Error& e) {
            std::cerr << "Error saving the model: " << e.what() << std::endl;
            return 1;  // 返回错误代码
        }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 1月30日
  • 已采纳回答 1月22日
  • 创建了问题 1月20日