pytorch写张量pt文件,libtorch读张量pt文件

++直接在pytorch中,用torch.save保存的张量,可能因格式差异无法在C++中加载。++

以下是一个最简单的例子,展示如何在 Pytorch中保存张量到 TorchScript 模块,并在 C++ 中使用 LibTorch 加载。

Python 代码 (save_tensor.py)

复制代码
import torch

# 定义一个简单的 TorchScript 模块来包装张量
class TensorWrapper(torch.jit.ScriptModule):
    def __init__(self, tensor):
        super().__init__()
        self.tensor = torch.jit.Attribute(tensor, torch.Tensor)

# 创建一个张量
tensor = torch.randn(2, 3)

# 包装张量到模块
module = TensorWrapper(tensor)

# 保存模块到文件
torch.jit.save(module, "tensor.pt")

C++ 代码 (load_tensor.cpp)

复制代码
#include <torch/script.h>
#include <iostream>

int main() {
    // 加载 TorchScript 模块
    torch::jit::script::Module module = torch::jit::load("tensor.pt");

    // 获取张量(假设我们知道属性名为 tensor)
    torch::Tensor tensor = module.attr("tensor").toTensor();

    // 打印张量
    std::cout << tensor << std::endl;

    return 0;
}

这种方法可靠,因为 TorchScript 提供了跨语言的序列化支持,保证张量数据一致性。

相关推荐
码农学院4 分钟前
AI优化AIO技术演进史:从模板生成到多智能体协同创作
人工智能
科技发布8 分钟前
拓氪科技 AI 内容引擎软文投放效果详解
人工智能·科技
nanawinona15 分钟前
2026年下半年量化学习,不同基础要查不同缺口
人工智能·python
海盗123420 分钟前
AI新闻日报_2026-07-22
人工智能
CTA量化套保31 分钟前
最新量化表达入门,从概念规则到简单实现
人工智能·python
AI应用苏大大33 分钟前
企业AI架构缺陷:低价工具堆叠,造成结构性效率浪费
人工智能
空中湖1 小时前
Spring AI Agent 编排:ReAct 模式 + 多 Agent 协作实战
人工智能·spring·react.js
only-qi1 小时前
RAG 工作机制详解:构建高质量知识库的技术全流程
网络·人工智能·rag
John_ToDebug1 小时前
Git Stash 完全指南:临时保存工作区的艺术
人工智能·git·agent
feibaoqq1 小时前
Atlas边端板卡AI识别:部署方法、技术实现、优劣及应用场景
人工智能·低空经济·低空安防