Caffe2 - C++ API
A deep learning, cross platform ML framework
init_omp.cc
1 #include <stdlib.h>
2 
3 #include "caffe2/core/common.h"
4 
5 #ifdef _OPENMP
6 #include "caffe2/core/common_omp.h"
7 #endif // _OPENMP
8 
9 #ifdef CAFFE2_USE_MKL
10 #include <mkl.h>
11 #endif // CAFFE2_USE_MKL
12 
13 #include "caffe2/core/init.h"
14 
15 CAFFE2_DEFINE_int(
16  caffe2_omp_num_threads, 0,
17  "The number of openmp threads. 0 to use default value. "
18  "Does not have effect if OpenMP is disabled.");
19 CAFFE2_DEFINE_int(
20  caffe2_mkl_num_threads,
21  0,
22  "The number of mkl threads. 0 to use default value. If set, "
23  "this overrides the caffe2_omp_num_threads flag if both are set. "
24  "Does not have effect if MKL is not used.");
25 
26 namespace caffe2 {
27 
28 #ifdef _OPENMP
29 bool Caffe2SetOpenMPThreads(int*, char***) {
30  if (!getenv("OMP_NUM_THREADS")) {
31  // OMP_NUM_THREADS not passed explicitly, so *disable* OMP by
32  // default. The user can use the CLI flag to override.
33  VLOG(1) << "OMP_NUM_THREADS not passed, defaulting to 1 thread";
34  omp_set_num_threads(1);
35  }
36 
37  if (FLAGS_caffe2_omp_num_threads > 0) {
38  VLOG(1) << "Setting omp_num_threads to " << FLAGS_caffe2_omp_num_threads;
39  omp_set_num_threads(FLAGS_caffe2_omp_num_threads);
40  }
41  VLOG(1) << "Caffe2 running with " << omp_get_max_threads() << " OMP threads";
42  return true;
43 }
44 REGISTER_CAFFE2_INIT_FUNCTION(Caffe2SetOpenMPThreads,
45  &Caffe2SetOpenMPThreads,
46  "Set OpenMP threads.");
47 #endif // _OPENMP
48 
49 #ifdef CAFFE2_USE_MKL
50 bool Caffe2SetMKLThreads(int*, char***) {
51  if (!getenv("MKL_NUM_THREADS")) {
52  VLOG(1) << "MKL_NUM_THREADS not passed, defaulting to 1 thread";
53  mkl_set_num_threads(1);
54  }
55 
56  // If caffe2_omp_num_threads is set, we use that for MKL as well.
57  if (FLAGS_caffe2_omp_num_threads > 0) {
58  VLOG(1) << "Setting mkl_num_threads to " << FLAGS_caffe2_omp_num_threads
59  << " as inherited from omp_num_threads.";
60  mkl_set_num_threads(FLAGS_caffe2_omp_num_threads);
61  }
62 
63  // Override omp_num_threads if mkl_num_threads is set.
64  if (FLAGS_caffe2_mkl_num_threads > 0) {
65  VLOG(1) << "Setting mkl_num_threads to " << FLAGS_caffe2_mkl_num_threads;
66  mkl_set_num_threads(FLAGS_caffe2_mkl_num_threads);
67  }
68  VLOG(1) << "Caffe2 running with " << mkl_get_max_threads() << " MKL threads";
69  return true;
70 }
71 REGISTER_CAFFE2_INIT_FUNCTION(
72  Caffe2SetMKLThreads,
73  &Caffe2SetMKLThreads,
74  "Set MKL threads.");
75 #endif // CAFFE2_USE_MKL
76 
77 } // namespace caffe2
A global dictionary that holds information about what Caffe2 modules have been loaded in the current ...