|
| 1 | +/* quickstart.cpp highlights some of the most basic concepts of `torch::deploy`. |
| 2 | +Specifically loading a pytorch model which was serialized by `torch.package` |
| 3 | +and running it. |
| 4 | +
|
| 5 | +In order to run this file, one needs to provide an archive produced by |
| 6 | +`torch.package`. The one used in our example is created by `gen_package.py` |
| 7 | +which produces my_package.pt. This program takes the path to the archive as |
| 8 | +an argument. |
| 9 | +*/ |
| 10 | + |
| 11 | +#include <multipy/runtime/deploy.h> |
| 12 | +#include <multipy/runtime/path_environment.h> |
| 13 | +#include <torch/script.h> |
| 14 | +#include <torch/torch.h> |
| 15 | + |
| 16 | +#include <iostream> |
| 17 | +#include <memory> |
| 18 | + |
| 19 | +int main(int argc, const char* argv[]) { |
| 20 | + if (argc != 2) { |
| 21 | + std::cerr << "usage: example-app <path-to-exported-script-module>\n"; |
| 22 | + return -1; |
| 23 | + } |
| 24 | + |
| 25 | + // Start an interpreter manager governing 4 embedded interpreters. |
| 26 | + torch::deploy::InterpreterManager manager(4); |
| 27 | + torch::deploy::ReplicatedObj model; |
| 28 | + try { |
| 29 | + // Load the model from the multipy.package. |
| 30 | + torch::deploy::Package package = manager.loadPackage(argv[1]); |
| 31 | + model = package.loadPickle("model", "model.pkl"); |
| 32 | + } catch (const c10::Error& e) { |
| 33 | + std::cerr << "error loading the model\n"; |
| 34 | + std::cerr << e.msg(); |
| 35 | + return -1; |
| 36 | + } |
| 37 | + |
| 38 | + // Create a vector of inputs. |
| 39 | + std::vector<torch::jit::IValue> inputs; |
| 40 | + inputs.push_back(torch::ones({1, 3, 224, 224})); |
| 41 | + |
| 42 | + // Execute the model and turn its output into a tensor. |
| 43 | + at::Tensor output = model(inputs).toTensor(); |
| 44 | + std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/5) << '\n'; |
| 45 | + |
| 46 | + std::cout << "ok\n"; |
| 47 | +} |
0 commit comments