Last active
August 27, 2018 08:14
-
-
Save dnlcrl/5679d340703cc09583158383ea87a22a to your computer and use it in GitHub Desktop.
PyTorch Model Export (Python) Import (Python, C++) Snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
import torch.nn as nn | |
class Model(nn.Module): | |
def __init__(self): | |
super(Model, self).__init__() | |
self.linear = nn.Linear(1,1) | |
def forward(self, x): | |
y = self.linear(x) | |
return y | |
x = torch.zeros(1) | |
model = Model() | |
module = torch.jit.trace(x)(model) | |
module.save('trace.pt') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "torch/csrc/jit/import.h" | |
#include <ATen/ATen.h> | |
using namespace torch; | |
int main(int argc, char const *argv[]) | |
{ | |
std::shared_ptr<jit::script::Module> module = jit::load("trace.pt"); | |
at::Tensor x = at::zeros({1}); | |
jit::Stack stack; | |
stack.push_back(autograd::make_variable(x)); | |
module->get_method("forward").run(stack); | |
at::Tensor y = torch::autograd::Variable(stack[0].toTensor()).data(); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
module = torch.jit.load('trace.pt') | |
x = torch.zeros(1) | |
with torch.no_grad(): | |
y = module(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fixed ;)