This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
Copy pathinitialize.cc
406 lines (362 loc) · 13.7 KB
/
initialize.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file initialize.cc
* \brief initialize mxnet library
*/
#include "initialize.h"
#include <algorithm>
#include <csignal>
#if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
#include <windows.h>
/*!
* \brief Retrieve the system error message for the last-error code
* \param err string that gets the error message
*/
void win_err(char** err) {
uint32_t dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<char*>(err),
0,
nullptr);
}
#else
#include <cxxabi.h>
#include <dlfcn.h>
#if MXNET_USE_SIGNAL_HANDLER && DMLC_LOG_STACK_TRACE
#include <execinfo.h>
#endif
#include <cerrno>
#endif
#include <dmlc/logging.h>
#include <mxnet/c_api.h>
#include <mxnet/engine.h>
#include "./engine/openmp.h"
#include "./operator/custom/custom-inl.h"
#if MXNET_USE_OPENCV
#include <opencv2/opencv.hpp>
#endif // MXNET_USE_OPENCV
#include "common/utils.h"
#include "engine/openmp.h"
#if defined(MKL_USE_SINGLE_DYNAMIC_LIBRARY)
#include <mkl.h>
#endif
namespace mxnet {
// pthread_atfork handlers, delegated to LibraryInitializer members.
void pthread_atfork_prepare() {
LibraryInitializer* library_initializer = LibraryInitializer::Get();
library_initializer->atfork_prepare();
}
void pthread_atfork_parent() {
LibraryInitializer* library_initializer = LibraryInitializer::Get();
library_initializer->atfork_parent();
}
void pthread_atfork_child() {
LibraryInitializer* library_initializer = LibraryInitializer::Get();
library_initializer->atfork_child();
}
// LibraryInitializer member functions
LibraryInitializer::LibraryInitializer()
: original_pid_(common::current_process_id()),
mp_worker_nthreads_(dmlc::GetEnv("MXNET_MP_WORKER_NTHREADS", 1)),
cpu_worker_nthreads_(dmlc::GetEnv("MXNET_CPU_WORKER_NTHREADS", 1)),
mp_cv_num_threads_(dmlc::GetEnv("MXNET_MP_OPENCV_NUM_THREADS", 0)) {
dmlc::InitLogging("mxnet");
init_mkl_dynamic_library();
engine::OpenMP::Get(); // force OpenMP initialization
install_pthread_atfork_handlers();
}
LibraryInitializer::~LibraryInitializer() = default;
bool LibraryInitializer::lib_is_loaded(const std::string& path) const {
return loaded_libs_.count(path) > 0;
}
/*!
* \brief Loads the dynamic shared library file
* \param path library file location
* \return handle a pointer for the loaded library, throws dmlc::error if library can't be loaded
*/
void* LibraryInitializer::lib_load(const char* path) {
void* handle = nullptr;
// check if library was already loaded
if (!lib_is_loaded(path)) {
// if not, load it
#if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
handle = LoadLibrary(path);
if (!handle) {
char* err_msg = nullptr;
win_err(&err_msg);
LOG(FATAL) << "Error loading library: '" << path << "'\n" << err_msg;
LocalFree(err_msg);
return nullptr;
}
#else
/* library loading flags:
* RTLD_LAZY - Perform lazy binding. Only resolve symbols as the code that
* references them is executed.
* RTLD_LOCAL - Symbols defined in this library are not made available to
* resolve references in subsequently loaded libraries.
*/
handle = dlopen(path, RTLD_LAZY | RTLD_LOCAL);
if (!handle) {
LOG(FATAL) << "Error loading library: '" << path << "'\n" << dlerror();
return nullptr;
}
#endif // _WIN32 or _WIN64 or __WINDOWS__
// then store the pointer to the library
loaded_libs_[path] = handle;
} else {
handle = loaded_libs_.at(path);
}
return handle;
}
/*!
* \brief Closes the loaded dynamic shared library file
* \param handle library file handle
*/
void LibraryInitializer::lib_close(void* handle, const std::string& libpath) {
#if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
FreeLibrary((HMODULE)handle);
#else
if (dlclose(handle)) {
LOG(WARNING) << "LibraryInitializer::lib_close: couldn't close library at address: " << handle
<< " loaded from: '" << libpath << "': " << dlerror();
}
#endif // _WIN32 or _WIN64 or __WINDOWS__
}
/*!
* \brief Obtains address of given function in the loaded library
* \param handle pointer for the loaded library
* \param func function pointer that gets output address
* \param name function name to be fetched
*/
void LibraryInitializer::get_sym(void* handle, void** func, const char* name) {
#if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
*func = GetProcAddress((HMODULE)handle, name);
if (!(*func)) {
char* err_msg = nullptr;
win_err(&err_msg);
LOG(FATAL) << "Error getting function '" << name << "' from library\n" << err_msg;
LocalFree(err_msg);
}
#else
*func = dlsym(handle, name);
if (!(*func)) {
LOG(FATAL) << "Error getting function '" << name << "' from library\n" << dlerror();
}
#endif // _WIN32 or _WIN64 or __WINDOWS__
}
bool LibraryInitializer::was_forked() const {
return common::current_process_id() != original_pid_;
}
void LibraryInitializer::atfork_prepare() {
using op::custom::CustomOperator;
CustomOperator::Get()->Stop();
Engine::Get()->Stop();
}
void LibraryInitializer::atfork_parent() {
using op::custom::CustomOperator;
Engine::Get()->Start();
CustomOperator::Get()->Start();
}
void LibraryInitializer::atfork_child() {
using op::custom::CustomOperator;
// Conservative thread management for multiprocess workers
this->cpu_worker_nthreads_ = this->mp_worker_nthreads_;
#if MXNET_USE_OPENCV && !__APPLE__
cv::setNumThreads(mp_cv_num_threads_);
#endif // MXNET_USE_OPENCV
engine::OpenMP::Get()->initialize_process();
engine::OpenMP::Get()->set_thread_max(1);
engine::OpenMP::Get()->set_enabled(false);
Engine::Get()->Start();
CustomOperator::Get()->Start();
}
void LibraryInitializer::install_pthread_atfork_handlers() {
#ifndef _WIN32
engine::OpenMP::Get()->initialize_process(); // force omp to set its atfork handler first
pthread_atfork(pthread_atfork_prepare, pthread_atfork_parent, pthread_atfork_child);
#endif
}
void LibraryInitializer::init_mkl_dynamic_library() {
#if !(defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__))
#if MKL_USE_SINGLE_DYNAMIC_LIBRARY
#if USE_INT64_TENSOR_SIZE
int interface = MKL_INTERFACE_ILP64;
#else
int interface = MKL_INTERFACE_LP64;
#endif
#if defined(__INTEL_LLVM_COMPILER) || defined(__APPLE__)
mkl_set_threading_layer(MKL_THREADING_INTEL);
#else
mkl_set_threading_layer(MKL_THREADING_GNU);
interface += MKL_INTERFACE_GNU;
#endif
mkl_set_interface_layer(interface);
#endif
#endif
}
#if MXNET_USE_SIGNAL_HANDLER && DMLC_LOG_STACK_TRACE
static inline void printStackTrace(FILE* out = stderr, const unsigned int max_frames = 63) {
#if !defined(_WIN32) && !defined(_WIN64) && !defined(__WINDOWS__)
// storage array for stack trace address data
void* addrlist[max_frames + 1];
// retrieve current stack addresses
size_t addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));
if (addrlen < 5) {
return;
} else {
addrlen = std::min(addrlen, dmlc::LogStackTraceLevel());
}
fprintf(out, "Stack trace:\n");
// resolve addresses into strings containing "filename(function+address)",
// Actually it will be ## program address function + offset
// this array must be free()-ed
char** symbollist = backtrace_symbols(addrlist, addrlen);
size_t funcnamesize = 1024;
char funcname[1024];
// iterate over the returned symbol lines. skip the first, it is the
// address of this function.
for (unsigned int i = 4; i < addrlen; i++) {
char* begin_name = nullptr;
char* begin_offset = nullptr;
char* end_offset = nullptr;
// find parentheses and +address offset surrounding the mangled name
#ifdef DARWIN
// OSX style stack trace
for (char* p = symbollist[i]; *p; ++p) {
if (*p == '_' && *(p - 1) == ' ') {
begin_name = p - 1;
} else if (*p == '+') {
begin_offset = p - 1;
}
}
if (begin_name && begin_offset && begin_name < begin_offset) {
*begin_name++ = '\0';
*begin_offset++ = '\0';
// mangled name is now in [begin_name, begin_offset) and caller
// offset in [begin_offset, end_offset). now apply
// __cxa_demangle():
int status;
char* ret = abi::__cxa_demangle(begin_name, &funcname[0], &funcnamesize, &status);
if (status == 0) {
funcname = ret; // use possibly realloc()-ed string
fprintf(out, " %-30s %-40s %s\n", symbollist[i], funcname, begin_offset);
} else {
// demangling failed. Output function name as a C function with
// no arguments.
fprintf(out, " %-30s %-38s() %s\n", symbollist[i], begin_name, begin_offset);
}
} else {
// couldn't parse the line? print the whole line.
fprintf(out, " %-40s\n", symbollist[i]);
}
#else
for (char* p = symbollist[i]; *p; ++p) {
if (*p == '(') {
begin_name = p;
} else if (*p == '+') {
begin_offset = p;
} else if (*p == ')' && (begin_offset || begin_name)) {
end_offset = p;
}
}
if (begin_name && end_offset && begin_name < end_offset) {
*begin_name++ = '\0';
*end_offset++ = '\0';
if (begin_offset) {
*begin_offset++ = '\0';
}
// mangled name is now in [begin_name, begin_offset) and caller
// offset in [begin_offset, end_offset). now apply
// __cxa_demangle():
int status = 0;
char* ret = abi::__cxa_demangle(begin_name, funcname, &funcnamesize, &status);
char* fname = begin_name;
if (status == 0) {
fname = ret;
}
if (begin_offset) {
fprintf(
out, " %-30s ( %-40s + %-6s) %s\n", symbollist[i], fname, begin_offset, end_offset);
} else {
fprintf(out, " %-30s ( %-40s %-6s) %s\n", symbollist[i], fname, "", end_offset);
}
} else {
// couldn't parse the line? print the whole line.
fprintf(out, " %-40s\n", symbollist[i]);
}
#endif // !DARWIN - but is posix
}
free(symbollist);
#endif
}
#define SIGNAL_HANDLER(SIGNAL, HANDLER_NAME, IS_FATAL) \
std::shared_ptr<void(int)> HANDLER_NAME( \
signal(SIGNAL, \
[](int signum) { \
if (IS_FATAL) { \
printf("\nFatal Error: %s\n", strsignal(SIGNAL)); \
printStackTrace(); \
signal(signum, SIG_DFL); \
raise(signum); \
} else { \
switch (signum) { \
case SIGSEGV: \
LOG(FATAL) << "InternalError: " << strsignal(SIGNAL); \
break; \
case SIGFPE: \
LOG(FATAL) << "FloatingPointError: " << strsignal(SIGNAL); \
break; \
case SIGBUS: \
LOG(FATAL) << "IOError: " << strsignal(SIGNAL); \
break; \
default: \
LOG(FATAL) << "RuntimeError: " << strsignal(SIGNAL); \
break; \
} \
} \
}), \
[](auto f) { signal(SIGNAL, f); });
SIGNAL_HANDLER(SIGSEGV, SIGSEGVHandler, true);
SIGNAL_HANDLER(SIGFPE, SIGFPEHandler, false);
SIGNAL_HANDLER(SIGBUS, SIGBUSHandler, false);
#endif
void LibraryInitializer::close_open_libs() {
for (const auto& l : loaded_libs_) {
lib_close(l.second, l.first);
}
loaded_libs_.clear();
}
/**
* Perform static initialization
*/
#ifdef __GNUC__
// In GCC we use constructor to perform initialization before any static initializer is able to run
__attribute__((constructor)) static void LibraryInitializerEntry() {
#pragma GCC diagnostic ignored "-Wunused-variable"
volatile LibraryInitializer* library_init = LibraryInitializer::Get();
}
#else
static LibraryInitializer* __library_init = LibraryInitializer::Get();
#endif
} // namespace mxnet