栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

libtorch调试——如何保存libtorch生成的张量并在python中加载

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

libtorch调试——如何保存libtorch生成的张量并在python中加载

C++ --> Python

c++保存

#include 

#include 
#include 

int main() {
  auto x = torch::ones({3, 3});
  auto bytes = torch::jit::pickle_save(x);
  std::ofstream fout("x.zip", std::ios::out | std::ios::binary);
  fout.write(bytes.data(), bytes.size());
  fout.close();
  return 0;
}

python加载

import torch
torch.load("x.zip")
Python --> C++

python保存

import io

import torch


def save_tensor(device):
    my_tensor = torch.rand(3, 3).to(device);
    print("[python] my_tensor: ", my_tensor)
    f = io.BytesIO()
    torch.save(my_tensor, f, _use_new_zipfile_serialization=True)
    with open('my_tensor_%s.pt' % device, "wb") as out_f:
        # Copy the BytesIO stream to the output file
        out_f.write(f.getbuffer())


if __name__ == '__main__':
    save_tensor('cpu')

c++加载

#include 
#include 

std::vector get_the_bytes(std::string filename) {
    std::ifstream input(filename, std::ios::binary);
    std::vector bytes(
        (std::istreambuf_iterator(input)),
        (std::istreambuf_iterator()));

    input.close();
    return bytes;
}

int main()
{
    std::vector f = get_the_bytes("my_tensor_cpu.pt");
    torch::IValue x = torch::pickle_load(f);
    torch::Tensor my_tensor = x.toTensor();
    std::cout << "[cpp] my_tensor: " << my_tensor << std::endl;

    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1030458.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号