common_dense_table.cc 13.8 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) {
142 143 144 145 146
    if (!context.push_context.is_param) {
      return PushDense(context.push_context.values, context.num);
    } else {
      return PushDenseParam(context.push_context.values, context.num);
    }
Y
yaoxuefeng 已提交
147 148 149 150
  }
  return 0;
}

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

Z
zhaocaibei123 已提交
157
int32_t CommonDenseTable::PushDenseParam(const float* values, size_t num) {
T
tangwei12 已提交
158 159 160 161 162 163 164 165
  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 已提交
166
int32_t CommonDenseTable::Pour() {
T
tangwei12 已提交
167
  pull_reservoir_.avg();
Z
zhaocaibei123 已提交
168
  _PushDense(pull_reservoir_.values.data(), pull_reservoir_.values.size());
T
tangwei12 已提交
169 170 171 172
  pull_reservoir_.reset();
  return 0;
}

Z
zhaocaibei123 已提交
173
int32_t CommonDenseTable::PushDense(const float* values, size_t num) {
T
tangwei12 已提交
174 175 176 177 178 179 180 181
  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 已提交
182
    _PushDense(values, num);
T
tangwei12 已提交
183 184 185 186
  }
  return 0;
}

Z
zhaocaibei123 已提交
187
int32_t CommonDenseTable::_PushDense(const float* values, size_t num) {
T
tangwei12 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200
  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 已提交
201
          optimizer_->Update(values, param_dim_, begin, end);
T
tangwei12 已提交
202 203 204 205 206 207 208
          return 0;
        });
  }

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

Z
zhaocaibei123 已提交
213
int32_t CommonDenseTable::Load(const std::string& path,
Z
zhaocaibei123 已提交
214 215 216 217
                               const std::string& param) {
  if (param_dim_ <= 0) {
    return 0;
  }
Z
zhaocaibei123 已提交
218
  std::string table_path = TableDir(path);
Z
zhaocaibei123 已提交
219 220 221 222 223 224 225
  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
226 227
  size_t dim_num_per_shard =
      _value_accesor->GetAccessorInfo().fea_dim / _shard_num + 1;
Z
zhaocaibei123 已提交
228 229 230 231 232 233 234 235 236 237 238
  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;

239
  channel_config.converter = _value_accesor->Converter(load_param).converter;
Z
zhaocaibei123 已提交
240
  channel_config.deconverter =
241
      _value_accesor->Converter(load_param).deconverter;
Z
zhaocaibei123 已提交
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
  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 已提交
318 319 320
  return 0;
}

Z
zhaocaibei123 已提交
321
int32_t CommonDenseTable::Save(const std::string& path,
Z
zhaocaibei123 已提交
322 323 324 325 326 327 328 329
                               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 已提交
330
        "%s/part-%03d.gz", TableDir(path).c_str(), _shard_idx);
Z
zhaocaibei123 已提交
331 332
  } else {
    channel_config.path = paddle::string::format_string(
Z
zhaocaibei123 已提交
333
        "%s/part-%03d", TableDir(path).c_str(), _shard_idx);
Z
zhaocaibei123 已提交
334 335
  }
  _afs_client.remove(channel_config.path);
336
  channel_config.converter = _value_accesor->Converter(save_param).converter;
Z
zhaocaibei123 已提交
337
  channel_config.deconverter =
338
      _value_accesor->Converter(save_param).deconverter;
Z
zhaocaibei123 已提交
339 340 341 342 343 344 345 346 347

  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());
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
  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 已提交
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 415 416 417 418
      }
    }
  }

  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 已提交
419 420
}  // namespace distributed
}  // namespace paddle