common_dense_table.cc 13.7 KB
Newer Older
T
tangwei12 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2020 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.

15
#include "paddle/fluid/distributed/ps/table/common_dense_table.h"
16 17

#include "paddle/fluid/platform/enforce.h"
T
tangwei12 已提交
18 19 20 21

namespace paddle {
namespace distributed {

Z
zhaocaibei123 已提交
22 23
int FLAGS_pslib_table_save_max_retry_dense = 3;

Z
zhaocaibei123 已提交
24 25
void CommonDenseTable::CreateInitializer(const std::string& attr,
                                         const std::string& name) {
T
tangwei12 已提交
26 27 28 29 30 31 32 33
  auto slices = string::split_string<std::string>(attr, "&");

  if (slices[0] == "gaussian_random") {
    initializers_[name] = new GaussianInitializer(slices);
  } else if (slices[0] == "fill_constant") {
    initializers_[name] = new FillConstantInitializer(slices);
  } else if (slices[0] == "uniform_random") {
    initializers_[name] = new UniformInitializer(slices);
C
Chengmo 已提交
34 35
  } else if (slices[0] == "truncated_gaussian_random") {
    initializers_[name] = new TruncatedGaussianInitializer(slices);
T
tangwei12 已提交
36 37 38 39 40 41
  } else {
    PADDLE_THROW(
        platform::errors::InvalidArgument("%s can not be supported", name));
  }
}

Z
zhaocaibei123 已提交
42
int32_t CommonDenseTable::Initialize() {
T
tangwei12 已提交
43 44 45 46 47 48 49
  _shards_task_pool.resize(task_pool_size_);
  for (int i = 0; i < _shards_task_pool.size(); ++i) {
    _shards_task_pool[i].reset(new ::ThreadPool(1));
  }

  sync = _config.common().sync();
  VLOG(1) << "table " << _config.common().table_name() << " is sync: " << sync;
50
  _global_lr = new float(1.0);
T
tangwei12 已提交
51

Z
zhaocaibei123 已提交
52 53
  InitializeValue();
  InitializeOptimizer();
T
tangwei12 已提交
54 55 56
  return 0;
}

Z
zhaocaibei123 已提交
57
int32_t CommonDenseTable::InitializeValue() {
T
tangwei12 已提交
58 59 60
  auto common = _config.common();
  int size = static_cast<int>(common.params().size());
  values_.resize(size);
Z
zhaocaibei123 已提交
61
  total_dim_ = 0;
T
tangwei12 已提交
62 63 64 65 66 67 68
  for (int x = 0; x < size; ++x) {
    auto& varname = common.params()[x];
    auto& dim = common.dims()[x];
    if (varname == "Param") {
      param_dim_ = dim;
      param_idx_ = x;
    }
Z
zhaocaibei123 已提交
69

T
tangwei12 已提交
70
    auto& initializer = common.initializers()[x];
Z
zhaocaibei123 已提交
71
    total_dim_ += dim;
T
tangwei12 已提交
72

Z
zhaocaibei123 已提交
73
    CreateInitializer(initializer, varname);
T
tangwei12 已提交
74 75 76 77 78 79 80 81
    values_[x].resize(dim);
    names_index_[varname] = x;

    for (int y = 0; y < dim; ++y) {
      values_[x][y] = initializers_[varname]->GetValue();
    }
  }

Z
zhaocaibei123 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94
  fixed_len_params_dim_ = 0;
  for (int x = 0; x < size; ++x) {
    auto& dim = common.dims()[x];
    if (dim != param_dim_) {
      fixed_len_params_dim_ += dim;
    } else {
      param_col_ids_.push_back(x);
    }
  }
  if (_config.common().name() == "adam_d2sum") {
    param_col_ids_.insert(param_col_ids_.begin() + 1, -1);
  }

Z
zhaocaibei123 已提交
95
  VLOG(1) << "CommonDenseTable::InitializeValue total dim: " << total_dim_
Z
zhaocaibei123 已提交
96 97
          << " fixed_len_params_dim: " << fixed_len_params_dim_;

T
tangwei12 已提交
98 99 100 101
  pull_reservoir_ = ReservoirValue<float>(param_dim_);
  return 0;
}

Z
zhaocaibei123 已提交
102
int32_t CommonDenseTable::InitializeOptimizer() {
T
tangwei12 已提交
103 104 105 106 107 108
  auto common = _config.common();
  auto name = common.name();
  auto attrs = common.attributes();

  if (name == "sgd") {
    optimizer_ = std::make_shared<DSGD>(common, &values_);
Z
zhaocaibei123 已提交
109
    optimizer_->SetGlobalLR(_global_lr);
T
tangwei12 已提交
110 111
  } else if (name == "adam") {
    optimizer_ = std::make_shared<DAdam>(common, &values_);
Z
zhaocaibei123 已提交
112
    optimizer_->SetGlobalLR(_global_lr);
Z
zhaocaibei123 已提交
113 114
  } else if (name == "adam_d2sum") {
    optimizer_ = std::make_shared<DAdamD2Sum>(common, &values_);
Z
zhaocaibei123 已提交
115
    // optimizer_->SetGlobalLR(_global_lr);  //no use
T
tangwei12 已提交
116 117
  } else if (name == "sum") {
    optimizer_ = std::make_shared<DSUM>(common, &values_);
118 119
  } else if (name == "summary") {
    optimizer_ = std::make_shared<DSummary>(common, &values_);
T
tangwei12 已提交
120 121 122
  } else {
    VLOG(0) << "init optimizer failed";
  }
123
  VLOG(3) << "init optimizer " << name << " done";
T
tangwei12 已提交
124 125 126
  return 0;
}

Z
zhaocaibei123 已提交
127
int32_t CommonDenseTable::SetGlobalLR(float* lr) {
128
  _global_lr = lr;
Z
zhaocaibei123 已提交
129
  optimizer_->SetGlobalLR(_global_lr);
130 131 132
  return 0;
}

Y
yaoxuefeng 已提交
133 134 135
int32_t CommonDenseTable::Pull(TableContext& context) {
  CHECK(context.value_type == Dense);
  float* pull_values = context.pull_context.values;
Z
zhaocaibei123 已提交
136
  return PullDense(pull_values, context.num);
Y
yaoxuefeng 已提交
137 138 139 140
}

int32_t CommonDenseTable::Push(TableContext& context) {
  CHECK(context.value_type == Dense);
141
  if (context.push_context.values != nullptr) {
Y
yaoxuefeng 已提交
142
    const float* values = context.push_context.values;
Z
zhaocaibei123 已提交
143
    return PushDense(values, context.num);
Y
yaoxuefeng 已提交
144 145 146 147
  }
  return 0;
}

Z
zhaocaibei123 已提交
148
int32_t CommonDenseTable::PullDense(float* pull_values, size_t num) {
T
tangwei12 已提交
149 150 151 152 153
  std::copy(values_[param_idx_].begin(), values_[param_idx_].end(),
            pull_values);
  return 0;
}

Z
zhaocaibei123 已提交
154
int32_t CommonDenseTable::PushDenseParam(const float* values, size_t num) {
T
tangwei12 已提交
155 156 157 158 159 160 161 162
  PADDLE_ENFORCE_GE(
      num, param_dim_,
      paddle::platform::errors::InvalidArgument(
          "update desne param numel expected %d, but got %d", param_dim_, num));
  std::copy_n(values, param_dim_, values_[param_idx_].begin());
  return 0;
}

Z
zhaocaibei123 已提交
163
int32_t CommonDenseTable::Pour() {
T
tangwei12 已提交
164
  pull_reservoir_.avg();
Z
zhaocaibei123 已提交
165
  _PushDense(pull_reservoir_.values.data(), pull_reservoir_.values.size());
T
tangwei12 已提交
166 167 168 169
  pull_reservoir_.reset();
  return 0;
}

Z
zhaocaibei123 已提交
170
int32_t CommonDenseTable::PushDense(const float* values, size_t num) {
T
tangwei12 已提交
171 172 173 174 175 176 177 178
  if (sync) {
    std::future<int> task =
        _shards_task_pool[0]->enqueue([this, &values]() -> int {
          pull_reservoir_.add(values, param_dim_);
          return 0;
        });
    task.wait();
  } else {
Z
zhaocaibei123 已提交
179
    _PushDense(values, num);
T
tangwei12 已提交
180 181 182 183
  }
  return 0;
}

Z
zhaocaibei123 已提交
184
int32_t CommonDenseTable::_PushDense(const float* values, size_t num) {
T
tangwei12 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197
  PADDLE_ENFORCE_GE(
      num, param_dim_,
      paddle::platform::errors::InvalidArgument(
          "update desne numel expected %d, but got %d", param_dim_, num));

  std::vector<int> buckets = bucket(param_dim_, task_pool_size_);
  std::vector<std::future<int>> tasks(task_pool_size_);

  for (int shard_id = 0; shard_id < task_pool_size_; ++shard_id) {
    tasks[shard_id] = _shards_task_pool[shard_id]->enqueue(
        [this, shard_id, &buckets, &values]() -> int {
          auto begin = buckets[shard_id];
          auto end = buckets[shard_id + 1];
Z
zhaocaibei123 已提交
198
          optimizer_->Update(values, param_dim_, begin, end);
T
tangwei12 已提交
199 200 201 202 203 204 205
          return 0;
        });
  }

  for (size_t shard_id = 0; shard_id < tasks.size(); ++shard_id) {
    tasks[shard_id].wait();
  }
Z
zhaocaibei123 已提交
206 207 208 209
  VLOG(2) << "debug CommonDenseTable::_push_dense done";
  return 0;
}

Z
zhaocaibei123 已提交
210
int32_t CommonDenseTable::Load(const std::string& path,
Z
zhaocaibei123 已提交
211 212 213 214
                               const std::string& param) {
  if (param_dim_ <= 0) {
    return 0;
  }
Z
zhaocaibei123 已提交
215
  std::string table_path = TableDir(path);
Z
zhaocaibei123 已提交
216 217 218 219 220 221 222
  auto file_list = _afs_client.list(table_path);
  std::sort(file_list.begin(), file_list.end());
  for (auto ff : file_list) {
    VLOG(1) << "load dense table file list: " << ff;
  }
  size_t dim_num_per_file = _config.accessor().fea_dim() / file_list.size() + 1;
  // param_dim_ in last node != _config.accesor().fea_dim() / _shard_num + 1
223
  size_t dim_num_per_shard = _table_info.fea_dim / _shard_num + 1;
Z
zhaocaibei123 已提交
224 225 226 227 228 229 230 231 232 233 234
  size_t start_dim_idx = dim_num_per_shard * _shard_idx;
  size_t start_file_idx = start_dim_idx / dim_num_per_file;
  size_t end_file_idx = (start_dim_idx + param_dim_) / dim_num_per_file;
  end_file_idx =
      end_file_idx < file_list.size() ? end_file_idx : file_list.size() - 1;
  VLOG(2) << "load dense table start_file_idx: " << start_file_idx
          << " end_file_idx: " << end_file_idx;

  int load_param = atoi(param.c_str());
  FsChannelConfig channel_config;

235
  channel_config.converter = _value_accesor->Converter(load_param).converter;
Z
zhaocaibei123 已提交
236
  channel_config.deconverter =
237
      _value_accesor->Converter(load_param).deconverter;
Z
zhaocaibei123 已提交
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
  bool is_read_failed = false;
  int err_no = 0;
  int retry_num = 0;
  do {
    is_read_failed = false;
    try {
      size_t dim_idx = 0;
      float data_buffer[5];
      float* data_buff_ptr = data_buffer;
      std::string line_data;
      int size = static_cast<int>(values_.size());
      auto common = _config.common();

      for (int i = start_file_idx; i < end_file_idx + 1; ++i) {
        channel_config.path = file_list[i];
        err_no = 0;
        auto read_channel = _afs_client.open_r(channel_config, 0, &err_no);
        size_t file_start_idx = start_dim_idx - i * dim_num_per_file;

        // not all file contains param and the length of last file containing
        // param may not equal to others
        size_t file_dim_idx = 0;
        for (; file_dim_idx < dim_num_per_file; ++file_dim_idx) {
          if (read_channel->read_line(line_data) != 0) {
            break;
          }
          if (dim_idx >= param_dim_) {
            break;
          }
          if (file_dim_idx < file_start_idx) {
            continue;
          }
          auto str_len =
              paddle::string::str_to_float(line_data.data(), data_buff_ptr);
          CHECK(str_len == param_col_ids_.size())
              << "expect " << param_col_ids_.size() << " float, but got "
              << str_len;
          for (size_t col_idx = 0; col_idx < str_len; ++col_idx) {
            if (param_col_ids_[col_idx] < 0) {
              continue;
            }
            values_[param_col_ids_[col_idx]][dim_idx] = data_buffer[col_idx];
            VLOG(2) << "CommonDenseTable::load param x: "
                    << param_col_ids_[col_idx] << " y: " << dim_idx
                    << " value: " << values_[param_col_ids_[col_idx]][dim_idx]
                    << " line " << file_dim_idx;
          }
          ++dim_idx;
        }
        read_channel->close();
        VLOG(1) << "DownpourDenseTable load done " << channel_config.path
                << " file_start_idx: " << file_start_idx
                << " dim_idx: " << dim_idx;
        if (err_no == -1) {
          if (retry_num > FLAGS_pslib_table_save_max_retry_dense) {
            LOG(ERROR) << "DownpourDenseTable load failed reach max limit!";
            exit(-1);
          }
          ++retry_num;
          --i;
          LOG(ERROR)
              << "DownpourDenseTable load failed after read , retry it! path:"
              << channel_config.path << ", retry_num=" << retry_num;
          continue;
        }
        retry_num = 0;
        start_dim_idx += file_dim_idx - file_start_idx;
        LOG(INFO) << "DownpourDenseTable load success, path:"
                  << channel_config.path;
      }
    } catch (...) {
      is_read_failed = true;
      LOG(ERROR) << "DownpourDenseTable load failed, retry it! path:"
                 << channel_config.path;
    }
  } while (is_read_failed);
T
tangwei12 已提交
314 315 316
  return 0;
}

Z
zhaocaibei123 已提交
317
int32_t CommonDenseTable::Save(const std::string& path,
Z
zhaocaibei123 已提交
318 319 320 321 322 323 324 325
                               const std::string& param) {
  int save_param = atoi(param.c_str());
  uint32_t feasign_size;
  VLOG(0) << "CommonDenseTable::save path " << path;

  FsChannelConfig channel_config;
  if (_config.compress_in_save()) {
    channel_config.path = paddle::string::format_string(
Z
zhaocaibei123 已提交
326
        "%s/part-%03d.gz", TableDir(path).c_str(), _shard_idx);
Z
zhaocaibei123 已提交
327 328
  } else {
    channel_config.path = paddle::string::format_string(
Z
zhaocaibei123 已提交
329
        "%s/part-%03d", TableDir(path).c_str(), _shard_idx);
Z
zhaocaibei123 已提交
330 331
  }
  _afs_client.remove(channel_config.path);
332
  channel_config.converter = _value_accesor->Converter(save_param).converter;
Z
zhaocaibei123 已提交
333
  channel_config.deconverter =
334
      _value_accesor->Converter(save_param).deconverter;
Z
zhaocaibei123 已提交
335 336 337 338 339 340 341 342 343

  bool is_write_failed = false;
  std::vector<std::vector<std::string>> result_buffer_param(
      param_dim_, std::vector<std::string>());
  std::vector<std::string> result_buffer_fixed_len;
  result_buffer_fixed_len.reserve(fixed_len_params_dim_);

  auto common = _config.common();
  int size = static_cast<int>(common.params().size());
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
  if (_config.common().name() == "summary") {
    for (int x = 0; x < param_dim_; ++x) {
      result_buffer_param[x].emplace_back(
          std::to_string(values_[param_idx_][x]));
    }

  } else {
    std::ostringstream os;
    for (int x = 0; x < size; ++x) {
      auto& varname = common.params()[x];
      auto& dim = common.dims()[x];
      VLOG(3) << "CommonDenseTable::save dim " << x << " size: " << dim;
      for (int y = 0; y < dim; ++y) {
        os.clear();
        os.str("");
        os << values_[x][y];
        if (dim == param_dim_) {
          result_buffer_param[y].emplace_back(std::move(os.str()));
        } else {
          result_buffer_fixed_len.emplace_back(std::move(os.str()));
        }
Z
zhaocaibei123 已提交
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 407 408 409 410 411 412 413 414
      }
    }
  }

  int retry_num = 0;
  int err_no = 0;
  do {
    err_no = 0;
    is_write_failed = false;
    feasign_size = 0;
    // 40M
    auto write_channel =
        _afs_client.open_w(channel_config, 1024 * 1024 * 40, &err_no);
    for (auto& t : result_buffer_param) {
      if (_config.common().name() == "adam_d2sum") {
        t.insert(t.begin() + 1, "0");  // avg_w
      }
      if (0 !=
          write_channel->write_line(paddle::string::join_strings(t, ' '))) {
        ++retry_num;
        is_write_failed = true;
        LOG(ERROR) << "DownpourDenseTable save failed, retry it! "
                      "path:"
                   << channel_config.path << ", retry_num=" << retry_num;
        break;
      }
    }

    ++feasign_size;
    write_channel->close();
    if (err_no == -1) {
      ++retry_num;
      is_write_failed = true;
      LOG(ERROR) << "DownpourDenseTable save failed after write, retry it! "
                 << "path:" << channel_config.path
                 << ", retry_num=" << retry_num;
    }
    if (is_write_failed) {
      _afs_client.remove(channel_config.path);
    }
    if (retry_num >
        paddle::distributed::FLAGS_pslib_table_save_max_retry_dense) {
      LOG(ERROR) << "DownpourDenseTable save failed reach max limit!";
      exit(-1);
    }
  } while (is_write_failed);
  LOG(INFO) << "DownpourDenseTable save success, path:" << channel_config.path;
  return feasign_size;
}

T
tangwei12 已提交
415 416
}  // namespace distributed
}  // namespace paddle