flags_native.cc 15.2 KB
Newer Older
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
// Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
//
// 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 "paddle/utils/flags_native.h"

#include <assert.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <map>
#include <mutex>
#include <set>
#include <sstream>

namespace paddle {
namespace flags {

std::stringstream& ErrorStream() {
  static std::stringstream err_ss;
  return err_ss;
}

inline void exit_with_errors() {
  std::cerr << ErrorStream().str();
  exit(-1);
}

#define LOG_FLAG_ERROR(message)                                             \
  ErrorStream() << "paddle flags error: " << message << " (at " << __FILE__ \
                << ":" << __LINE__ << ")" << std::endl

#define LOG_FLAG_FATAL_ERROR(message) \
  LOG_FLAG_ERROR(message);            \
  exit_with_errors()

enum class FlagType : uint8_t {
  BOOL = 0,
  INT32 = 1,
  UINT32 = 2,
  INT64 = 3,
  UINT64 = 4,
  DOUBLE = 5,
  STRING = 6,
  UNDEFINED = 7,
};

class Flag {
 public:
  Flag(std::string name,
       std::string description,
       std::string file,
       FlagType type,
       const void* default_value,
       void* value)
      : name_(name),
        description_(description),
        file_(file),
        type_(type),
        default_value_(default_value),
        value_(value) {}
  ~Flag() = default;

  // Summary: --name_: type_, description_ (default: default_value_)
  std::string Summary() const;

  void SetValueFromString(const std::string& value);

 private:
  friend class FlagRegistry;

  const std::string name_;
  const std::string description_;
  const std::string file_;
  const FlagType type_;
  const void* default_value_;
  void* value_;
};

class FlagRegistry {
 public:
  static FlagRegistry* Instance() {
    static FlagRegistry* global_registry_ = new FlagRegistry();
    return global_registry_;
  }

  void RegisterFlag(Flag* flag);

  bool SetFlagValue(const std::string& name, const std::string& value);

  bool HasFlag(const std::string& name) const;

  void PrintAllFlagHelp(std::ostream& os) const;

 private:
  FlagRegistry() = default;

  std::map<std::string, Flag*> flags_;

  struct FlagCompare {
    bool operator()(const Flag* flag1, const Flag* flag2) const {
      return flag1->name_ < flag2->name_;
    }
  };

  std::map<std::string, std::set<Flag*, FlagCompare>> flags_by_file_;

  std::mutex mutex_;
};

template <typename T>
struct FlagTypeTraits {
  static constexpr FlagType Type = FlagType::UNDEFINED;
};

#define DEFINE_FLAG_TYPE_TRAITS(type, flag_type) \
  template <>                                    \
  struct FlagTypeTraits<type> {                  \
    static constexpr FlagType Type = flag_type;  \
  }

DEFINE_FLAG_TYPE_TRAITS(bool, FlagType::BOOL);
DEFINE_FLAG_TYPE_TRAITS(int32_t, FlagType::INT32);
DEFINE_FLAG_TYPE_TRAITS(uint32_t, FlagType::UINT32);
DEFINE_FLAG_TYPE_TRAITS(int64_t, FlagType::INT64);
DEFINE_FLAG_TYPE_TRAITS(uint64_t, FlagType::UINT64);
DEFINE_FLAG_TYPE_TRAITS(double, FlagType::DOUBLE);
DEFINE_FLAG_TYPE_TRAITS(std::string, FlagType::STRING);

#undef DEFINE_FLAG_TYPE_TRAITS

template <typename T>
FlagRegisterer::FlagRegisterer(std::string name,
                               std::string help,
                               std::string file,
                               const T* default_value,
                               T* value) {
  FlagType type = FlagTypeTraits<T>::Type;
  Flag* flag = new Flag(name, help, file, type, default_value, value);
  FlagRegistry::Instance()->RegisterFlag(flag);
}

// Instantiate FlagRegisterer for supported types.
#define INSTANTIATE_FLAG_REGISTERER(type)                            \
  template FlagRegisterer::FlagRegisterer(std::string name,          \
                                          std::string help,          \
                                          std::string file,          \
                                          const type* default_value, \
                                          type* value)

INSTANTIATE_FLAG_REGISTERER(bool);
INSTANTIATE_FLAG_REGISTERER(int32_t);
INSTANTIATE_FLAG_REGISTERER(uint32_t);
INSTANTIATE_FLAG_REGISTERER(int64_t);
INSTANTIATE_FLAG_REGISTERER(uint64_t);
INSTANTIATE_FLAG_REGISTERER(double);
INSTANTIATE_FLAG_REGISTERER(std::string);

#undef INSTANTIATE_FLAG_REGISTERER

std::string FlagType2String(FlagType type) {
  switch (type) {
    case FlagType::BOOL:
      return "bool";
    case FlagType::INT32:
      return "int32";
    case FlagType::UINT32:
      return "uint32";
    case FlagType::INT64:
      return "int64";
    case FlagType::UINT64:
      return "uint64";
    case FlagType::DOUBLE:
      return "double";
    case FlagType::STRING:
      return "string";
    default:
      return "undefined";
  }
}

std::string Value2String(const void* value, FlagType type) {
  switch (type) {
    case FlagType::BOOL: {
      const bool* val = static_cast<const bool*>(value);
      return *val ? "true" : "false";
    }
    case FlagType::INT32: {
      const int32_t* val = static_cast<const int32_t*>(value);
      return std::to_string(*val);
    }
    case FlagType::UINT32: {
      const uint32_t* val = static_cast<const uint32_t*>(value);
      return std::to_string(*val);
    }
    case FlagType::INT64: {
      const int64_t* val = static_cast<const int64_t*>(value);
      return std::to_string(*val);
    }
    case FlagType::UINT64: {
      const uint64_t* val = static_cast<const uint64_t*>(value);
      return std::to_string(*val);
    }
    case FlagType::DOUBLE: {
      const double* val = static_cast<const double*>(value);
      return std::to_string(*val);
    }
    case FlagType::STRING: {
      const std::string* val = static_cast<const std::string*>(value);
      return *val;
    }
    default:
      LOG_FLAG_FATAL_ERROR("flag type is undefined.");
      return "";
  }
}

std::string Flag::Summary() const {
  return "--" + name_ + ": " + FlagType2String(type_) + ", " + description_ +
         " (default: " + Value2String(default_value_, type_) + ")";
}

void Flag::SetValueFromString(const std::string& value) {
  try {
    switch (type_) {
      case FlagType::BOOL: {
        bool* val = static_cast<bool*>(value_);
        if (value == "true" || value == "True" || value == "TRUE" ||
            value == "1") {
          *val = true;
        } else if (value == "false" || value == "False" || value == "FALSE" ||
                   value == "0") {
          *val = false;
        } else {
          throw std::invalid_argument(
              ", please use [true, True, TRUE, 1] or [false, False, FALSE, "
              "0].");
        }
        break;
      }
      case FlagType::INT32: {
        int32_t* val = static_cast<int32_t*>(value_);
        *val = std::stoi(value);
        break;
      }
      case FlagType::UINT32: {
        uint32_t* val = static_cast<uint32_t*>(value_);
        *val = std::stoul(value);
        break;
      }
      case FlagType::INT64: {
        int64_t* val = static_cast<int64_t*>(value_);
        *val = std::stoll(value);
        break;
      }
      case FlagType::UINT64: {
        uint64_t* val = static_cast<uint64_t*>(value_);
        *val = std::stoull(value);
        break;
      }
      case FlagType::DOUBLE: {
        double* val = static_cast<double*>(value_);
        *val = std::stod(value);
        break;
      }
      case FlagType::STRING: {
        std::string* val = static_cast<std::string*>(value_);
        *val = value;
        break;
      }
      default: {
        LOG_FLAG_FATAL_ERROR("flag type is undefined.");
      }
    }
  } catch (const std::exception& e) {
    std::string error_msg = "value: \"" + value + "\" is invalid for " +
                            FlagType2String(type_) + " flag \"" + name_ + "\"";
    if (type_ == FlagType::BOOL) {
      error_msg += e.what();
    } else {
      error_msg += ".";
    }
    LOG_FLAG_ERROR(error_msg);
  }
}

void FlagRegistry::RegisterFlag(Flag* flag) {
  auto iter = flags_.find(flag->name_);
  if (iter != flags_.end()) {
H
huangjiyi 已提交
300 301 302
    LOG_FLAG_FATAL_ERROR("flag multiple definition, flag \"" + flag->name_ +
                         "\" was defined both in " + iter->second->file_ +
                         " and " + flag->file_);
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
  } else {
    std::lock_guard<std::mutex> lock(mutex_);
    flags_[flag->name_] = flag;
    flags_by_file_[flag->file_].insert(flag);
  }
}

bool FlagRegistry::SetFlagValue(const std::string& name,
                                const std::string& value) {
  if (HasFlag(name)) {
    std::lock_guard<std::mutex> lock(mutex_);
    flags_[name]->SetValueFromString(value);
    return true;
  } else {
    LOG_FLAG_ERROR("illegal SetFlagValue, flag \"" + name +
                   "\" is not defined.");
    return false;
  }
}

bool FlagRegistry::HasFlag(const std::string& name) const {
  return flags_.find(name) != flags_.end();
}

void FlagRegistry::PrintAllFlagHelp(std::ostream& os) const {
  for (const auto& iter : flags_by_file_) {
    os << std::endl << "Flags defined in " << iter.first << ":" << std::endl;
    for (const auto& flag : iter.second) {
      os << "  " << flag->Summary() << std::endl;
    }
  }
  os << std::endl;
}

void PrintAllFlagHelp(bool to_file, const std::string& file_path) {
  if (to_file) {
    std::ofstream fout(file_path);
    FlagRegistry::Instance()->PrintAllFlagHelp(fout);
  } else {
    FlagRegistry::Instance()->PrintAllFlagHelp(std::cout);
  }
}

bool SetFlagValue(const std::string& name, const std::string& value) {
  return FlagRegistry::Instance()->SetFlagValue(name, value);
}

bool FindFlag(const std::string& name) {
  return FlagRegistry::Instance()->HasFlag(name);
}

bool GetValueFromEnv(const std::string& name, std::string* value) {
  const char* env_var = std::getenv(name.c_str());
  if (env_var == nullptr) {
    return false;
  }
  *value = std::string(env_var);
  return true;
}

void SetFlagsFromEnv(const std::vector<std::string>& flags, bool error_fatal) {
  bool success = true;
  for (const std::string& flag_name : flags) {
    std::string env_var_name = std::string("FLAGS_") + flag_name;
    std::string env_var_value;
    if (GetValueFromEnv(env_var_name, &env_var_value)) {
      success =
          FlagRegistry::Instance()->SetFlagValue(flag_name, env_var_value);
    } else if (error_fatal) {
      LOG_FLAG_ERROR("environment variable \"" + env_var_name +
                     "\" is not set.");
      success = false;
    }
  }
  if (error_fatal && !success) {
    exit_with_errors();
  }
}

static bool allow_undefined_flags = false;

void AllowUndefinedFlags() { allow_undefined_flags = true; }

void ParseCommandLineFlags(int* pargc, char*** pargv) {
  assert(*pargc > 0);
  size_t argv_num = *pargc - 1;
  std::vector<std::string> argvs(*pargv + 1, *pargv + *pargc);

  std::string arg_format_help =
      "please follow the formats: \"--help(h)\", \"--name=value\""
      " or \"--name value\".";
  for (size_t i = 0; i < argv_num; i++) {
    const std::string& argv = argvs[i];

H
huangjiyi 已提交
397 398 399 400
    if (argv.empty()) {
      continue;
    }

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    if (argv.size() < 2 || argv[0] != '-') {
      LOG_FLAG_FATAL_ERROR("invalid commandline argument: \"" + argv + "\", " +
                           arg_format_help);
    }

    // parse arg name and value
    size_t hyphen_num = argv[1] == '-' ? 2 : 1;
    std::string name, value;
    size_t split_pos = argv.find('=');
    if (split_pos == std::string::npos) {
      // the argv format is "--name" or "--name value"
      name = argv.substr(hyphen_num);
      if (name.empty()) {
        LOG_FLAG_FATAL_ERROR("invalid commandline argument: \"" + argv +
                             "\", " + arg_format_help);
      }

      // print help message
      if (name == "help" || name == "h") {
        FlagRegistry::Instance()->PrintAllFlagHelp(std::cout);
        exit(1);
      }

      // get the value from next argv.
      if (++i == argv_num) {
        LOG_FLAG_FATAL_ERROR("expected value of flag \"" + name +
                             "\" but found none.");
      } else {
        value = argvs[i];
      }
    } else {
      // the argv format is "--name=value"
      if (split_pos == hyphen_num || split_pos == argv.size() - 1) {
        LOG_FLAG_FATAL_ERROR("invalid commandline argument: \"" + argv +
                             "\", " + arg_format_help);
      }
      name = argv.substr(hyphen_num, split_pos - hyphen_num);
      value = argv.substr(split_pos + 1);
    }

    // special case for flag value enclosed in ""
    if (value[0] == '"') {
      value = value.substr(1);
      if (value.back() == '"') {
        value.pop_back();
      } else {
        while (i < argv_num) {
          value += " ";
          value += argvs[++i];
          if (value.back() == '"') {
            break;
          }
        }
        if (value.back() == '"') {
          value.pop_back();
        } else {
          LOG_FLAG_FATAL_ERROR("unexperted end of flag \"" + name +
                               "\" value while looking for matching `\"'");
        }
      }
    }

    if (name == "fromenv" || name == "tryfromenv") {
      // Value of --fromenv or --tryfromenv should be
      // a comma separated list of env var names.
      std::vector<std::string> env_flag_names;
      for (size_t start_pos = 0, end_pos = 0;
           start_pos < value.size() && end_pos != std::string::npos;
           start_pos = end_pos + 1) {
        end_pos = value.find(',', start_pos);
        env_flag_names.push_back(value.substr(start_pos, end_pos - start_pos));
      }
      if (name == "fromenv") {
        SetFlagsFromEnv(env_flag_names, true);
      } else {
        SetFlagsFromEnv(env_flag_names, false);
      }
      continue;
    }

    FlagRegistry::Instance()->SetFlagValue(name, value);
  }
  if (!allow_undefined_flags && !ErrorStream().str().empty()) {
    exit_with_errors();
  }
}

H
huangjiyi 已提交
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
template <typename T>
T GetFromEnv(const std::string& name, const T& default_val) {
  std::string value_str;
  if (GetValueFromEnv(name, &value_str)) {
    T value;
    FlagType type = FlagTypeTraits<T>::Type;
    Flag flag("tmp_" + name, "", "", type, &value, &value);
    flag.SetValueFromString(value_str);
    if (!ErrorStream().str().empty()) {
      ErrorStream().str("");
      LOG_FLAG_FATAL_ERROR("value \"" + value_str +
                           "\" of environment"
                           "variable \"" +
                           name +
                           "\" is invalid when "
                           "using GetFromEnv with " +
                           FlagType2String(type) + " type.");
    }
    return value;
  } else {
    return default_val;
  }
}

#define INSTANTIATE_GET_FROM_ENV(type) \
  template type GetFromEnv(const std::string& name, const type& default_val)

INSTANTIATE_GET_FROM_ENV(bool);
INSTANTIATE_GET_FROM_ENV(int32_t);
INSTANTIATE_GET_FROM_ENV(uint32_t);
INSTANTIATE_GET_FROM_ENV(int64_t);
INSTANTIATE_GET_FROM_ENV(uint64_t);
INSTANTIATE_GET_FROM_ENV(double);
INSTANTIATE_GET_FROM_ENV(std::string);

#undef INSTANTIATE_GET_FROM_ENV

525 526
}  // namespace flags
}  // namespace paddle