Util.cpp 10.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Licensed 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. */

#include "Util.h"

#include <dirent.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
L
Liu Yiqun 已提交
21 22

#ifdef __SSE__
Z
zhangjinchao01 已提交
23
#include <xmmintrin.h>
L
Liu Yiqun 已提交
24 25 26 27
#endif
#ifdef __SSE3__
#include <pmmintrin.h>
#endif
Z
zhangjinchao01 已提交
28 29 30 31

#include <fstream>
#include <mutex>

L
liaogang 已提交
32
#include <gflags/gflags.h>
Z
zhangjinchao01 已提交
33

34
#include "CpuId.h"
Z
zhangjinchao01 已提交
35
#include "CustomStackTrace.h"
L
liaogang 已提交
36
#include "Logging.h"
Y
Yu Yang 已提交
37
#include "StringUtil.h"
Z
zhangjinchao01 已提交
38 39 40 41
#include "Thread.h"
#include "ThreadLocal.h"
#include "Version.h"

42
DEFINE_int32(seed, 1, "random number seed. 0 for srand(time)");
Z
zhangjinchao01 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

#ifdef WITH_GOOGLE_PERFTOOLS
/*
  In order to use google profiler, you need to install gperftools,
  which can be obtained at:
  https://gperftools.googlecode.com/files/gperftools-2.0.tar.gz

  gperftools should be configured with --enable-frame-pointers

  Then link the executable with -lprofiler.

  After you start the application, you can use kill -s signal PID to
  start/stop profiling. The profile data will be stored in file
  FLAGS_profile_data_file, which can be analyzed by pprof.
*/

#include <gperftools/profiler.h>

61 62
DEFINE_int32(profile_signal, 12, "signal for switch google profiler");
DEFINE_string(profile_data_file, "gperf.prof", "file for storing profile data");
Z
zhangjinchao01 已提交
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

static void profilerSwitch(int signalNumber) {
  bool static started = false;

  if (!started) {
    if (ProfilerStart(FLAGS_profile_data_file.c_str())) {
      LOG(INFO) << "Profiler started";
    } else {
      LOG(WARNING) << "Can't turn on cpu profiling for "
                   << FLAGS_profile_data_file;
    }
  } else {
    ProfilerStop();
    LOG(INFO) << "Profiler stopped";
  }
  started = !started;
}

static void installProfilerSwitch() {
  sighandler_t oldHandler = signal(FLAGS_profile_signal, profilerSwitch);

  if (!oldHandler) {
    LOG(INFO) << "Using signal " << FLAGS_profile_signal
              << " to turn on/off profiler";
  } else {
    LOG(WARNING) << "Signal " << FLAGS_profile_signal << " is already in use\n";
  }
}

#else

static void installProfilerSwitch() {}

#endif  // WITH_GOOGLE_PERFTOOLS

namespace paddle {

L
liaogang 已提交
100
pid_t getTID() {
101 102 103 104 105 106 107 108 109 110 111 112
#if defined(__APPLE__) || defined(__OSX__)
  // syscall is deprecated: first deprecated in macOS 10.12.
  // syscall is unsupported;
  // syscall pid_t tid = syscall(SYS_thread_selfid);
  uint64_t tid;
  pthread_threadid_np(NULL, &tid);
#else
#ifndef __NR_gettid
#define __NR_gettid 224
#endif
  pid_t tid = syscall(__NR_gettid);
#endif
113
  CHECK_NE((int)tid, -1);
L
liaogang 已提交
114 115 116
  return tid;
}

Z
zhangjinchao01 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
static bool g_initialized = false;
typedef std::pair<int, std::function<void()>> PriorityFuncPair;
typedef std::vector<PriorityFuncPair> InitFuncList;
static InitFuncList* g_initFuncs = nullptr;
static std::once_flag g_onceFlag;
void registerInitFunction(std::function<void()> func, int priority) {
  if (g_initialized) {
    LOG(FATAL) << "registerInitFunction() should only called before initMain()";
  }
  if (!g_initFuncs) {
    g_initFuncs = new InitFuncList();
  }
  g_initFuncs->push_back(std::make_pair(priority, func));
}

void runInitFunctions() {
Y
Yu Yang 已提交
133
  std::call_once(g_onceFlag, []() {
L
Luo Tao 已提交
134
    VLOG(3) << "Calling runInitFunctions";
Y
Yu Yang 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147
    if (g_initFuncs) {
      std::sort(g_initFuncs->begin(),
                g_initFuncs->end(),
                [](const PriorityFuncPair& x, const PriorityFuncPair& y) {
                  return x.first > y.first;
                });
      for (auto& f : *g_initFuncs) {
        f.second();
      }
      delete g_initFuncs;
      g_initFuncs = nullptr;
    }
    g_initialized = true;
L
Luo Tao 已提交
148
    VLOG(3) << "Call runInitFunctions done.";
Y
Yu Yang 已提交
149
  });
Z
zhangjinchao01 已提交
150 151 152
}

void initMain(int argc, char** argv) {
Y
Yu Yang 已提交
153
  installLayerStackTracer();
Z
zhangjinchao01 已提交
154 155 156 157 158
  std::string line;
  for (int i = 0; i < argc; ++i) {
    line += argv[i];
    line += ' ';
  }
L
liaogang 已提交
159 160 161 162 163

#ifndef GFLAGS_GFLAGS_H_
  namespace gflags = google;
#endif

L
liaogang 已提交
164
  gflags::ParseCommandLineFlags(&argc, &argv, true);
X
xuwei06 已提交
165 166
  initializeLogging(argc, argv);
  LOG(INFO) << "commandline: " << line;
Z
zhangjinchao01 已提交
167 168 169 170
  CHECK_EQ(argc, 1) << "Unknown commandline argument: " << argv[1];

  installProfilerSwitch();

L
Liu Yiqun 已提交
171
#ifdef __SSE__
Z
zhangjinchao01 已提交
172
  _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
L
Liu Yiqun 已提交
173 174
#endif
#ifdef __SSE3__
Z
zhangjinchao01 已提交
175
  _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
L
Liu Yiqun 已提交
176
#endif
Z
zhangjinchao01 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

  if (FLAGS_seed == 0) {
    unsigned int t = time(NULL);
    srand(t);
    ThreadLocalRand::initSeed(t);
    LOG(INFO) << "random number seed=" << t;
  } else {
    srand(FLAGS_seed);
    ThreadLocalRand::initSeed(FLAGS_seed);
  }

  if (FLAGS_use_gpu) {
    // This is the initialization of the CUDA environment,
    // need before runInitFunctions.
    // TODO(hedaoyuan) Can be considered in the runInitFunctions,
    // but to ensure that it is the first to initialize.
    hl_start();
    hl_init(FLAGS_gpu_id);
  }

  version::printVersion();
198
  checkCPUFeature().check();
Z
zhangjinchao01 已提交
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
  runInitFunctions();
}

std::string readFile(const std::string& fileName) {
  std::ifstream is(fileName);

  // get length of file:
  is.seekg(0, is.end);
  size_t length = is.tellg();
  is.seekg(0, is.beg);
  std::string str(length, (char)0);
  CHECK(is.read(&str[0], length)) << "Fail to read file: " << fileName;
  return str;
}

namespace path {

std::string basename(const std::string& path) {
  size_t pos = path.rfind(sep);
  ++pos;
  return path.substr(pos, std::string::npos);
}

std::string dirname(const std::string& path) {
  size_t pos = path.rfind(sep);
  if (pos == std::string::npos) return std::string();
  return path.substr(0, pos);
}

std::string join(const std::string& part1, const std::string& part2) {
  if (!part2.empty() && part2.front() == sep) {
    return part2;
  }
  std::string ret;
  ret.reserve(part1.size() + part2.size() + 1);
  ret = part1;
  if (!ret.empty() && ret.back() != sep) {
    ret += sep;
  }
  ret += part2;
  return ret;
}

}  // namespace path

void copyFileToPath(const std::string& file, const std::string& dir) {
L
Luo Tao 已提交
245
  VLOG(3) << "copy " << file << " to " << dir;
Z
zhangjinchao01 已提交
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
  std::string fileName = path::basename(file);
  std::string dst = path::join(dir, fileName);
  std::ifstream source(file, std::ios_base::binary);
  std::ofstream dest(dst, std::ios_base::binary);
  CHECK(source) << "Fail to open " << file;
  CHECK(dest) << "Fail to open " << dst;
  dest << source.rdbuf();
  source.close();
  dest.close();
}

bool fileExist(const char* filename) { return (access(filename, 0) == 0); }

void touchFile(const char* filename) {
  if (!fileExist(filename)) {
    std::ofstream os(filename);
  }
}

int isDir(const char* path) {
  struct stat s_buf;
  if (stat(path, &s_buf)) {
    return 0;
  }
  return S_ISDIR(s_buf.st_mode);
}

void rmDir(const char* folderName) {
  if (isDir(folderName)) {
    DIR* dp;
    struct dirent* ep;
    std::string buf;
    dp = opendir(folderName);
    while ((ep = readdir(dp)) != NULL) {
      if (strcmp(ep->d_name, ".") && strcmp(ep->d_name, "..")) {
        buf = std::string(folderName) + "/" + std::string(ep->d_name);
        if (isDir(buf.c_str())) {
          rmDir(buf.c_str());
        } else {
          remove(buf.c_str());
        }
      }
    }
    closedir(dp);
    rmdir(folderName);
  }
}

void mkDir(const char* filename) {
  if (mkdir(filename, 0755)) {
    CHECK(errno == EEXIST) << filename << "mkdir failed!";
  }
}

300
void mkDirRecursively(const char* dir) {
Z
zhangjinchao01 已提交
301 302
  struct stat sb;

X
xuwei06 已提交
303
  if (*dir == 0) return;  // empty string
Z
zhangjinchao01 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
  if (!stat(dir, &sb)) return;

  mkDirRecursively(path::dirname(dir).c_str());

  mkDir(dir);
}

void loadFileList(const std::string& fileListFileName,
                  std::vector<std::string>& fileList) {
  std::ifstream is(fileListFileName);
  CHECK(is) << "Fail to open " << fileListFileName;
  std::string line;
  while (is) {
    if (!getline(is, line)) break;
    fileList.push_back(line);
  }
}

double getMemoryUsage() {
H
hedaoyuan 已提交
323 324 325
#if defined(__ANDROID__)
  return 0.0;
#else
Z
zhangjinchao01 已提交
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
  FILE* fp = fopen("/proc/meminfo", "r");
  CHECK(fp) << "failed to fopen /proc/meminfo";
  size_t bufsize = 256 * sizeof(char);
  char* buf = new (std::nothrow) char[bufsize];
  CHECK(buf);
  int totalMem = -1;
  int freeMem = -1;
  int bufMem = -1;
  int cacheMem = -1;
  while (getline(&buf, &bufsize, fp) >= 0) {
    if (0 == strncmp(buf, "MemTotal", 8)) {
      if (1 != sscanf(buf, "%*s%d", &totalMem)) {
        LOG(FATAL) << "failed to get MemTotal from string: [" << buf << "]";
      }
    } else if (0 == strncmp(buf, "MemFree", 7)) {
      if (1 != sscanf(buf, "%*s%d", &freeMem)) {
        LOG(FATAL) << "failed to get MemFree from string: [" << buf << "]";
      }
    } else if (0 == strncmp(buf, "Buffers", 7)) {
      if (1 != sscanf(buf, "%*s%d", &bufMem)) {
        LOG(FATAL) << "failed to get Buffers from string: [" << buf << "]";
      }
    } else if (0 == strncmp(buf, "Cached", 6)) {
      if (1 != sscanf(buf, "%*s%d", &cacheMem)) {
        LOG(FATAL) << "failed to get Cached from string: [" << buf << "]";
      }
    }
    if (totalMem != -1 && freeMem != -1 && bufMem != -1 && cacheMem != -1) {
      break;
    }
  }
  CHECK(totalMem != -1 && freeMem != -1 && bufMem != -1 && cacheMem != -1)
      << "failed to get all information";
  fclose(fp);
  delete[] buf;
  double usedMem = 1.0 - 1.0 * (freeMem + bufMem + cacheMem) / totalMem;
  return usedMem;
H
hedaoyuan 已提交
363
#endif
Z
zhangjinchao01 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
}

SyncThreadPool* getGlobalSyncThreadPool() {
  static std::unique_ptr<SyncThreadPool> syncThreadPool;
  if (syncThreadPool &&
      syncThreadPool->getNumThreads() != (size_t)FLAGS_trainer_count) {
    LOG(WARNING) << "trainer_count changed in training process!";
    syncThreadPool.reset(nullptr);
  }
  if (!syncThreadPool) {
    syncThreadPool.reset(new SyncThreadPool(FLAGS_trainer_count));
  }
  return syncThreadPool.get();
}

size_t calculateServiceNum(const std::string& pservers, int ports_num) {
  std::vector<std::string> hosts;
  str::split(pservers, ',', &hosts);
  return hosts.size() * ports_num;
}

385 386 387
void memcpyWithCheck(void* dest,
                     const void* src,
                     size_t num,
Z
zhangjinchao01 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401
                     const void* srcEnd) {
  int minus = (char*)srcEnd - (char*)src - num;
  CHECK_LE(0, minus) << "memcpyWithCheck: copy " << num
                     << " bytes data out of range.";
  memcpy(dest, src, num);
}

hl_activation_mode_t hlActiveType(const std::string& type) {
  if (type == "sigmoid") {
    return HL_ACTIVATION_SIGMOID;
  } else if (type == "relu") {
    return HL_ACTIVATION_RELU;
  } else if (type == "tanh") {
    return HL_ACTIVATION_TANH;
H
Haonan 已提交
402
  } else if (type == "linear" || type == "") {
Z
zhangjinchao01 已提交
403 404 405 406 407 408 409
    return HL_ACTIVATION_LINEAR;
  } else {
    LOG(FATAL) << "Do not support activation type " << type;
  }
}

}  // namespace paddle