File: predictor.cpp

package info (click to toggle)
pytorch 1.13.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 139,252 kB
  • sloc: cpp: 1,100,274; python: 706,454; ansic: 83,052; asm: 7,618; java: 3,273; sh: 2,841; javascript: 612; makefile: 323; xml: 269; ruby: 185; yacc: 144; objc: 68; lex: 44
file content (48 lines) | stat: -rw-r--r-- 1,296 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// This is a simple predictor binary that loads a TorchScript CV model and runs
// a forward pass with fixed input `torch::ones({1, 3, 224, 224})`.
// It's used for end-to-end integration test for custom mobile build.

#include <iostream>
#include <string>
#include <c10/util/irange.h>
#include <torch/script.h>

using namespace std;

namespace {

struct MobileCallGuard {
  // Set InferenceMode for inference only use case.
  c10::InferenceMode guard;
  // Disable graph optimizer to ensure list of unused ops are not changed for
  // custom mobile build.
  torch::jit::GraphOptimizerEnabledGuard no_optimizer_guard{false};
};

torch::jit::Module loadModel(const std::string& path) {
  MobileCallGuard guard;
  auto module = torch::jit::load(path);
  module.eval();
  return module;
}

} // namespace

int main(int argc, const char* argv[]) {
  if (argc < 2) {
    std::cerr << "Usage: " << argv[0] << " <model_path>\n";
    return 1;
  }
  auto module = loadModel(argv[1]);
  auto input = torch::ones({1, 3, 224, 224});
  auto output = [&]() {
    MobileCallGuard guard;
    return module.forward({input}).toTensor();
  }();

  std::cout << std::setprecision(3) << std::fixed;
  for (const auto i : c10::irange(5)) {
    std::cout << output.data_ptr<float>()[i] << std::endl;
  }
  return 0;
}