test_frcnn_tracing.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include <torch/script.h>
  2. #include <torch/torch.h>
  3. #include <torchvision/vision.h>
  4. #include <torchvision/ops/nms.h>
  5. int main() {
  6. torch::DeviceType device_type;
  7. device_type = torch::kCPU;
  8. torch::jit::script::Module module;
  9. try {
  10. std::cout << "Loading model\n";
  11. // Deserialize the ScriptModule from a file using torch::jit::load().
  12. module = torch::jit::load("fasterrcnn_resnet50_fpn.pt");
  13. std::cout << "Model loaded\n";
  14. } catch (const torch::Error& e) {
  15. std::cout << "error loading the model\n";
  16. return -1;
  17. } catch (const std::exception& e) {
  18. std::cout << "Other error: " << e.what() << "\n";
  19. return -1;
  20. }
  21. // TorchScript models require a List[IValue] as input
  22. std::vector<torch::jit::IValue> inputs;
  23. // Faster RCNN accepts a List[Tensor] as main input
  24. std::vector<torch::Tensor> images;
  25. images.push_back(torch::rand({3, 256, 275}));
  26. images.push_back(torch::rand({3, 256, 275}));
  27. inputs.push_back(images);
  28. auto output = module.forward(inputs);
  29. std::cout << "ok\n";
  30. std::cout << "output" << output << "\n";
  31. if (torch::cuda::is_available()) {
  32. // Move traced model to GPU
  33. module.to(torch::kCUDA);
  34. // Add GPU inputs
  35. images.clear();
  36. inputs.clear();
  37. torch::TensorOptions options = torch::TensorOptions{torch::kCUDA};
  38. images.push_back(torch::rand({3, 256, 275}, options));
  39. images.push_back(torch::rand({3, 256, 275}, options));
  40. inputs.push_back(images);
  41. auto output = module.forward(inputs);
  42. std::cout << "ok\n";
  43. std::cout << "output" << output << "\n";
  44. }
  45. return 0;
  46. }