Line data Source code
1 : /**
2 : * @file cfdnn_kernels_omp.c
3 : * @brief OpenMP backend for `.cfdnn` inference.
4 : *
5 : * Parallelises the SAMPLE axis only. That axis is not reduced -- each sample's
6 : * accumulation over input features is untouched and runs in the same ascending
7 : * order as the scalar reference -- so this backend is BIT-IDENTICAL to scalar,
8 : * and the cross-backend test asserts exact equality rather than a tolerance.
9 : * If that test ever fails it means someone parallelised a reduction axis,
10 : * which is precisely what it exists to catch.
11 : *
12 : * This file compiles with or without OpenMP. Without it the table exports a
13 : * NULL kernel, so the backend reports itself unavailable instead of quietly
14 : * running serial code under the name "omp" -- a silent cross-backend fallback
15 : * is exactly what the project's dispatch rules forbid. It must keep compiling
16 : * either way: cfdnn.c references cfd_nn_impl_omp unconditionally, so dropping
17 : * this translation unit from a no-OpenMP build would leave that symbol
18 : * undefined and fail the link for the whole library.
19 : */
20 :
21 : #include "../cfdnn_internal.h"
22 :
23 : #ifdef _OPENMP
24 : #include <omp.h>
25 : #endif
26 :
27 : #ifdef CFD_ENABLE_OPENMP
28 :
29 3 : static void dense_omp(const cfd_nn_layer_t* l, size_t batch, const float* in,
30 : float* out, float* scratch) {
31 3 : (void)scratch;
32 3 : const size_t ni = l->in_features;
33 3 : const size_t no = l->out_features;
34 :
35 : /* Signed loop variable declared outside the for-init: MSVC's OpenMP
36 : * rejects a declaration there (error C3015). Matches the idiom used by
37 : * the turbulence and boundary OMP kernels. */
38 3 : const int n = (int)batch;
39 3 : int s;
40 :
41 3 : #pragma omp parallel for schedule(static)
42 : for (s = 0; s < n; s++) {
43 : const float* x = in + (size_t)s * ni;
44 : float* y = out + (size_t)s * no;
45 : for (size_t o = 0; o < no; o++) {
46 : const float* w = l->weights + o * ni;
47 : float acc = l->bias ? l->bias[o] : 0.0f;
48 : for (size_t i = 0; i < ni; i++) {
49 : acc += x[i] * w[i];
50 : }
51 : y[o] = acc;
52 : }
53 : cfd_nn_apply_activation(l->activation, l->act_param, y, no);
54 : }
55 3 : }
56 :
57 : const cfd_nn_backend_impl_t cfd_nn_impl_omp = {
58 : "omp",
59 : dense_omp,
60 : 0,
61 : };
62 :
63 : #else /* !CFD_ENABLE_OPENMP */
64 :
65 : const cfd_nn_backend_impl_t cfd_nn_impl_omp = {
66 : "omp",
67 : NULL, /* unavailable: reported, never silently substituted */
68 : 0,
69 : };
70 :
71 : #endif /* CFD_ENABLE_OPENMP */
|