|
NPU部门回复:
pytorch模型必须继承自torch.nn.Module,1个fc层的pytorch示例可以参考test.py:
- import torch
- from rknn.api import RKNN
- import numpy as np
- def export_pytorch_model():
- class MyNet(torch.nn.Module):
- def __init__(self):
- super(MyNet, self).__init__()
- self.fc = torch.nn.Linear(224*224, 10)
- def forward(self, x):
- x = x.view(1,-1)
- return self.fc(x)
- net = MyNet()
- dummy_input = torch.randn([1, 1, 224, 224])
- trace_model = torch.jit.trace(net, dummy_input)
- pt_save_path = './test.pt'
- trace_model.save(pt_save_path)
- return pt_save_path
- if __name__ == '__main__':
- pt_model = export_pytorch_model()
- input_size_list = [[1, 224, 224]]
- # Create RKNN object
- rknn = RKNN()
- # pre-process config
- print('--> config model')
- rknn.config(channel_mean_value='0 1', reorder_channel='0 1 2')
- print('done')
- # Load pytorch model
- print('--> Loading model')
- ret = rknn.load_pytorch(model=pt_model, input_size_list=input_size_list)
- if ret != 0:
- print('Load pytorch model failed!')
- exit(ret)
- print('done')
- # Build model
- print('--> Building model')
- ret = rknn.build(do_quantization=False, dataset='./dataset.txt')
- if ret != 0:
- print('Build pytorch failed!')
- exit(ret)
- print('done')
- # Set inputs
- img = np.random.randn(224,224,1).astype(np.float32)
- # init runtime environment
- print('--> Init runtime environment')
- ret = rknn.init_runtime()
- if ret != 0:
- print('Init runtime environment failed')
- exit(ret)
- print('done')
- # Inference
- print('--> Running model')
- outputs = rknn.inference(inputs=[img])
- print('rknn output:')
- print(outputs[0])
- # pytorch inference
- pt_i = np.expand_dims(img, axis=0)
- pt_i = np.transpose(pt_i, [0,3,1,2])
- pt_i = torch.from_numpy(pt_i)
- model = torch.jit.load(pt_model)
- pt_o = model(pt_i).detach().numpy()
- print('pytorch output:')
- print(pt_o)
|
|