This C++ API example demonstrates the basics of the DNNL programming model.
#include <cmath>
#include <numeric>
#include <stdexcept>
#include <vector>
#include "example_utils.hpp"
const int N = 1, H = 13, W = 13, C = 3;
const int stride_N = H * W * C;
const int stride_H = W * C;
const int stride_W = C;
const int stride_C = 1;
auto offset = [=](int n, int h, int w, int c) {
return n * stride_N + h * stride_H + w * stride_W + c * stride_C;
};
const int image_size = N * H * W * C;
std::vector<float> image(image_size);
for (int n = 0; n < N; ++n)
for (int h = 0; h < H; ++h)
for (int w = 0; w < W; ++w)
for (int c = 0; c < C; ++c) {
int off = offset(
n, h, w, c);
image[off] = -std::cos(off / 10.f);
}
{N, C, H, W},
);
{N, C, H, W},
{stride_N, stride_C, stride_H, stride_W}
);
throw std::logic_error("Memory descriptor initialization mismatch.");
write_to_dnnl_memory(image.data(), src_mem);
0.f,
0.f
);
auto relu_pd
eng
);
relu.execute(engine_stream,
{
});
std::vector<float> relu_image(image_size);
read_from_dnnl_memory(relu_image.data(), dst_mem);
for (int n = 0; n < N; ++n)
for (int h = 0; h < H; ++h)
for (int w = 0; w < W; ++w)
for (int c = 0; c < C; ++c) {
int off = offset(
n, h, w, c);
float expected = image[off] < 0
? 0.f
: image[off];
if (relu_image[off] != expected) {
std::cout << "At index(" << n << ", " << c << ", " << h
<< ", " << w << ") expect " << expected
<< " but got " << relu_image[off]
<< std::endl;
throw std::logic_error("Accuracy check failed.");
}
}
}
int main(int argc, char **argv) {
int exit_code = 0;
try {
getting_started_tutorial(engine_kind);
std::cout << "DNNL error caught: " << std::endl
<<
"\tStatus: " << dnnl_status2str(e.
status) << std::endl
<<
"\tMessage: " << e.
what() << std::endl;
exit_code = 1;
} catch (std::string &e) {
std::cout << "Error in the example: " << e << "." << std::endl;
exit_code = 2;
}
std::cout << "Example " << (exit_code ? "failed" : "passed") << " on "
<< engine_kind2str_upper(engine_kind) << "." << std::endl;
return exit_code;
}