Skip to content

Conversation

lancerstadium
Copy link

目的

腾讯开源课题实战:ncnn task1 (pnnx input npy files)
提交时间:2025/8/7
提交者:江南大学-鲁天硕

改动

  1. 添加依赖:引入npy.hpp头文件pnnx/src项目主文件夹;
  2. 添加pnnx::Graph::bind_operand接口:用于解析导入.npy文件数据,将其绑定到pnnx_graph的指定(名字name或索引index)operand上,具体数据保存在operand.params["__data__"]中(兼容结构体);
  3. 添加张量绑定过程:在main函数内,bindpnnx::pass_level2之前执行;
  4. 添加参数解析解析:在main函数内,添加参数input=a.npy,...的解析过程(复用parse_string_list接口);

接口

int Graph::bind_operand(const std::string& path, int index);
  • path: 需要解析的文件地址(解析模式{...}/${name}.{suffix},其中suffix可为npybin等等格式进行进一步拓展解析);
  • index: $index < 0$ 时,不强制匹配(没找到对应${name})。 $index >= 0$ 时,强制匹配对应的graph.operand[index]
  • return: -1解析报错,0其他。

测试

step1: 模型pt & 输入npy 生成

  • 执行并获得resnet18.pta.npy
import numpy as np
import torch
import torchvision.models as models

net = models.resnet18(pretrained=True)
net = net.eval()

x = torch.rand(1, 3, 224, 224)
mod = torch.jit.trace(net, x)
mod.save("resnet18.pt")

# export input to .npy
np.save("a.npy", x.detach().numpy())

step2: 测试改动功能

  • 执行正确验证command:
./build/src/pnnx ../../../playground/resnet18.pt input=../../../playground/a.npy
  • 得到输出:
############# pass_level1
bind_operand a to x.1 success
############# pass_level2
############# pass_level3
...
  • 执行多输入验证command:
./build/src/pnnx ../../../playground/resnet18.pt input=../../../playground/a.npy,b.npy
  • 得到输出:
############# pass_level1
bind_operand a to x.1 success
bind_operand failed to load b.npy: io error: failed to open a file.
############# pass_level2
############# pass_level3
...

Copy link

github-actions bot commented Aug 7, 2025

The binary size change of libncnn.so (bytes)

architecture base size pr size difference
x86_64 15648008 15648008 0 😘
armhf 6649020 6649020 0 😘
aarch64 9987736 9987736 0 😘

@nihui
Copy link
Member

nihui commented Aug 21, 2025

感谢你的工作,请将你在实现中的笔记和心得,遇到的困难和解决方法等,记录成文章,发表在discussion分区,这将作为知识总结 https://github.com/Tencent/ncnn/discussions

Thank you for your work. Please record your notes and experience in the implementation, difficulties encountered and solutions, etc. into an article and publish it in the discussion section. This will serve as a knowledge summary. https://github.com/Tencent/ncnn/discussions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants