global_value_getter_setter.cc 14.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2019 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/fluid/pybind/global_value_getter_setter.h"
16

17
#include <cctype>
18 19 20 21 22 23
#include <functional>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
24

25 26 27 28 29 30 31
#include "gflags/gflags.h"
#include "paddle/fluid/framework/python_headers.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/errors.h"
#include "paddle/fluid/platform/macros.h"
#include "pybind11/stl.h"

G
guofei 已提交
32
// data processing
33
DECLARE_bool(use_mkldnn);
34 35
DECLARE_string(tracer_mkldnn_ops_on);
DECLARE_string(tracer_mkldnn_ops_off);
G
guofei 已提交
36 37 38 39 40 41
// debug
DECLARE_bool(check_nan_inf);
DECLARE_bool(cpu_deterministic);
DECLARE_bool(enable_rpc_profiler);
DECLARE_int32(multiple_of_cupti_buffer_size);
DECLARE_bool(reader_queue_speed_test_mode);
42
DECLARE_int32(call_stack_level);
43
DECLARE_bool(sort_sum_gradient);
44
DECLARE_bool(check_kernel_launch);
G
guofei 已提交
45 46 47 48 49 50
// device management
DECLARE_int32(paddle_num_threads);
// executor
DECLARE_bool(enable_parallel_graph);
DECLARE_string(pe_profile_fname);
DECLARE_string(print_sub_graph_dir);
51
DECLARE_bool(use_ngraph);
G
guofei 已提交
52 53 54 55
// memory management
DECLARE_string(allocator_strategy);
DECLARE_double(eager_delete_tensor_gb);
DECLARE_double(fraction_of_cpu_memory_to_use);
56 57
DECLARE_bool(free_idle_chunk);
DECLARE_bool(free_when_no_cache_hit);
G
guofei 已提交
58 59 60 61 62 63 64 65 66 67
DECLARE_int32(fuse_parameter_groups_size);
DECLARE_double(fuse_parameter_memory_size);
DECLARE_bool(init_allocated_mem);
DECLARE_uint64(initial_cpu_memory_in_mb);
DECLARE_double(memory_fraction_of_eager_deletion);
DECLARE_bool(use_pinned_memory);
DECLARE_bool(use_system_allocator);
// others
DECLARE_bool(benchmark);
DECLARE_int32(inner_op_parallelism);
68
DECLARE_int32(max_inplace_grad_add);
G
guofei 已提交
69
DECLARE_string(tracer_profile_fname);
70
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
G
guofei 已提交
71 72 73
// cudnn
DECLARE_uint64(conv_workspace_size_limit);
DECLARE_bool(cudnn_batchnorm_spatial_persistent);
74
DECLARE_bool(cudnn_deterministic);
G
guofei 已提交
75
DECLARE_bool(cudnn_exhaustive_search);
76
DECLARE_bool(conv2d_disable_cudnn);
G
guofei 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
// data processing
DECLARE_bool(enable_cublas_tensor_op_math);
// device management
DECLARE_string(selected_gpus);
// memory management
DECLARE_bool(eager_delete_scope);
DECLARE_bool(fast_eager_deletion_mode);
DECLARE_double(fraction_of_cuda_pinned_memory_to_use);
DECLARE_double(fraction_of_gpu_memory_to_use);
DECLARE_uint64(gpu_memory_limit_mb);
DECLARE_uint64(initial_gpu_memory_in_mb);
DECLARE_uint64(reallocate_gpu_memory_in_mb);
// others
DECLARE_bool(sync_nccl_allreduce);
#endif
92

93 94 95 96
#ifdef PADDLE_WITH_XPU
// device management
DECLARE_string(selected_xpus);
#endif
97 98 99 100

#ifdef PADDLE_WITH_ASCEND_CL
// device management
DECLARE_string(selected_npus);
101 102
// set minmum loss scaling value
DECLARE_int32(min_loss_scaling);
103 104
#endif

G
guofei 已提交
105 106 107 108
#ifdef PADDLE_WITH_DISTRIBUTE
DECLARE_int32(rpc_send_thread_num);
DECLARE_int32(rpc_get_thread_num);
DECLARE_int32(rpc_prefetch_thread_num);
109
#endif
110 111 112 113 114 115 116 117 118 119 120 121 122

namespace paddle {
namespace pybind {

namespace py = pybind11;

class PYBIND11_HIDDEN GlobalVarGetterSetterRegistry {
  DISABLE_COPY_AND_ASSIGN(GlobalVarGetterSetterRegistry);

  GlobalVarGetterSetterRegistry() = default;

 public:
  using Getter = std::function<py::object()>;
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
  using Setter = std::function<void(const py::object &)>;

  template <typename T>
  static Getter CreateGetter(const T &var) {
    return [&]() -> py::object { return py::cast(var); };
  }

  template <typename T>
  static Setter CreateSetter(T *var) {
    return [var](const py::object &obj) { *var = py::cast<T>(obj); };
  }

 private:
  struct VarInfo {
    VarInfo(bool is_public, const Getter &getter)
        : is_public(is_public), getter(getter) {}

    VarInfo(bool is_public, const Getter &getter, const Setter &setter)
        : is_public(is_public), getter(getter), setter(setter) {}
142

143 144 145 146 147 148
    const bool is_public;
    const Getter getter;
    const Setter setter;
  };

 public:
149 150 151 152
  static const GlobalVarGetterSetterRegistry &Instance() { return instance_; }

  static GlobalVarGetterSetterRegistry *MutableInstance() { return &instance_; }

153
  void Register(const std::string &name, bool is_public, const Getter &getter) {
154
    PADDLE_ENFORCE_EQ(
155
        HasGetterMethod(name), false,
156 157
        platform::errors::AlreadyExists(
            "Getter of global variable %s has been registered", name));
158 159 160 161
    PADDLE_ENFORCE_NOT_NULL(getter,
                            platform::errors::InvalidArgument(
                                "Getter of %s should not be null", name));
    var_infos_.insert({name, VarInfo(is_public, getter)});
162 163
  }

164 165
  void Register(const std::string &name, bool is_public, const Getter &getter,
                const Setter &setter) {
166
    PADDLE_ENFORCE_EQ(
167 168 169
        HasGetterMethod(name), false,
        platform::errors::AlreadyExists(
            "Getter of global variable %s has been registered", name));
170 171

    PADDLE_ENFORCE_EQ(
172
        HasSetterMethod(name), false,
173 174
        platform::errors::AlreadyExists(
            "Setter of global variable %s has been registered", name));
175 176 177 178 179 180 181 182 183 184

    PADDLE_ENFORCE_NOT_NULL(getter,
                            platform::errors::InvalidArgument(
                                "Getter of %s should not be null", name));

    PADDLE_ENFORCE_NOT_NULL(setter,
                            platform::errors::InvalidArgument(
                                "Setter of %s should not be null", name));

    var_infos_.insert({name, VarInfo(is_public, getter, setter)});
185 186 187 188 189 190
  }

  const Getter &GetterMethod(const std::string &name) const {
    PADDLE_ENFORCE_EQ(
        HasGetterMethod(name), true,
        platform::errors::NotFound("Cannot find global variable %s", name));
191
    return var_infos_.at(name).getter;
192 193 194
  }

  py::object GetOrReturnDefaultValue(const std::string &name,
195
                                     const py::object &default_value) const {
196 197 198 199 200 201 202
    if (HasGetterMethod(name)) {
      return GetterMethod(name)();
    } else {
      return default_value;
    }
  }

203
  py::object Get(const std::string &name) const { return GetterMethod(name)(); }
204 205 206 207 208

  const Setter &SetterMethod(const std::string &name) const {
    PADDLE_ENFORCE_EQ(
        HasSetterMethod(name), true,
        platform::errors::NotFound("Global variable %s is not writable", name));
209
    return var_infos_.at(name).setter;
210 211 212 213 214 215 216
  }

  void Set(const std::string &name, const py::object &value) const {
    SetterMethod(name)(value);
  }

  bool HasGetterMethod(const std::string &name) const {
217
    return var_infos_.count(name) > 0;
218 219 220
  }

  bool HasSetterMethod(const std::string &name) const {
221 222 223 224 225
    return var_infos_.count(name) > 0 && var_infos_.at(name).setter;
  }

  bool IsPublic(const std::string &name) const {
    return var_infos_.count(name) > 0 && var_infos_.at(name).is_public;
226 227 228 229
  }

  std::unordered_set<std::string> Keys() const {
    std::unordered_set<std::string> keys;
230 231
    keys.reserve(var_infos_.size());
    for (auto &pair : var_infos_) {
232 233 234 235 236 237 238 239
      keys.insert(pair.first);
    }
    return keys;
  }

 private:
  static GlobalVarGetterSetterRegistry instance_;

240
  std::unordered_map<std::string, VarInfo> var_infos_;
241 242 243 244
};

GlobalVarGetterSetterRegistry GlobalVarGetterSetterRegistry::instance_;

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
class GlobalVarGetterSetterRegistryHelper {
 public:
  GlobalVarGetterSetterRegistryHelper(bool is_public, bool is_writable,
                                      const std::string &var_names)
      : is_public_(is_public),
        is_writable_(is_writable),
        var_names_(SplitVarNames(var_names)) {}

  template <typename... Args>
  void Register(Args &&... args) const {
    Impl<0, sizeof...(args) == 1, Args...>::Register(
        is_public_, is_writable_, var_names_, std::forward<Args>(args)...);
  }

 private:
  static std::vector<std::string> SplitVarNames(const std::string &names) {
    auto valid_char = [](char ch) { return !std::isspace(ch) && ch != ','; };

    std::vector<std::string> ret;
    size_t i = 0, j = 0, n = names.size();
    while (i < n) {
      for (; i < n && !valid_char(names[i]); ++i) {
      }
      for (j = i + 1; j < n && valid_char(names[j]); ++j) {
      }

      if (i < n && j <= n) {
        auto substring = names.substr(i, j - i);
        VLOG(10) << "Get substring: \"" << substring << "\"";
        ret.emplace_back(substring);
      }
      i = j + 1;
    }
    return ret;
  }

 private:
  template <size_t kIdx, bool kIsStop, typename T, typename... Args>
  struct Impl {
    static void Register(bool is_public, bool is_writable,
                         const std::vector<std::string> &var_names, T &&var,
                         Args &&... args) {
      PADDLE_ENFORCE_EQ(kIdx + 1 + sizeof...(args), var_names.size(),
                        platform::errors::InvalidArgument(
                            "Argument number not match name number"));
      Impl<kIdx, true, T>::Register(is_public, is_writable, var_names, var);
      Impl<kIdx + 1, sizeof...(Args) == 1, Args...>::Register(
          is_public, is_writable, var_names, std::forward<Args>(args)...);
    }
  };

  template <size_t kIdx, typename T>
  struct Impl<kIdx, true, T> {
    static void Register(bool is_public, bool is_writable,
                         const std::vector<std::string> &var_names, T &&var) {
      auto *instance = GlobalVarGetterSetterRegistry::MutableInstance();
      if (is_writable) {
        instance->Register(
            var_names[kIdx], is_public,
            GlobalVarGetterSetterRegistry::CreateGetter(std::forward<T>(var)),
            GlobalVarGetterSetterRegistry::CreateSetter(&var));
      } else {
        instance->Register(
            var_names[kIdx], is_public,
            GlobalVarGetterSetterRegistry::CreateGetter(std::forward<T>(var)));
      }
    }
  };

 private:
  const bool is_public_;
  const bool is_writable_;
  const std::vector<std::string> var_names_;
};

320 321 322 323 324 325 326 327 328 329 330
static void RegisterGlobalVarGetterSetter();

void BindGlobalValueGetterSetter(pybind11::module *module) {
  RegisterGlobalVarGetterSetter();

  py::class_<GlobalVarGetterSetterRegistry>(*module,
                                            "GlobalVarGetterSetterRegistry")
      .def("__getitem__", &GlobalVarGetterSetterRegistry::Get)
      .def("__setitem__", &GlobalVarGetterSetterRegistry::Set)
      .def("__contains__", &GlobalVarGetterSetterRegistry::HasGetterMethod)
      .def("keys", &GlobalVarGetterSetterRegistry::Keys)
331
      .def("is_public", &GlobalVarGetterSetterRegistry::IsPublic)
332 333 334 335 336 337 338
      .def("get", &GlobalVarGetterSetterRegistry::GetOrReturnDefaultValue,
           py::arg("key"), py::arg("default") = py::cast<py::none>(Py_None));

  module->def("globals", &GlobalVarGetterSetterRegistry::Instance,
              py::return_value_policy::reference);
}

339 340 341 342 343 344 345 346 347 348 349 350 351 352
/* Public vars are designed to be writable. */
#define REGISTER_PUBLIC_GLOBAL_VAR(...)                                        \
  do {                                                                         \
    GlobalVarGetterSetterRegistryHelper(/*is_public=*/true,                    \
                                        /*is_writable=*/true, "" #__VA_ARGS__) \
        .Register(__VA_ARGS__);                                                \
  } while (0)

#define REGISTER_PRIVATE_GLOBAL_VAR(is_writable, ...)                     \
  do {                                                                    \
    GlobalVarGetterSetterRegistryHelper(/*is_public=*/false, is_writable, \
                                        "" #__VA_ARGS__)                  \
        .Register(__VA_ARGS__);                                           \
  } while (0)
353

354
static void RegisterGlobalVarGetterSetter() {
355
  REGISTER_PRIVATE_GLOBAL_VAR(/*is_writable=*/false, FLAGS_free_idle_chunk,
356
                              FLAGS_free_when_no_cache_hit);
357

358 359
  REGISTER_PUBLIC_GLOBAL_VAR(
      FLAGS_eager_delete_tensor_gb, FLAGS_enable_parallel_graph,
G
guofei 已提交
360
      FLAGS_allocator_strategy, FLAGS_use_system_allocator, FLAGS_check_nan_inf,
361
      FLAGS_call_stack_level, FLAGS_sort_sum_gradient, FLAGS_cpu_deterministic,
362 363 364 365 366 367 368
      FLAGS_enable_rpc_profiler, FLAGS_multiple_of_cupti_buffer_size,
      FLAGS_reader_queue_speed_test_mode, FLAGS_pe_profile_fname,
      FLAGS_print_sub_graph_dir, FLAGS_fraction_of_cpu_memory_to_use,
      FLAGS_fuse_parameter_groups_size, FLAGS_fuse_parameter_memory_size,
      FLAGS_init_allocated_mem, FLAGS_initial_cpu_memory_in_mb,
      FLAGS_memory_fraction_of_eager_deletion, FLAGS_use_pinned_memory,
      FLAGS_benchmark, FLAGS_inner_op_parallelism, FLAGS_tracer_profile_fname,
369 370
      FLAGS_paddle_num_threads, FLAGS_use_mkldnn, FLAGS_max_inplace_grad_add,
      FLAGS_tracer_mkldnn_ops_on, FLAGS_tracer_mkldnn_ops_off);
371

372
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
G
guofei 已提交
373 374 375 376 377 378 379 380
  REGISTER_PUBLIC_GLOBAL_VAR(
      FLAGS_gpu_memory_limit_mb, FLAGS_cudnn_deterministic,
      FLAGS_conv_workspace_size_limit, FLAGS_cudnn_batchnorm_spatial_persistent,
      FLAGS_cudnn_exhaustive_search, FLAGS_eager_delete_scope,
      FLAGS_fast_eager_deletion_mode,
      FLAGS_fraction_of_cuda_pinned_memory_to_use,
      FLAGS_fraction_of_gpu_memory_to_use, FLAGS_initial_gpu_memory_in_mb,
      FLAGS_reallocate_gpu_memory_in_mb, FLAGS_enable_cublas_tensor_op_math,
381
      FLAGS_selected_gpus, FLAGS_sync_nccl_allreduce,
382
      FLAGS_conv2d_disable_cudnn, FLAGS_check_kernel_launch);
G
guofei 已提交
383
#endif
384 385 386
#ifdef PADDLE_WITH_XPU
  REGISTER_PUBLIC_GLOBAL_VAR(FLAGS_selected_xpus);
#endif
387 388 389

#ifdef PADDLE_WITH_ASCEND_CL
  REGISTER_PUBLIC_GLOBAL_VAR(FLAGS_selected_npus);
390
  REGISTER_PUBLIC_GLOBAL_VAR(FLAGS_min_loss_scaling);
391 392
#endif

G
guofei 已提交
393 394 395 396
#ifdef PADDLE_WITH_DITRIBUTE
  REGISTER_PUBLIC_GLOBAL_VAR(FLAGS_rpc_send_thread_num,
                             FLAGS_rpc_get_thread_num,
                             FLAGS_rpc_prefetch_thread_num);
397
#endif
398 399 400
}
}  // namespace pybind
}  // namespace paddle