memory_sparse_table.cc 40.6 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
  _shards_task_pool.resize(_task_pool_size);
45
  for (size_t i = 0; i < _shards_task_pool.size(); ++i) {
46
    _shards_task_pool[i].reset(new ::ThreadPool(1));
Z
zhaocaibei123 已提交
47
  }
48 49 50
  auto& profiler = CostProfiler::instance();
  profiler.register_profiler("pserver_sparse_update_all");
  profiler.register_profiler("pserver_sparse_select_all");
Z
zhaocaibei123 已提交
51
  InitializeValue();
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
  }
68 69 70
  VLOG(1) << "memory sparse table _avg_local_shard_num: "
          << _avg_local_shard_num
          << " _real_local_shard_num: " << _real_local_shard_num;
Z
zhaocaibei123 已提交
71

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

Z
zhaocaibei123 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  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 已提交
98 99 100
  return 0;
}

Z
zhaocaibei123 已提交
101
int32_t MemorySparseTable::Load(const std::string& path,
Z
zhaocaibei123 已提交
102
                                const std::string& param) {
Z
zhaocaibei123 已提交
103
  std::string table_path = TableDir(path);
Z
zhaocaibei123 已提交
104 105 106 107
  auto file_list = _afs_client.list(table_path);

  std::sort(file_list.begin(), file_list.end());
  for (auto file : file_list) {
Z
zhaocaibei123 已提交
108
    VLOG(1) << "MemorySparseTable::Load() file list: " << file;
Z
zhaocaibei123 已提交
109 110 111
  }

  int load_param = atoi(param.c_str());
112
  size_t expect_shard_num = _sparse_table_shard_num;
Z
zhaocaibei123 已提交
113 114 115 116 117 118 119 120 121 122
  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 已提交
123 124 125 126
  if (load_param == 5) {
    return LoadPatch(file_list, load_param);
  }

127
  size_t file_start_idx = _shard_idx * _avg_local_shard_num;
Z
zhaocaibei123 已提交
128

Z
zhaocaibei123 已提交
129 130 131 132
  if (file_start_idx >= file_list.size()) {
    return 0;
  }

133
  size_t feature_value_size =
134
      _value_accesor->GetAccessorInfo().size / sizeof(float);
135 136 137 138

  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)
139
  for (int i = 0; i < _real_local_shard_num; ++i) {
Z
zhaocaibei123 已提交
140 141 142 143
    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;
144
    channel_config.converter = _value_accesor->Converter(load_param).converter;
Z
zhaocaibei123 已提交
145
    channel_config.deconverter =
146
        _value_accesor->Converter(load_param).deconverter;
Z
zhaocaibei123 已提交
147 148 149 150 151 152 153 154 155 156

    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;
157
      auto& shard = _local_shards[i];
Z
zhaocaibei123 已提交
158 159 160 161
      try {
        while (read_channel->read_line(line_data) == 0 &&
               line_data.size() > 1) {
          uint64_t key = std::strtoul(line_data.data(), &end, 10);
162 163
          auto& value = shard[key];
          value.resize(feature_value_size);
164
          int parse_size = _value_accesor->ParseFromString(++end, value.data());
165
          value.resize(parse_size);
Z
zhaocaibei123 已提交
166 167 168 169

          // for debug
          for (int ii = 0; ii < parse_size; ++ii) {
            VLOG(2) << "MemorySparseTable::load key: " << key << " value " << ii
170
                    << ": " << value.data()[ii] << " local_shard: " << i;
Z
zhaocaibei123 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
          }
        }
        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 已提交
187
      if (retry_num > FLAGS_pserver_table_save_max_retry) {
Z
zhaocaibei123 已提交
188 189 190 191 192 193 194
        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 "
195
            << file_list[file_start_idx + _real_local_shard_num - 1];
Z
zhaocaibei123 已提交
196 197 198
  return 0;
}

Z
zhaocaibei123 已提交
199 200 201 202 203
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 已提交
204
  }
Z
zhaocaibei123 已提交
205 206 207 208 209 210 211 212 213
  // 聚合分片数据索引
  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 已提交
214
  }
215
  size_t feature_value_size =
216
      _value_accesor->GetAccessorInfo().size / sizeof(float);
Z
zhaocaibei123 已提交
217 218 219
  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 已提交
220

221 222
  omp_set_num_threads(thread_num);
#pragma omp parallel for schedule(dynamic)
Z
zhaocaibei123 已提交
223 224 225 226 227 228 229
  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 已提交
230 231 232 233 234 235 236
    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 已提交
237
      auto read_channel = _afs_client.open_r(channel_config, 0, &err_no);
Z
zhaocaibei123 已提交
238
      char* end = NULL;
Z
zhaocaibei123 已提交
239 240 241 242 243 244 245 246 247 248
      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 已提交
249
      try {
Z
zhaocaibei123 已提交
250 251
        while (read_channel->read_line(line_data) == 0 &&
               line_data.size() > 1) {
Z
zhaocaibei123 已提交
252
          uint64_t key = std::strtoul(line_data.data(), &end, 10);
Z
zhaocaibei123 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267

          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];

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

Z
zhaocaibei123 已提交
298 299 300 301 302 303 304 305 306 307
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 已提交
308
int32_t MemorySparseTable::Save(const std::string& dirname,
Z
zhaocaibei123 已提交
309
                                const std::string& param) {
Z
zhaocaibei123 已提交
310 311 312 313 314
  if (_real_local_shard_num == 0) {
    _local_show_threshold = -1;
    return 0;
  }

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

  // 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 已提交
332
  std::string table_path = TableDir(dirname);
Z
zhaocaibei123 已提交
333 334 335 336
  _afs_client.remove(paddle::string::format_string(
      "%s/part-%03d-*", table_path.c_str(), _shard_idx));
  std::atomic<uint32_t> feasign_size_all{0};

337
  size_t file_start_idx = _avg_local_shard_num * _shard_idx;
Z
zhaocaibei123 已提交
338

339 340 341
  int thread_num = _real_local_shard_num < 20 ? _real_local_shard_num : 20;
  omp_set_num_threads(thread_num);
#pragma omp parallel for schedule(dynamic)
342
  for (int i = 0; i < _real_local_shard_num; ++i) {
Z
zhaocaibei123 已提交
343 344 345
    FsChannelConfig channel_config;
    if (_config.compress_in_save() && (save_param == 0 || save_param == 3)) {
      channel_config.path =
346 347 348 349 350 351 352 353 354
          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 已提交
355
    }
356
    channel_config.converter = _value_accesor->Converter(save_param).converter;
Z
zhaocaibei123 已提交
357
    channel_config.deconverter =
358
        _value_accesor->Converter(save_param).deconverter;
Z
zhaocaibei123 已提交
359 360 361 362
    bool is_write_failed = false;
    int feasign_size = 0;
    int retry_num = 0;
    int err_no = 0;
363
    auto& shard = _local_shards[i];
Z
zhaocaibei123 已提交
364 365 366 367 368 369
    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);
370
      for (auto it = shard.begin(); it != shard.end(); ++it) {
Z
zhaocaibei123 已提交
371 372 373 374 375 376 377
        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"));
        }

378 379
        if (_value_accesor->Save(it.value().data(), save_param)) {
          std::string format_value = _value_accesor->ParseToString(
380
              it.value().data(), it.value().size());
381 382
          if (0 != write_channel->write_line(paddle::string::format_string(
                       "%lu %s", it.key(), format_value.c_str()))) {
383 384 385 386 387 388
            ++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 已提交
389
          }
390
          ++feasign_size;
Z
zhaocaibei123 已提交
391 392 393 394 395 396 397 398 399 400 401 402 403
        }
      }
      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 已提交
404
      if (retry_num > FLAGS_pserver_table_save_max_retry) {
Z
zhaocaibei123 已提交
405 406 407 408 409
        LOG(ERROR) << "MemorySparseTable save prefix failed reach max limit!";
        exit(-1);
      }
    } while (is_write_failed);
    feasign_size_all += feasign_size;
410
    for (auto it = shard.begin(); it != shard.end(); ++it) {
411
      _value_accesor->UpdateStatAfterSave(it.value().data(), save_param);
Z
zhaocaibei123 已提交
412 413
    }
    LOG(INFO) << "MemorySparseTable save prefix success, path: "
Z
zhaocaibei123 已提交
414
              << channel_config.path << " feasign_size: " << feasign_size;
Z
zhaocaibei123 已提交
415
  }
Z
zhaocaibei123 已提交
416
  _local_show_threshold = tk.top();
Z
zhaocaibei123 已提交
417 418 419 420
  // int32 may overflow need to change return value
  return 0;
}

Z
zhaocaibei123 已提交
421 422 423 424 425 426 427 428 429 430
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;
431 432 433 434 435

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

  omp_set_num_threads(thread_num);
#pragma omp parallel for schedule(dynamic)
Z
zhaocaibei123 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 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
  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 已提交
567 568
      }
    }
Z
zhaocaibei123 已提交
569 570
    writer.Flush();
    writer.channel()->Close();
Z
zhaocaibei123 已提交
571
  }
Z
zhaocaibei123 已提交
572 573 574 575 576 577 578 579 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
  // 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 已提交
621 622 623
  return 0;
}

Z
zhaocaibei123 已提交
624 625 626 627 628 629 630 631 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
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 已提交
674
int64_t MemorySparseTable::LocalSize() {
675
  int64_t local_size = 0;
676
  for (int i = 0; i < _real_local_shard_num; ++i) {
677 678 679 680
    local_size += _local_shards[i].size();
  }
  return local_size;
}
Z
zhaocaibei123 已提交
681

Z
zhaocaibei123 已提交
682
int64_t MemorySparseTable::LocalMFSize() {
683 684 685
  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;
686
  for (int shard_id = 0; shard_id < _real_local_shard_num; ++shard_id) {
687 688 689 690 691 692
    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) {
693
                if (_value_accesor->HasMF(it.value().size())) {
694 695 696 697 698 699
                  size_arr[shard_id] += 1;
                }
              }
              return 0;
            });
  }
700
  for (int i = 0; i < _real_local_shard_num; ++i) {
701 702 703 704
    tasks[i].wait();
  }
  for (auto x : size_arr) {
    ret_size += x;
Z
zhaocaibei123 已提交
705
  }
706 707
  return ret_size;
}
Z
zhaocaibei123 已提交
708

Z
zhaocaibei123 已提交
709 710 711
std::pair<int64_t, int64_t> MemorySparseTable::PrintTableStat() {
  int64_t feasign_size = LocalSize();
  int64_t mf_size = LocalMFSize();
Z
zhaocaibei123 已提交
712 713 714
  return {feasign_size, mf_size};
}

Y
yaoxuefeng 已提交
715 716 717 718 719
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 已提交
720
    return PullSparsePtr(pull_values, keys, context.num);
Y
yaoxuefeng 已提交
721 722 723
  } else {
    float* pull_values = context.pull_context.values;
    const PullSparseValue& pull_value = context.pull_context.pull_value;
Z
zhaocaibei123 已提交
724
    return PullSparse(pull_values, pull_value);
Y
yaoxuefeng 已提交
725 726 727 728 729
  }
}

int32_t MemorySparseTable::Push(TableContext& context) {
  CHECK(context.value_type == Sparse);
730
  if (!context.use_ptr) {
731 732
    return PushSparse(
        context.push_context.keys, context.push_context.values, context.num);
733 734
  } else {
    return PushSparse(context.push_context.keys,
735 736
                      context.push_context.ptr_values,
                      context.num);
737
  }
Y
yaoxuefeng 已提交
738 739
}

Z
zhaocaibei123 已提交
740 741
int32_t MemorySparseTable::PullSparse(float* pull_values,
                                      const PullSparseValue& pull_value) {
742 743
  CostTimer timer("pserver_sparse_select_all");
  std::vector<std::future<int>> tasks(_real_local_shard_num);
Z
zhaocaibei123 已提交
744

745 746 747 748
  const size_t value_size =
      _value_accesor->GetAccessorInfo().size / sizeof(float);
  size_t mf_value_size =
      _value_accesor->GetAccessorInfo().mf_size / sizeof(float);
749
  size_t select_value_size =
750
      _value_accesor->GetAccessorInfo().select_size / sizeof(float);
Z
zhaocaibei123 已提交
751 752 753
  // std::atomic<uint32_t> missed_keys{0};

  std::vector<std::vector<std::pair<uint64_t, int>>> task_keys(
754
      _real_local_shard_num);
Z
zhaocaibei123 已提交
755 756
  size_t num = pull_value.numel_;
  for (size_t i = 0; i < num; ++i) {
757 758
    int shard_id = (pull_value.feasigns_[i] % _sparse_table_shard_num) %
                   _avg_local_shard_num;
Z
zhaocaibei123 已提交
759 760
    task_keys[shard_id].push_back({pull_value.feasigns_[i], i});
  }
761
  for (int shard_id = 0; shard_id < _real_local_shard_num; ++shard_id) {
Z
zhaocaibei123 已提交
762
    tasks[shard_id] =
763
        _shards_task_pool[shard_id % _shards_task_pool.size()]->enqueue(
764 765 766 767 768 769
            [this,
             shard_id,
             &task_keys,
             value_size,
             pull_values,
             mf_value_size,
Z
zhaocaibei123 已提交
770
             select_value_size]() -> int {
771
              auto& local_shard = _local_shards[shard_id];
Z
zhaocaibei123 已提交
772 773 774 775 776 777
              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;
778
                auto itr = local_shard.find(key);
Z
zhaocaibei123 已提交
779
                size_t data_size = value_size - mf_value_size;
780
                if (itr == local_shard.end()) {
Z
zhaocaibei123 已提交
781
                  // ++missed_keys;
782
                  if (FLAGS_pserver_create_value_when_push) {
Z
zhaocaibei123 已提交
783 784
                    memset(data_buffer, 0, sizeof(float) * data_size);
                  } else {
785 786 787
                    auto& feature_value = local_shard[key];
                    feature_value.resize(data_size);
                    float* data_ptr = feature_value.data();
788
                    _value_accesor->Create(&data_buffer_ptr, 1);
789 790
                    memcpy(
                        data_ptr, data_buffer_ptr, data_size * sizeof(float));
Z
zhaocaibei123 已提交
791 792
                  }
                } else {
793
                  data_size = itr.value().size();
794 795
                  memcpy(data_buffer_ptr,
                         itr.value().data(),
Z
zhaocaibei123 已提交
796 797
                         data_size * sizeof(float));
                }
798
                for (size_t mf_idx = data_size; mf_idx < value_size; ++mf_idx) {
Z
zhaocaibei123 已提交
799 800 801 802
                  data_buffer[mf_idx] = 0.0;
                }
                auto offset = keys[i].second;
                float* select_data = pull_values + select_value_size * offset;
803 804
                _value_accesor->Select(
                    &select_data, (const float**)&data_buffer_ptr, 1);
Z
zhaocaibei123 已提交
805 806 807 808 809 810 811 812 813 814 815 816
              }

              return 0;
            });
  }

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

Z
zhaocaibei123 已提交
817
int32_t MemorySparseTable::PullSparsePtr(char** pull_values,
818 819
                                         const uint64_t* keys,
                                         size_t num) {
820
  CostTimer timer("pscore_sparse_select_all");
821 822 823
  size_t value_size = _value_accesor->GetAccessorInfo().size / sizeof(float);
  size_t mf_value_size =
      _value_accesor->GetAccessorInfo().mf_size / sizeof(float);
824 825 826 827 828 829 830 831 832

  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};
833
  for (int shard_id = 0; shard_id < _real_local_shard_num; ++shard_id) {
834 835
    tasks[shard_id] =
        _shards_task_pool[shard_id % _shards_task_pool.size()]->enqueue(
836 837 838 839 840
            [this,
             shard_id,
             &task_keys,
             pull_values,
             value_size,
841 842 843
             mf_value_size]() -> int {
              auto& keys = task_keys[shard_id];
              auto& local_shard = _local_shards[shard_id];
R
Ruibiao Chen 已提交
844
              float data_buffer[value_size];  // NOLINT
845
              float* data_buffer_ptr = data_buffer;
846
              for (size_t i = 0; i < keys.size(); ++i) {
847 848 849 850 851 852 853 854 855
                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();
856
                  _value_accesor->Create(&data_buffer_ptr, 1);
857 858 859 860 861 862
                  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 已提交
863
                pull_values[pull_data_idx] = reinterpret_cast<char*>(ret);
864 865 866 867 868 869 870
              }
              return 0;
            });
  }
  for (size_t shard_id = 0; shard_id < tasks.size(); ++shard_id) {
    tasks[shard_id].wait();
  }
Z
zhaocaibei123 已提交
871 872 873
  return 0;
}

874 875
int32_t MemorySparseTable::PushSparse(const uint64_t* keys,
                                      const float* values,
Z
zhaocaibei123 已提交
876
                                      size_t num) {
877 878
  CostTimer timer("pserver_sparse_update_all");
  std::vector<std::future<int>> tasks(_real_local_shard_num);
Z
zhaocaibei123 已提交
879
  std::vector<std::vector<std::pair<uint64_t, int>>> task_keys(
880
      _real_local_shard_num);
Z
zhaocaibei123 已提交
881
  for (size_t i = 0; i < num; ++i) {
882
    int shard_id = (keys[i] % _sparse_table_shard_num) % _avg_local_shard_num;
Z
zhaocaibei123 已提交
883 884 885
    task_keys[shard_id].push_back({keys[i], i});
  }

886 887 888 889
  const size_t value_col =
      _value_accesor->GetAccessorInfo().size / sizeof(float);
  size_t mf_value_col =
      _value_accesor->GetAccessorInfo().mf_size / sizeof(float);
890
  size_t update_value_col =
891
      _value_accesor->GetAccessorInfo().update_size / sizeof(float);
Z
zhaocaibei123 已提交
892

893
  for (int shard_id = 0; shard_id < _real_local_shard_num; ++shard_id) {
894
    tasks[shard_id] = _shards_task_pool[shard_id % _task_pool_size]->enqueue(
895 896 897 898 899 900
        [this,
         shard_id,
         value_col,
         mf_value_col,
         update_value_col,
         values,
Z
zhaocaibei123 已提交
901 902
         &task_keys]() -> int {
          auto& keys = task_keys[shard_id];
903
          auto& local_shard = _local_shards[shard_id];
Z
zhaocaibei123 已提交
904
          auto& local_shard_new = _local_shards_new[shard_id];
Z
zhaocaibei123 已提交
905 906
          float data_buffer[value_col];  // NOLINT
          float* data_buffer_ptr = data_buffer;
907
          for (size_t i = 0; i < keys.size(); ++i) {
Z
zhaocaibei123 已提交
908 909 910 911
            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;
912 913 914
            auto itr = local_shard.find(key);
            if (itr == local_shard.end()) {
              if (FLAGS_pserver_enable_create_feasign_randomly &&
915
                  !_value_accesor->CreateValue(1, update_data)) {
Z
zhaocaibei123 已提交
916 917 918
                continue;
              }
              auto value_size = value_col - mf_value_col;
919 920
              auto& feature_value = local_shard[key];
              feature_value.resize(value_size);
921
              _value_accesor->Create(&data_buffer_ptr, 1);
922 923
              memcpy(feature_value.data(),
                     data_buffer_ptr,
Z
zhaocaibei123 已提交
924
                     value_size * sizeof(float));
925
              itr = local_shard.find(key);
Z
zhaocaibei123 已提交
926 927
            }

928 929 930
            auto& feature_value = itr.value();
            float* value_data = feature_value.data();
            size_t value_size = feature_value.size();
Z
zhaocaibei123 已提交
931 932

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

939
              if (_value_accesor->NeedExtendMF(data_buffer)) {
940 941
                feature_value.resize(value_col);
                value_data = feature_value.data();
942
                _value_accesor->Create(&value_data, 1);
Z
zhaocaibei123 已提交
943 944 945
              }
              memcpy(value_data, data_buffer_ptr, value_size * sizeof(float));
            }
Z
zhaocaibei123 已提交
946 947 948 949 950 951 952 953
            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 已提交
954 955 956 957 958 959 960 961 962 963 964
          }
          return 0;
        });
  }

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

Z
zhaocaibei123 已提交
965
int32_t MemorySparseTable::PushSparse(const uint64_t* keys,
966 967
                                      const float** values,
                                      size_t num) {
968
  std::vector<std::future<int>> tasks(_real_local_shard_num);
Z
zhaocaibei123 已提交
969
  std::vector<std::vector<std::pair<uint64_t, int>>> task_keys(
970
      _real_local_shard_num);
Z
zhaocaibei123 已提交
971
  for (size_t i = 0; i < num; ++i) {
972
    int shard_id = (keys[i] % _sparse_table_shard_num) % _avg_local_shard_num;
Z
zhaocaibei123 已提交
973 974 975
    task_keys[shard_id].push_back({keys[i], i});
  }

976 977 978
  size_t value_col = _value_accesor->GetAccessorInfo().size / sizeof(float);
  size_t mf_value_col =
      _value_accesor->GetAccessorInfo().mf_size / sizeof(float);
979
  size_t update_value_col =
980
      _value_accesor->GetAccessorInfo().update_size / sizeof(float);
Z
zhaocaibei123 已提交
981

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

Z
zhaocaibei123 已提交
1043 1044
int32_t MemorySparseTable::Shrink(const std::string& param) {
  VLOG(0) << "MemorySparseTable::Shrink";
Z
zhaocaibei123 已提交
1045
  // TODO(zhaocaibei123): implement with multi-thread
1046
  for (int shard_id = 0; shard_id < _real_local_shard_num; ++shard_id) {
Z
zhaocaibei123 已提交
1047
    // Shrink
1048 1049
    auto& shard = _local_shards[shard_id];
    for (auto it = shard.begin(); it != shard.end();) {
1050
      if (_value_accesor->Shrink(it.value().data())) {
1051 1052 1053
        it = shard.erase(it);
      } else {
        ++it;
Z
zhaocaibei123 已提交
1054 1055 1056 1057 1058 1059
      }
    }
  }
  return 0;
}

Z
zhaocaibei123 已提交
1060
void MemorySparseTable::Clear() { VLOG(0) << "clear coming soon"; }
Z
zhaocaibei123 已提交
1061 1062 1063

}  // namespace distributed
}  // namespace paddle