pytorch/test/custom_backend/test_custom_backend.cpp
Meghan Lele e2a291b396 [JIT] Add out-of-source-tree to_backend tests (#40842)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/40842

**Summary**
This commit adds out-of-source-tree tests for `to_backend`. These tests check
that a Module can be lowered to a backend, exported, loaded (in both
Python and C++) and executed.

**Fixes**
This commit fixes #40067.

Test Plan: Imported from OSS

Differential Revision: D22418731

Pulled By: SplitInfinity

fbshipit-source-id: 621ba4efc1b121fa76c9c7ca377792ac7440d250
2020-07-07 21:00:43 -07:00

40 lines
1.3 KiB
C++

#include <torch/cuda.h>
#include <torch/script.h>
#include <string>
#include "custom_backend.h"
// Load a module lowered for the custom backend from \p path and test that
// it can be executed and produces correct results.
void load_serialized_lowered_module_and_execute(const std::string& path) {
torch::jit::Module module = torch::jit::load(path);
// The custom backend is hardcoded to compute f(a, b) = (a + b, a - b).
auto tensor = torch::ones(5);
std::vector<torch::jit::IValue> inputs{tensor, tensor};
auto output = module.forward(inputs);
AT_ASSERT(output.isTuple());
auto output_elements = output.toTuple()->elements();
for (auto& e : output_elements) {
AT_ASSERT(e.isTensor());
}
AT_ASSERT(output_elements.size(), 2);
AT_ASSERT(output_elements[0].toTensor().allclose(tensor + tensor));
AT_ASSERT(output_elements[1].toTensor().allclose(tensor - tensor));
}
int main(int argc, const char* argv[]) {
if (argc != 2) {
std::cerr
<< "usage: test_custom_backend <path-to-exported-script-module>\n";
return -1;
}
const std::string path_to_exported_script_module = argv[1];
std::cout << "Testing " << torch::custom_backend::getBackendName() << "\n";
load_serialized_lowered_module_and_execute(path_to_exported_script_module);
std::cout << "OK\n";
return 0;
}