memory_sparse_table.cc 40.8 KB
Newer Older
Z
zhaocaibei123 已提交
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 <omp.h>
16
#include <sstream>
Z
zhaocaibei123 已提交
17 18

#include "glog/logging.h"
19
#include "paddle/fluid/distributed/common/cost_timer.h"
Z
zhaocaibei123 已提交
20 21 22 23
#include "paddle/fluid/distributed/common/local_random.h"
#include "paddle/fluid/distributed/common/topk_calculator.h"
#include "paddle/fluid/distributed/ps/table/memory_sparse_table.h"
#include "paddle/fluid/framework/archive.h"
24
#include "paddle/fluid/framework/io/fs.h"
Z
zhaocaibei123 已提交
25 26

// #include "boost/lexical_cast.hpp"
Z
zhaocaibei123 已提交
27 28
#include "paddle/fluid/platform/enforce.h"

29 30
DEFINE_bool(pserver_print_missed_key_num_every_push,
            false,
Z
zhaocaibei123 已提交
31
            "pserver_print_missed_key_num_every_push");
32 33
DEFINE_bool(pserver_create_value_when_push,
            true,
Z
zhaocaibei123 已提交
34
            "pserver create value when push");
35 36
DEFINE_bool(pserver_enable_create_feasign_randomly,
            false,
Z
zhaocaibei123 已提交
37 38 39
            "pserver_enable_create_feasign_randomly");
DEFINE_int32(pserver_table_save_max_retry, 3, "pserver_table_save_max_retry");

Z
zhaocaibei123 已提交
40 41 42
namespace paddle {
namespace distributed {

Z
zhaocaibei123 已提交
43
int32_t MemorySparseTable::Initialize() {
44 45 46
  auto& profiler = CostProfiler::instance();
  profiler.register_profiler("pserver_sparse_update_all");
  profiler.register_profiler("pserver_sparse_select_all");
Z
zhaocaibei123 已提交
47
  InitializeValue();
D
danleifeng 已提交
48 49 50 51
  _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));
  }
Z
zhaocaibei123 已提交
52 53 54 55
  VLOG(0) << "initalize MemorySparseTable succ";
  return 0;
}

Z
zhaocaibei123 已提交
56
int32_t MemorySparseTable::InitializeValue() {
57 58
  _sparse_table_shard_num = static_cast<int>(_config.shard_num());
  _avg_local_shard_num =
59
      sparse_local_shard_num(_sparse_table_shard_num, _shard_num);
60
  _real_local_shard_num = _avg_local_shard_num;
Z
zhangchunle 已提交
61 62
  if (static_cast<int>(_real_local_shard_num * (_shard_idx + 1)) >
      _sparse_table_shard_num) {
63 64 65 66
    _real_local_shard_num =
        _sparse_table_shard_num - _real_local_shard_num * _shard_idx;
    _real_local_shard_num =
        _real_local_shard_num < 0 ? 0 : _real_local_shard_num;
Z
zhaocaibei123 已提交
67
  }
D
danleifeng 已提交
68 69 70
#ifdef PADDLE_WITH_HETERPS
  _task_pool_size = _sparse_table_shard_num;
#endif
71 72
  VLOG(1) << "memory sparse table _avg_local_shard_num: "
          << _avg_local_shard_num
D
danleifeng 已提交
73 74
          << " _real_local_shard_num: " << _real_local_shard_num
          << " _task_pool_size:" << _task_pool_size;
Z
zhaocaibei123 已提交
75

76
  _local_shards.reset(new shard_type[_real_local_shard_num]);
Z
zhaocaibei123 已提交
77

Z
zhaocaibei123 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
  if (_config.enable_revert()) {
    // calculate merged shard number based on config param;
    _shard_merge_rate = _config.has_shard_merge_rate()
                            ? _config.shard_merge_rate()
                            : _shard_merge_rate;
    CHECK((_m_avg_local_shard_num = static_cast<int>(
               std::ceil(_avg_local_shard_num * _shard_merge_rate)),
           _m_avg_local_shard_num <= _avg_local_shard_num));
    CHECK((_m_real_local_shard_num = static_cast<int>(
               std::ceil(_real_local_shard_num * _shard_merge_rate)),
           _m_real_local_shard_num <= _real_local_shard_num));

    uint32_t avg_shard_server_num =
        _sparse_table_shard_num / _avg_local_shard_num;
    uint32_t last_server_shard_num =
        _sparse_table_shard_num - avg_shard_server_num * _avg_local_shard_num;
    _m_sparse_table_shard_num =
        avg_shard_server_num * _m_avg_local_shard_num +
        std::ceil(last_server_shard_num * _shard_merge_rate);
    LOG(INFO) << "merged shard info: [" << _m_sparse_table_shard_num << "|"
              << _m_avg_local_shard_num << "|" << _m_real_local_shard_num
              << "]";
    _local_shards_new.reset(new shard_type[_real_local_shard_num]);
  }
Z
zhaocaibei123 已提交
102 103 104
  return 0;
}

Z
zhaocaibei123 已提交
105
int32_t MemorySparseTable::Load(const std::string& path,
Z
zhaocaibei123 已提交
106
                                const std::string& param) {
Z
zhaocaibei123 已提交
107
  std::string table_path = TableDir(path);
Z
zhaocaibei123 已提交
108 109 110 111
  auto file_list = _afs_client.list(table_path);

  std::sort(file_list.begin(), file_list.end());
  for (auto file : file_list) {
Z
zhaocaibei123 已提交
112
    VLOG(1) << "MemorySparseTable::Load() file list: " << file;
Z
zhaocaibei123 已提交
113 114 115
  }

  int load_param = atoi(param.c_str());
116
  size_t expect_shard_num = _sparse_table_shard_num;
Z
zhaocaibei123 已提交
117 118 119 120 121 122 123 124 125 126
  if (file_list.size() != expect_shard_num) {
    LOG(WARNING) << "MemorySparseTable file_size:" << file_list.size()
                 << " not equal to expect_shard_num:" << expect_shard_num;
    return -1;
  }
  if (file_list.size() == 0) {
    LOG(WARNING) << "MemorySparseTable load file is empty, path:" << path;
    return -1;
  }

Z
zhaocaibei123 已提交
127 128 129 130
  if (load_param == 5) {
    return LoadPatch(file_list, load_param);
  }

131
  size_t file_start_idx = _shard_idx * _avg_local_shard_num;
Z
zhaocaibei123 已提交
132

Z
zhaocaibei123 已提交
133 134 135 136
  if (file_start_idx >= file_list.size()) {
    return 0;
  }

137
  size_t feature_value_size =
138
      _value_accesor->GetAccessorInfo().size / sizeof(float);
139 140 141 142

  int thread_num = _real_local_shard_num < 15 ? _real_local_shard_num : 15;
  omp_set_num_threads(thread_num);
#pragma omp parallel for schedule(dynamic)
143
  for (int i = 0; i < _real_local_shard_num; ++i) {
Z
zhaocaibei123 已提交
144 145 146 147
    FsChannelConfig channel_config;
    channel_config.path = file_list[file_start_idx + i];
    VLOG(1) << "MemorySparseTable::load begin load " << channel_config.path
            << " into local shard " << i;
148
    channel_config.converter = _value_accesor->Converter(load_param).converter;
Z
zhaocaibei123 已提交
149
    channel_config.deconverter =
150
        _value_accesor->Converter(load_param).deconverter;
Z
zhaocaibei123 已提交
151 152 153 154 155 156 157 158 159 160

    bool is_read_failed = false;
    int retry_num = 0;
    int err_no = 0;
    do {
      is_read_failed = false;
      err_no = 0;
      std::string line_data;
      auto read_channel = _afs_client.open_r(channel_config, 0, &err_no);
      char* end = NULL;
161
      auto& shard = _local_shards[i];
Z
zhaocaibei123 已提交
162 163 164 165
      try {
        while (read_channel->read_line(line_data) == 0 &&
               line_data.size() > 1) {
          uint64_t key = std::strtoul(line_data.data(), &end, 10);
166 167
          auto& value = shard[key];
          value.resize(feature_value_size);
168
          int parse_size = _value_accesor->ParseFromString(++end, value.data());
169
          value.resize(parse_size);
Z
zhaocaibei123 已提交
170 171 172 173

          // for debug
          for (int ii = 0; ii < parse_size; ++ii) {
            VLOG(2) << "MemorySparseTable::load key: " << key << " value " << ii
174
                    << ": " << value.data()[ii] << " local_shard: " << i;
Z
zhaocaibei123 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
          }
        }
        read_channel->close();
        if (err_no == -1) {
          ++retry_num;
          is_read_failed = true;
          LOG(ERROR)
              << "MemorySparseTable load failed after read, retry it! path:"
              << channel_config.path << " , retry_num=" << retry_num;
        }
      } catch (...) {
        ++retry_num;
        is_read_failed = true;
        LOG(ERROR) << "MemorySparseTable load failed, retry it! path:"
                   << channel_config.path << " , retry_num=" << retry_num;
      }
Z
zhaocaibei123 已提交
191
      if (retry_num > FLAGS_pserver_table_save_max_retry) {
Z
zhaocaibei123 已提交
192 193 194 195 196 197 198
        LOG(ERROR) << "MemorySparseTable load failed reach max limit!";
        exit(-1);
      }
    } while (is_read_failed);
  }
  LOG(INFO) << "MemorySparseTable load success, path from "
            << file_list[file_start_idx] << " to "
199
            << file_list[file_start_idx + _real_local_shard_num - 1];
Z
zhaocaibei123 已提交
200 201 202
  return 0;
}

Z
zhaocaibei123 已提交
203 204 205 206 207
int32_t MemorySparseTable::LoadPatch(const std::vector<std::string>& file_list,
                                     int load_param) {
  if (!_config.enable_revert()) {
    LOG(INFO) << "MemorySparseTable should be enabled revert.";
    return 0;
Z
zhaocaibei123 已提交
208
  }
Z
zhaocaibei123 已提交
209 210 211 212 213 214 215 216 217
  // 聚合分片数据索引
  int start_idx = _shard_idx * _m_avg_local_shard_num;
  int end_idx = start_idx + _m_real_local_shard_num;
  // 原始分片数据索引
  int o_start_idx = _shard_idx * _avg_local_shard_num;
  int o_end_idx = o_start_idx + _real_local_shard_num;

  if (start_idx >= file_list.size()) {
    return 0;
Z
zhaocaibei123 已提交
218
  }
219
  size_t feature_value_size =
220
      _value_accesor->GetAccessorInfo().size / sizeof(float);
Z
zhaocaibei123 已提交
221 222 223
  end_idx =
      end_idx < _m_sparse_table_shard_num ? end_idx : _m_sparse_table_shard_num;
  int thread_num = (end_idx - start_idx) < 15 ? (end_idx - start_idx) : 15;
Z
zhaocaibei123 已提交
224

225 226
  omp_set_num_threads(thread_num);
#pragma omp parallel for schedule(dynamic)
Z
zhaocaibei123 已提交
227 228 229 230 231 232 233
  for (size_t i = start_idx; i < end_idx; ++i) {
    FsChannelConfig channel_config;
    channel_config.path = file_list[i];
    channel_config.converter = _value_accesor->Converter(load_param).converter;
    channel_config.deconverter =
        _value_accesor->Converter(load_param).deconverter;

Z
zhaocaibei123 已提交
234 235 236 237 238 239 240
    bool is_read_failed = false;
    int retry_num = 0;
    int err_no = 0;
    do {
      is_read_failed = false;
      err_no = 0;
      std::string line_data;
Z
zhaocaibei123 已提交
241
      auto read_channel = _afs_client.open_r(channel_config, 0, &err_no);
Z
zhaocaibei123 已提交
242
      char* end = NULL;
Z
zhaocaibei123 已提交
243 244 245 246 247 248 249 250 251 252
      int m_local_shard_id = i % _m_avg_local_shard_num;
      std::unordered_set<size_t> global_shard_idx;
      std::string global_shard_idx_str;
      for (size_t j = o_start_idx; j < o_end_idx; ++j) {
        if ((j % _avg_local_shard_num) % _m_real_local_shard_num ==
            m_local_shard_id) {
          global_shard_idx.insert(j);
          global_shard_idx_str.append(std::to_string(j)).append(",");
        }
      }
Z
zhaocaibei123 已提交
253
      try {
Z
zhaocaibei123 已提交
254 255
        while (read_channel->read_line(line_data) == 0 &&
               line_data.size() > 1) {
Z
zhaocaibei123 已提交
256
          uint64_t key = std::strtoul(line_data.data(), &end, 10);
Z
zhaocaibei123 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

          auto index_iter =
              global_shard_idx.find(key % _sparse_table_shard_num);
          if (index_iter == global_shard_idx.end()) {
            LOG(WARNING) << "MemorySparseTable key:" << key
                         << " not match shard,"
                         << " file_idx:" << i
                         << " global_shard_idx:" << global_shard_idx_str
                         << " shard num:" << _sparse_table_shard_num
                         << " file:" << channel_config.path;
            continue;
          }
          size_t local_shard_idx = *index_iter % _avg_local_shard_num;
          auto& shard = _local_shards[local_shard_idx];

272 273
          auto& value = shard[key];
          value.resize(feature_value_size);
274
          int parse_size = _value_accesor->ParseFromString(++end, value.data());
275
          value.resize(parse_size);
Z
zhaocaibei123 已提交
276
        }
Z
zhaocaibei123 已提交
277
        read_channel->close();
Z
zhaocaibei123 已提交
278 279 280 281 282
        if (err_no == -1) {
          ++retry_num;
          is_read_failed = true;
          LOG(ERROR)
              << "MemorySparseTable load failed after read, retry it! path:"
Z
zhaocaibei123 已提交
283
              << channel_config.path << " , retry_num=" << retry_num;
Z
zhaocaibei123 已提交
284 285 286 287 288
        }
      } catch (...) {
        ++retry_num;
        is_read_failed = true;
        LOG(ERROR) << "MemorySparseTable load failed, retry it! path:"
Z
zhaocaibei123 已提交
289
                   << channel_config.path << " , retry_num=" << retry_num;
Z
zhaocaibei123 已提交
290
      }
Z
zhaocaibei123 已提交
291
      if (retry_num > FLAGS_pserver_table_save_max_retry) {
Z
zhaocaibei123 已提交
292 293 294 295 296 297
        LOG(ERROR) << "MemorySparseTable load failed reach max limit!";
        exit(-1);
      }
    } while (is_read_failed);
  }
  LOG(INFO) << "MemorySparseTable load success, path from "
Z
zhaocaibei123 已提交
298
            << file_list[start_idx] << " to " << file_list[end_idx - 1];
Z
zhaocaibei123 已提交
299 300 301
  return 0;
}

Z
zhaocaibei123 已提交
302 303 304 305 306 307 308 309 310 311
void MemorySparseTable::Revert() {
  for (size_t i = 0; i < _real_local_shard_num; ++i) {
    _local_shards_new[i].clear();
  }
}

void MemorySparseTable::CheckSavePrePatchDone() {
  _save_patch_model_thread.join();
}

Z
zhaocaibei123 已提交
312
int32_t MemorySparseTable::Save(const std::string& dirname,
Z
zhaocaibei123 已提交
313
                                const std::string& param) {
Z
zhaocaibei123 已提交
314 315 316 317 318
  if (_real_local_shard_num == 0) {
    _local_show_threshold = -1;
    return 0;
  }

Z
zhaocaibei123 已提交
319 320 321
  VLOG(0) << "MemorySparseTable::save dirname: " << dirname;
  int save_param =
      atoi(param.c_str());  // checkpoint:0  xbox delta:1  xbox base:2
Z
zhaocaibei123 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335

  // patch model
  if (save_param == 5) {
    _local_shards_patch_model.reset(_local_shards_new.release());
    _local_shards_new.reset(new shard_type[_real_local_shard_num]);
    _save_patch_model_thread = std::thread(std::bind(
        &MemorySparseTable::SavePatch, this, std::string(dirname), save_param));
    return 0;
  }

  // cache model
  int64_t tk_size = LocalSize() * _config.sparse_table_cache_rate();
  TopkCalculator tk(_real_local_shard_num, tk_size);

Z
zhaocaibei123 已提交
336
  std::string table_path = TableDir(dirname);
Z
zhaocaibei123 已提交
337 338 339 340
  _afs_client.remove(paddle::string::format_string(
      "%s/part-%03d-*", table_path.c_str(), _shard_idx));
  std::atomic<uint32_t> feasign_size_all{0};

341
  size_t file_start_idx = _avg_local_shard_num * _shard_idx;
Z
zhaocaibei123 已提交
342

D
danleifeng 已提交
343 344 345
#ifdef PADDLE_WITH_GPU_GRAPH
  int thread_num = _real_local_shard_num;
#else
346
  int thread_num = _real_local_shard_num < 20 ? _real_local_shard_num : 20;
D
danleifeng 已提交
347
#endif
348 349
  omp_set_num_threads(thread_num);
#pragma omp parallel for schedule(dynamic)
350
  for (int i = 0; i < _real_local_shard_num; ++i) {
Z
zhaocaibei123 已提交
351 352 353
    FsChannelConfig channel_config;
    if (_config.compress_in_save() && (save_param == 0 || save_param == 3)) {
      channel_config.path =
354 355 356 357 358 359 360 361 362
          paddle::string::format_string("%s/part-%03d-%05d.gz",
                                        table_path.c_str(),
                                        _shard_idx,
                                        file_start_idx + i);
    } else {
      channel_config.path = paddle::string::format_string("%s/part-%03d-%05d",
                                                          table_path.c_str(),
                                                          _shard_idx,
                                                          file_start_idx + i);
Z
zhaocaibei123 已提交
363
    }
364
    channel_config.converter = _value_accesor->Converter(save_param).converter;
Z
zhaocaibei123 已提交
365
    channel_config.deconverter =
366
        _value_accesor->Converter(save_param).deconverter;
Z
zhaocaibei123 已提交
367 368 369 370
    bool is_write_failed = false;
    int feasign_size = 0;
    int retry_num = 0;
    int err_no = 0;
371
    auto& shard = _local_shards[i];
Z
zhaocaibei123 已提交
372 373 374 375 376 377
    do {
      err_no = 0;
      feasign_size = 0;
      is_write_failed = false;
      auto write_channel =
          _afs_client.open_w(channel_config, 1024 * 1024 * 40, &err_no);
378
      for (auto it = shard.begin(); it != shard.end(); ++it) {
Z
zhaocaibei123 已提交
379 380 381 382 383 384 385
        if (_config.enable_sparse_table_cache() &&
            (save_param == 1 || save_param == 2) &&
            _value_accesor->Save(it.value().data(), 4)) {
          CostTimer timer10("sprase table top push");
          tk.push(i, _value_accesor->GetField(it.value().data(), "show"));
        }

386 387
        if (_value_accesor->Save(it.value().data(), save_param)) {
          std::string format_value = _value_accesor->ParseToString(
388
              it.value().data(), it.value().size());
389 390
          if (0 != write_channel->write_line(paddle::string::format_string(
                       "%lu %s", it.key(), format_value.c_str()))) {
391 392 393 394 395 396
            ++retry_num;
            is_write_failed = true;
            LOG(ERROR)
                << "MemorySparseTable save prefix failed, retry it! path:"
                << channel_config.path << " , retry_num=" << retry_num;
            break;
Z
zhaocaibei123 已提交
397
          }
398
          ++feasign_size;
Z
zhaocaibei123 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411
        }
      }
      write_channel->close();
      if (err_no == -1) {
        ++retry_num;
        is_write_failed = true;
        LOG(ERROR)
            << "MemorySparseTable save prefix failed after write, retry it! "
            << "path:" << channel_config.path << " , retry_num=" << retry_num;
      }
      if (is_write_failed) {
        _afs_client.remove(channel_config.path);
      }
Z
zhaocaibei123 已提交
412
      if (retry_num > FLAGS_pserver_table_save_max_retry) {
Z
zhaocaibei123 已提交
413 414 415 416 417
        LOG(ERROR) << "MemorySparseTable save prefix failed reach max limit!";
        exit(-1);
      }
    } while (is_write_failed);
    feasign_size_all += feasign_size;
418
    for (auto it = shard.begin(); it != shard.end(); ++it) {
419
      _value_accesor->UpdateStatAfterSave(it.value().data(), save_param);
Z
zhaocaibei123 已提交
420 421
    }
    LOG(INFO) << "MemorySparseTable save prefix success, path: "
Z
zhaocaibei123 已提交
422
              << channel_config.path << " feasign_size: " << feasign_size;
Z
zhaocaibei123 已提交
423
  }
Z
zhaocaibei123 已提交
424
  _local_show_threshold = tk.top();
Z
zhaocaibei123 已提交
425 426 427 428
  // int32 may overflow need to change return value
  return 0;
}

Z
zhaocaibei123 已提交
429 430 431 432 433 434 435 436 437 438
int32_t MemorySparseTable::SavePatch(const std::string& path, int save_param) {
  if (!_config.enable_revert()) {
    LOG(INFO) << "MemorySparseTable should be enabled revert.";
    return 0;
  }
  size_t file_start_idx = _m_avg_local_shard_num * _shard_idx;
  std::string table_path = TableDir(path);
  _afs_client.remove(paddle::string::format_string(
      "%s/part-%03d-*", table_path.c_str(), _shard_idx));
  int thread_num = _m_real_local_shard_num < 20 ? _m_real_local_shard_num : 20;
439 440 441 442 443

  std::atomic<uint32_t> feasign_size_all{0};

  omp_set_num_threads(thread_num);
#pragma omp parallel for schedule(dynamic)
Z
zhaocaibei123 已提交
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 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 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
  for (size_t i = 0; i < _m_real_local_shard_num; ++i) {
    FsChannelConfig channel_config;
    channel_config.path = paddle::string::format_string("%s/part-%03d-%05d",
                                                        table_path.c_str(),
                                                        _shard_idx,
                                                        file_start_idx + i);

    channel_config.converter = _value_accesor->Converter(save_param).converter;
    channel_config.deconverter =
        _value_accesor->Converter(save_param).deconverter;

    bool is_write_failed = false;
    int feasign_size = 0;
    int retry_num = 0;
    int err_no = 0;
    do {
      err_no = 0;
      feasign_size = 0;
      is_write_failed = false;
      auto write_channel =
          _afs_client.open_w(channel_config, 1024 * 1024 * 40, &err_no);

      for (size_t j = 0; j < _real_local_shard_num; ++j) {
        if (j % _m_real_local_shard_num == i) {
          auto& shard = _local_shards_patch_model[j];
          for (auto it = shard.begin(); it != shard.end(); ++it) {
            if (_value_accesor->Save(it.value().data(), save_param)) {
              std::string format_value = _value_accesor->ParseToString(
                  it.value().data(), it.value().size());
              if (0 != write_channel->write_line(paddle::string::format_string(
                           "%lu %s", it.key(), format_value.c_str()))) {
                ++retry_num;
                is_write_failed = true;
                LOG(ERROR) << "MemorySparseTable save failed, retry it! path:"
                           << channel_config.path
                           << " , retry_num=" << retry_num;
                break;
              }
              ++feasign_size;
            }
          }
        }
        if (is_write_failed) break;
      }
      write_channel->close();
      if (err_no == -1) {
        ++retry_num;
        is_write_failed = true;
        LOG(ERROR)
            << "MemorySparseTable save patch 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 > FLAGS_pserver_table_save_max_retry) {
        LOG(ERROR) << "MemorySparseTable save patch failed reach max limit!";
        exit(-1);
      }
    } while (is_write_failed);
    feasign_size_all += feasign_size;
  }
  LOG(INFO) << "MemorySparseTable save patch success, path:"
            << paddle::string::format_string("%s/%03d/part-%03d-",
                                             path.c_str(),
                                             _config.table_id(),
                                             _shard_idx)
            << " from " << file_start_idx << " to "
            << file_start_idx + _m_real_local_shard_num - 1
            << ", feasign size: " << feasign_size_all;
  return 0;
}

int64_t MemorySparseTable::CacheShuffle(
    const std::string& path,
    const std::string& param,
    double cache_threshold,
    std::function<std::future<int32_t>(
        int msg_type, int to_pserver_id, std::string& msg)> send_msg_func,
    paddle::framework::Channel<std::pair<uint64_t, std::string>>&
        shuffled_channel,
    const std::vector<Table*>& table_ptrs) {
  LOG(INFO) << "cache shuffle with cache threshold: " << cache_threshold;
  int save_param = atoi(param.c_str());  // batch_model:0  xbox:1
  if (!_config.enable_sparse_table_cache() || cache_threshold < 0) {
    LOG(WARNING)
        << "cache shuffle failed not enable table cache or cache threshold < 0 "
        << _config.enable_sparse_table_cache() << " or " << cache_threshold;
    // return -1;
  }
  int shuffle_node_num = _config.sparse_table_cache_file_num();
  LOG(INFO) << "Table>> shuffle node num is: " << shuffle_node_num;
  // TODO(zhaocaibei123): check shuffle_node_num <= server_node_num
  size_t file_start_idx = _avg_local_shard_num * _shard_idx;
  int thread_num = _real_local_shard_num < 20 ? _real_local_shard_num : 20;

  std::vector<
      paddle::framework::ChannelWriter<std::pair<uint64_t, std::string>>>
      writers(_real_local_shard_num);
  std::vector<std::vector<std::pair<uint64_t, std::string>>> datas(
      _real_local_shard_num);

  int feasign_size = 0;
  std::vector<paddle::framework::Channel<std::pair<uint64_t, std::string>>>
      tmp_channels;
  for (size_t i = 0; i < _real_local_shard_num; ++i) {
    tmp_channels.push_back(
        paddle::framework::MakeChannel<std::pair<uint64_t, std::string>>());
  }

  omp_set_num_threads(thread_num);
#pragma omp parallel for schedule(dynamic)
  for (size_t i = 0; i < _real_local_shard_num; ++i) {
    paddle::framework::ChannelWriter<std::pair<uint64_t, std::string>>& writer =
        writers[i];
    writer.Reset(tmp_channels[i].get());

    for (size_t idx = 0; idx < table_ptrs.size(); idx++) {
      Table* table_ptr = table_ptrs[idx];
      auto value_accesor = table_ptr->ValueAccesor();
      shard_type* shard_ptr = static_cast<shard_type*>(table_ptr->GetShard(i));

      for (auto it = shard_ptr->begin(); it != shard_ptr->end(); ++it) {
        if (value_accesor->SaveCache(
                it.value().data(), save_param, cache_threshold)) {
          std::string format_value = value_accesor->ParseToString(
              it.value().data(), it.value().size());
          std::pair<uint64_t, std::string> pkv(it.key(), format_value.c_str());
          writer << pkv;
          ++feasign_size;
        }
Z
zhaocaibei123 已提交
575 576
      }
    }
Z
zhaocaibei123 已提交
577 578
    writer.Flush();
    writer.channel()->Close();
Z
zhaocaibei123 已提交
579
  }
Z
zhaocaibei123 已提交
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
  // LOG(INFO) << "MemorySparseTable cache KV save success to Channel feasigh
  // size: " << feasign_size << " and start sparse cache data shuffle real local
  // shard num: " << _real_local_shard_num;
  std::vector<std::pair<uint64_t, std::string>> local_datas;
  for (size_t idx_shard = 0; idx_shard < _real_local_shard_num; ++idx_shard) {
    paddle::framework::ChannelWriter<std::pair<uint64_t, std::string>>& writer =
        writers[idx_shard];
    auto channel = writer.channel();
    std::vector<std::pair<uint64_t, std::string>>& data = datas[idx_shard];
    std::vector<paddle::framework::BinaryArchive> ars(shuffle_node_num);
    while (channel->Read(data)) {
      for (auto& t : data) {
        auto pserver_id =
            paddle::distributed::local_random_engine()() % shuffle_node_num;
        if (pserver_id != _shard_idx) {
          ars[pserver_id] << t;
        } else {
          local_datas.emplace_back(std::move(t));
        }
      }
      std::vector<std::future<int32_t>> total_status;
      std::vector<uint32_t> send_data_size(shuffle_node_num, 0);
      std::vector<int> send_index(shuffle_node_num);
      for (int i = 0; i < shuffle_node_num; ++i) {
        send_index[i] = i;
      }
      std::random_shuffle(send_index.begin(), send_index.end());
      for (auto index = 0u; index < shuffle_node_num; ++index) {
        int i = send_index[index];
        if (i == _shard_idx) {
          continue;
        }
        if (ars[i].Length() == 0) {
          continue;
        }
        std::string msg(ars[i].Buffer(), ars[i].Length());
        auto ret = send_msg_func(101, i, msg);
        total_status.push_back(std::move(ret));
        send_data_size[i] += ars[i].Length();
      }
      for (auto& t : total_status) {
        t.wait();
      }
      ars.clear();
      ars = std::vector<paddle::framework::BinaryArchive>(shuffle_node_num);
      data = std::vector<std::pair<uint64_t, std::string>>();
    }
  }
  shuffled_channel->Write(std::move(local_datas));
Z
zhaocaibei123 已提交
629 630 631
  return 0;
}

Z
zhaocaibei123 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
int32_t MemorySparseTable::SaveCache(
    const std::string& path,
    const std::string& param,
    paddle::framework::Channel<std::pair<uint64_t, std::string>>&
        shuffled_channel) {
  if (_shard_idx >= _config.sparse_table_cache_file_num()) {
    return 0;
  }
  int save_param = atoi(param.c_str());  // batch_model:0  xbox:1
  size_t file_start_idx = _avg_local_shard_num * _shard_idx;
  std::string table_path = paddle::string::format_string(
      "%s/%03d_cache/", path.c_str(), _config.table_id());
  _afs_client.remove(paddle::string::format_string(
      "%s/part-%03d", table_path.c_str(), _shard_idx));
  uint32_t feasign_size = 0;
  FsChannelConfig channel_config;
  // not compress cache model
  channel_config.path = paddle::string::format_string(
      "%s/part-%03d", table_path.c_str(), _shard_idx);
  channel_config.converter = _value_accesor->Converter(save_param).converter;
  channel_config.deconverter =
      _value_accesor->Converter(save_param).deconverter;
  auto write_channel = _afs_client.open_w(channel_config, 1024 * 1024 * 40);
  std::vector<std::pair<uint64_t, std::string>> data;
  bool is_write_failed = false;
  shuffled_channel->Close();
  while (shuffled_channel->Read(data)) {
    for (auto& t : data) {
      ++feasign_size;
      if (0 != write_channel->write_line(paddle::string::format_string(
                   "%lu %s", t.first, t.second.c_str()))) {
        LOG(ERROR) << "Cache Table save failed, "
                      "path:"
                   << channel_config.path << ", retry it!";
        is_write_failed = true;
        break;
      }
    }
    data = std::vector<std::pair<uint64_t, std::string>>();
  }
  if (is_write_failed) {
    _afs_client.remove(channel_config.path);
  }
  write_channel->close();
  LOG(INFO) << "MemorySparseTable cache save success, feasign: " << feasign_size
            << ", path: " << channel_config.path;
  shuffled_channel->Open();
  return feasign_size;
}

Z
zhaocaibei123 已提交
682
int64_t MemorySparseTable::LocalSize() {
683
  int64_t local_size = 0;
684
  for (int i = 0; i < _real_local_shard_num; ++i) {
685 686 687 688
    local_size += _local_shards[i].size();
  }
  return local_size;
}
Z
zhaocaibei123 已提交
689

Z
zhaocaibei123 已提交
690
int64_t MemorySparseTable::LocalMFSize() {
691 692 693
  std::vector<int64_t> size_arr(_real_local_shard_num, 0);
  std::vector<std::future<int>> tasks(_real_local_shard_num);
  int64_t ret_size = 0;
694
  for (int shard_id = 0; shard_id < _real_local_shard_num; ++shard_id) {
695 696 697 698 699 700
    tasks[shard_id] =
        _shards_task_pool[shard_id % _shards_task_pool.size()]->enqueue(
            [this, shard_id, &size_arr]() -> int {
              auto& local_shard = _local_shards[shard_id];
              for (auto it = local_shard.begin(); it != local_shard.end();
                   ++it) {
701
                if (_value_accesor->HasMF(it.value().size())) {
702 703 704 705 706 707
                  size_arr[shard_id] += 1;
                }
              }
              return 0;
            });
  }
708
  for (int i = 0; i < _real_local_shard_num; ++i) {
709 710 711 712
    tasks[i].wait();
  }
  for (auto x : size_arr) {
    ret_size += x;
Z
zhaocaibei123 已提交
713
  }
714 715
  return ret_size;
}
Z
zhaocaibei123 已提交
716

Z
zhaocaibei123 已提交
717 718 719
std::pair<int64_t, int64_t> MemorySparseTable::PrintTableStat() {
  int64_t feasign_size = LocalSize();
  int64_t mf_size = LocalMFSize();
Z
zhaocaibei123 已提交
720 721 722
  return {feasign_size, mf_size};
}

Y
yaoxuefeng 已提交
723 724 725 726 727
int32_t MemorySparseTable::Pull(TableContext& context) {
  CHECK(context.value_type == Sparse);
  if (context.use_ptr) {
    char** pull_values = context.pull_context.ptr_values;
    const uint64_t* keys = context.pull_context.keys;
Z
zhaocaibei123 已提交
728
    return PullSparsePtr(pull_values, keys, context.num);
Y
yaoxuefeng 已提交
729 730 731
  } else {
    float* pull_values = context.pull_context.values;
    const PullSparseValue& pull_value = context.pull_context.pull_value;
Z
zhaocaibei123 已提交
732
    return PullSparse(pull_values, pull_value);
Y
yaoxuefeng 已提交
733 734 735 736 737
  }
}

int32_t MemorySparseTable::Push(TableContext& context) {
  CHECK(context.value_type == Sparse);
738
  if (!context.use_ptr) {
739 740
    return PushSparse(
        context.push_context.keys, context.push_context.values, context.num);
741 742
  } else {
    return PushSparse(context.push_context.keys,
743 744
                      context.push_context.ptr_values,
                      context.num);
745
  }
Y
yaoxuefeng 已提交
746 747
}

Z
zhaocaibei123 已提交
748 749
int32_t MemorySparseTable::PullSparse(float* pull_values,
                                      const PullSparseValue& pull_value) {
750 751
  CostTimer timer("pserver_sparse_select_all");
  std::vector<std::future<int>> tasks(_real_local_shard_num);
Z
zhaocaibei123 已提交
752

753 754 755 756
  const size_t value_size =
      _value_accesor->GetAccessorInfo().size / sizeof(float);
  size_t mf_value_size =
      _value_accesor->GetAccessorInfo().mf_size / sizeof(float);
757
  size_t select_value_size =
758
      _value_accesor->GetAccessorInfo().select_size / sizeof(float);
Z
zhaocaibei123 已提交
759 760 761
  // std::atomic<uint32_t> missed_keys{0};

  std::vector<std::vector<std::pair<uint64_t, int>>> task_keys(
762
      _real_local_shard_num);
Z
zhaocaibei123 已提交
763 764
  size_t num = pull_value.numel_;
  for (size_t i = 0; i < num; ++i) {
765 766
    int shard_id = (pull_value.feasigns_[i] % _sparse_table_shard_num) %
                   _avg_local_shard_num;
Z
zhaocaibei123 已提交
767 768
    task_keys[shard_id].push_back({pull_value.feasigns_[i], i});
  }
769
  for (int shard_id = 0; shard_id < _real_local_shard_num; ++shard_id) {
Z
zhaocaibei123 已提交
770
    tasks[shard_id] =
771
        _shards_task_pool[shard_id % _shards_task_pool.size()]->enqueue(
772 773 774 775 776 777
            [this,
             shard_id,
             &task_keys,
             value_size,
             pull_values,
             mf_value_size,
Z
zhaocaibei123 已提交
778
             select_value_size]() -> int {
779
              auto& local_shard = _local_shards[shard_id];
Z
zhaocaibei123 已提交
780 781 782 783 784 785
              float data_buffer[value_size];  // NOLINT
              float* data_buffer_ptr = data_buffer;

              auto& keys = task_keys[shard_id];
              for (size_t i = 0; i < keys.size(); i++) {
                uint64_t key = keys[i].first;
786
                auto itr = local_shard.find(key);
Z
zhaocaibei123 已提交
787
                size_t data_size = value_size - mf_value_size;
788
                if (itr == local_shard.end()) {
Z
zhaocaibei123 已提交
789
                  // ++missed_keys;
790
                  if (FLAGS_pserver_create_value_when_push) {
Z
zhaocaibei123 已提交
791 792
                    memset(data_buffer, 0, sizeof(float) * data_size);
                  } else {
793 794 795
                    auto& feature_value = local_shard[key];
                    feature_value.resize(data_size);
                    float* data_ptr = feature_value.data();
796
                    _value_accesor->Create(&data_buffer_ptr, 1);
797 798
                    memcpy(
                        data_ptr, data_buffer_ptr, data_size * sizeof(float));
Z
zhaocaibei123 已提交
799 800
                  }
                } else {
801
                  data_size = itr.value().size();
802 803
                  memcpy(data_buffer_ptr,
                         itr.value().data(),
Z
zhaocaibei123 已提交
804 805
                         data_size * sizeof(float));
                }
806
                for (size_t mf_idx = data_size; mf_idx < value_size; ++mf_idx) {
Z
zhaocaibei123 已提交
807 808 809 810
                  data_buffer[mf_idx] = 0.0;
                }
                auto offset = keys[i].second;
                float* select_data = pull_values + select_value_size * offset;
811 812
                _value_accesor->Select(
                    &select_data, (const float**)&data_buffer_ptr, 1);
Z
zhaocaibei123 已提交
813 814 815 816 817 818 819 820 821 822 823 824
              }

              return 0;
            });
  }

  for (size_t shard_id = 0; shard_id < tasks.size(); ++shard_id) {
    tasks[shard_id].wait();
  }
  return 0;
}

Z
zhaocaibei123 已提交
825
int32_t MemorySparseTable::PullSparsePtr(char** pull_values,
826 827
                                         const uint64_t* keys,
                                         size_t num) {
828
  CostTimer timer("pscore_sparse_select_all");
829 830 831
  size_t value_size = _value_accesor->GetAccessorInfo().size / sizeof(float);
  size_t mf_value_size =
      _value_accesor->GetAccessorInfo().mf_size / sizeof(float);
832 833 834 835 836 837 838 839 840

  std::vector<std::future<int>> tasks(_real_local_shard_num);
  std::vector<std::vector<std::pair<uint64_t, int>>> task_keys(
      _real_local_shard_num);
  for (size_t i = 0; i < num; ++i) {
    int shard_id = (keys[i] % _sparse_table_shard_num) % _avg_local_shard_num;
    task_keys[shard_id].push_back({keys[i], i});
  }
  // std::atomic<uint32_t> missed_keys{0};
841
  for (int shard_id = 0; shard_id < _real_local_shard_num; ++shard_id) {
842 843
    tasks[shard_id] =
        _shards_task_pool[shard_id % _shards_task_pool.size()]->enqueue(
844 845 846 847 848
            [this,
             shard_id,
             &task_keys,
             pull_values,
             value_size,
849 850 851
             mf_value_size]() -> int {
              auto& keys = task_keys[shard_id];
              auto& local_shard = _local_shards[shard_id];
R
Ruibiao Chen 已提交
852
              float data_buffer[value_size];  // NOLINT
853
              float* data_buffer_ptr = data_buffer;
854
              for (size_t i = 0; i < keys.size(); ++i) {
855 856 857 858 859 860 861 862 863
                uint64_t key = keys[i].first;
                auto itr = local_shard.find(key);
                size_t data_size = value_size - mf_value_size;
                FixedFeatureValue* ret = NULL;
                if (itr == local_shard.end()) {
                  // ++missed_keys;
                  auto& feature_value = local_shard[key];
                  feature_value.resize(data_size);
                  float* data_ptr = feature_value.data();
864
                  _value_accesor->Create(&data_buffer_ptr, 1);
865 866 867 868 869 870
                  memcpy(data_ptr, data_buffer_ptr, data_size * sizeof(float));
                  ret = &feature_value;
                } else {
                  ret = itr.value_ptr();
                }
                int pull_data_idx = keys[i].second;
Z
zhaocaibei123 已提交
871
                pull_values[pull_data_idx] = reinterpret_cast<char*>(ret);
872 873 874 875 876 877 878
              }
              return 0;
            });
  }
  for (size_t shard_id = 0; shard_id < tasks.size(); ++shard_id) {
    tasks[shard_id].wait();
  }
Z
zhaocaibei123 已提交
879 880 881
  return 0;
}

882 883
int32_t MemorySparseTable::PushSparse(const uint64_t* keys,
                                      const float* values,
Z
zhaocaibei123 已提交
884
                                      size_t num) {
885 886
  CostTimer timer("pserver_sparse_update_all");
  std::vector<std::future<int>> tasks(_real_local_shard_num);
Z
zhaocaibei123 已提交
887
  std::vector<std::vector<std::pair<uint64_t, int>>> task_keys(
888
      _real_local_shard_num);
Z
zhaocaibei123 已提交
889
  for (size_t i = 0; i < num; ++i) {
890
    int shard_id = (keys[i] % _sparse_table_shard_num) % _avg_local_shard_num;
Z
zhaocaibei123 已提交
891 892 893
    task_keys[shard_id].push_back({keys[i], i});
  }

894 895 896 897
  const size_t value_col =
      _value_accesor->GetAccessorInfo().size / sizeof(float);
  size_t mf_value_col =
      _value_accesor->GetAccessorInfo().mf_size / sizeof(float);
898
  size_t update_value_col =
899
      _value_accesor->GetAccessorInfo().update_size / sizeof(float);
Z
zhaocaibei123 已提交
900

901
  for (int shard_id = 0; shard_id < _real_local_shard_num; ++shard_id) {
902
    tasks[shard_id] = _shards_task_pool[shard_id % _task_pool_size]->enqueue(
903 904 905 906 907 908
        [this,
         shard_id,
         value_col,
         mf_value_col,
         update_value_col,
         values,
Z
zhaocaibei123 已提交
909 910
         &task_keys]() -> int {
          auto& keys = task_keys[shard_id];
911
          auto& local_shard = _local_shards[shard_id];
Z
zhaocaibei123 已提交
912
          auto& local_shard_new = _local_shards_new[shard_id];
Z
zhaocaibei123 已提交
913 914
          float data_buffer[value_col];  // NOLINT
          float* data_buffer_ptr = data_buffer;
915
          for (size_t i = 0; i < keys.size(); ++i) {
Z
zhaocaibei123 已提交
916 917 918 919
            uint64_t key = keys[i].first;
            uint64_t push_data_idx = keys[i].second;
            const float* update_data =
                values + push_data_idx * update_value_col;
920 921 922
            auto itr = local_shard.find(key);
            if (itr == local_shard.end()) {
              if (FLAGS_pserver_enable_create_feasign_randomly &&
923
                  !_value_accesor->CreateValue(1, update_data)) {
Z
zhaocaibei123 已提交
924 925 926
                continue;
              }
              auto value_size = value_col - mf_value_col;
927 928
              auto& feature_value = local_shard[key];
              feature_value.resize(value_size);
929
              _value_accesor->Create(&data_buffer_ptr, 1);
930 931
              memcpy(feature_value.data(),
                     data_buffer_ptr,
Z
zhaocaibei123 已提交
932
                     value_size * sizeof(float));
933
              itr = local_shard.find(key);
Z
zhaocaibei123 已提交
934 935
            }

936 937 938
            auto& feature_value = itr.value();
            float* value_data = feature_value.data();
            size_t value_size = feature_value.size();
Z
zhaocaibei123 已提交
939 940

            if (value_size == value_col) {  // 已拓展到最大size, 则就地update
941
              _value_accesor->Update(&value_data, &update_data, 1);
Z
zhaocaibei123 已提交
942 943 944
            } else {
              // 拷入buffer区进行update,然后再回填,不需要的mf则回填时抛弃了
              memcpy(data_buffer_ptr, value_data, value_size * sizeof(float));
945
              _value_accesor->Update(&data_buffer_ptr, &update_data, 1);
Z
zhaocaibei123 已提交
946

947
              if (_value_accesor->NeedExtendMF(data_buffer)) {
948 949
                feature_value.resize(value_col);
                value_data = feature_value.data();
950
                _value_accesor->Create(&value_data, 1);
Z
zhaocaibei123 已提交
951 952 953
              }
              memcpy(value_data, data_buffer_ptr, value_size * sizeof(float));
            }
Z
zhaocaibei123 已提交
954 955 956 957 958 959 960 961
            if (_config.enable_revert()) {
              FixedFeatureValue* feature_value_new = &(local_shard_new[key]);
              auto new_size = feature_value.size();
              feature_value_new->resize(new_size);
              memcpy(feature_value_new->data(),
                     value_data,
                     new_size * sizeof(float));
            }
Z
zhaocaibei123 已提交
962 963 964 965 966 967 968 969 970 971 972
          }
          return 0;
        });
  }

  for (size_t shard_id = 0; shard_id < tasks.size(); ++shard_id) {
    tasks[shard_id].wait();
  }
  return 0;
}

Z
zhaocaibei123 已提交
973
int32_t MemorySparseTable::PushSparse(const uint64_t* keys,
974 975
                                      const float** values,
                                      size_t num) {
976
  std::vector<std::future<int>> tasks(_real_local_shard_num);
Z
zhaocaibei123 已提交
977
  std::vector<std::vector<std::pair<uint64_t, int>>> task_keys(
978
      _real_local_shard_num);
Z
zhaocaibei123 已提交
979
  for (size_t i = 0; i < num; ++i) {
980
    int shard_id = (keys[i] % _sparse_table_shard_num) % _avg_local_shard_num;
Z
zhaocaibei123 已提交
981 982 983
    task_keys[shard_id].push_back({keys[i], i});
  }

984 985 986
  size_t value_col = _value_accesor->GetAccessorInfo().size / sizeof(float);
  size_t mf_value_col =
      _value_accesor->GetAccessorInfo().mf_size / sizeof(float);
987
  size_t update_value_col =
988
      _value_accesor->GetAccessorInfo().update_size / sizeof(float);
Z
zhaocaibei123 已提交
989

990 991
  for (int shard_id = 0; shard_id < _real_local_shard_num; ++shard_id) {
    tasks[shard_id] = _shards_task_pool[shard_id % _task_pool_size]->enqueue(
992 993 994 995 996 997
        [this,
         shard_id,
         value_col,
         mf_value_col,
         update_value_col,
         values,
Z
zhaocaibei123 已提交
998 999
         &task_keys]() -> int {
          auto& keys = task_keys[shard_id];
1000
          auto& local_shard = _local_shards[shard_id];
Z
zhaocaibei123 已提交
1001 1002
          float data_buffer[value_col];  // NOLINT
          float* data_buffer_ptr = data_buffer;
1003
          for (size_t i = 0; i < keys.size(); ++i) {
Z
zhaocaibei123 已提交
1004 1005 1006
            uint64_t key = keys[i].first;
            uint64_t push_data_idx = keys[i].second;
            const float* update_data = values[push_data_idx];
1007 1008 1009
            auto itr = local_shard.find(key);
            if (itr == local_shard.end()) {
              if (FLAGS_pserver_enable_create_feasign_randomly &&
1010
                  !_value_accesor->CreateValue(1, update_data)) {
Z
zhaocaibei123 已提交
1011 1012 1013
                continue;
              }
              auto value_size = value_col - mf_value_col;
1014 1015
              auto& feature_value = local_shard[key];
              feature_value.resize(value_size);
1016
              _value_accesor->Create(&data_buffer_ptr, 1);
1017 1018
              memcpy(feature_value.data(),
                     data_buffer_ptr,
Z
zhaocaibei123 已提交
1019
                     value_size * sizeof(float));
1020
              itr = local_shard.find(key);
Z
zhaocaibei123 已提交
1021
            }
1022 1023 1024
            auto& feature_value = itr.value();
            float* value_data = feature_value.data();
            size_t value_size = feature_value.size();
Z
zhaocaibei123 已提交
1025
            if (value_size == value_col) {  // 已拓展到最大size, 则就地update
1026
              _value_accesor->Update(&value_data, &update_data, 1);
Z
zhaocaibei123 已提交
1027 1028 1029
            } else {
              // 拷入buffer区进行update,然后再回填,不需要的mf则回填时抛弃了
              memcpy(data_buffer_ptr, value_data, value_size * sizeof(float));
1030 1031
              _value_accesor->Update(&data_buffer_ptr, &update_data, 1);
              if (_value_accesor->NeedExtendMF(data_buffer)) {
1032 1033
                feature_value.resize(value_col);
                value_data = feature_value.data();
1034
                _value_accesor->Create(&value_data, 1);
Z
zhaocaibei123 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
              }
              memcpy(value_data, data_buffer_ptr, value_size * sizeof(float));
            }
          }
          return 0;
        });
  }

  for (size_t shard_id = 0; shard_id < tasks.size(); ++shard_id) {
    tasks[shard_id].wait();
  }
  return 0;
}

Z
zhaocaibei123 已提交
1049
int32_t MemorySparseTable::Flush() { return 0; }
Z
zhaocaibei123 已提交
1050

Z
zhaocaibei123 已提交
1051 1052
int32_t MemorySparseTable::Shrink(const std::string& param) {
  VLOG(0) << "MemorySparseTable::Shrink";
Z
zhaocaibei123 已提交
1053
  // TODO(zhaocaibei123): implement with multi-thread
1054
  for (int shard_id = 0; shard_id < _real_local_shard_num; ++shard_id) {
Z
zhaocaibei123 已提交
1055
    // Shrink
1056 1057
    auto& shard = _local_shards[shard_id];
    for (auto it = shard.begin(); it != shard.end();) {
1058
      if (_value_accesor->Shrink(it.value().data())) {
1059 1060 1061
        it = shard.erase(it);
      } else {
        ++it;
Z
zhaocaibei123 已提交
1062 1063 1064 1065 1066 1067
      }
    }
  }
  return 0;
}

Z
zhaocaibei123 已提交
1068
void MemorySparseTable::Clear() { VLOG(0) << "clear coming soon"; }
Z
zhaocaibei123 已提交
1069 1070 1071

}  // namespace distributed
}  // namespace paddle