request_handler_impl.cc 14.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2018 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.

W
Wang Guibao 已提交
15
#include "paddle/fluid/operators/distributed/request_handler_impl.h"
16 17 18 19 20 21 22 23
#include <iostream>
#include <string>
#include <vector>

#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/scope.h"
#include "paddle/fluid/framework/selected_rows.h"
W
Wang Guibao 已提交
24
#include "paddle/fluid/framework/variable_helper.h"
25
#include "paddle/fluid/operators/distributed/rpc_server.h"
26
#include "paddle/fluid/string/piece.h"
T
tangwei12 已提交
27
#include "paddle/fluid/string/printf.h"
28
#include "paddle/fluid/string/split.h"
29

30 31
#include "paddle/fluid/operators/distributed/async_sparse_param_update_recorder.h"
#include "paddle/fluid/operators/distributed/heart_beat_monitor.h"
32
#include "paddle/fluid/operators/distributed/large_scale_kv.h"
33

34 35
namespace paddle {
namespace operators {
36
namespace distributed {
37

T
tangwei12 已提交
38 39
// define LOOKUP_TABLE_PATH for checkpoint notify to save lookup table variables
// to directory specified.
T
tangwei12 已提交
40
constexpr char LOOKUP_TABLE_PATH[] = "kLookupTablePath";
T
tangwei12 已提交
41

42 43 44 45
bool RequestSendHandler::Handle(const std::string &varname,
                                framework::Scope *scope,
                                framework::Variable *invar,
                                framework::Variable **outvar,
W
Wu Yi 已提交
46
                                const int trainer_id,
47 48
                                const std::string &out_var_name,
                                const std::string &table_name) {
M
minqiyang 已提交
49
  VLOG(4) << "RequestSendHandler:" << varname;
50

T
tangwei12 已提交
51 52 53 54 55 56
  // Sync
  if (varname == BATCH_BARRIER_MESSAGE) {
    VLOG(3) << "sync: recv BATCH_BARRIER_MESSAGE";
    rpc_server_->IncreaseBatchBarrier(kRequestSend);
  } else if (varname == COMPLETE_MESSAGE) {
    VLOG(3) << "sync: recv complete message";
57

T
tangwei12 已提交
58 59 60
    if (HeartBeatMonitor::GetInstance() != nullptr) {
      HeartBeatMonitor::GetInstance()->Update(trainer_id, "", COMPLETED);
    }
61

T
tangwei12 已提交
62 63 64 65 66 67
    rpc_server_->Complete();
  } else {
    // Async
    if (distributed_mode_ != DistributedMode::kSync) {
      VLOG(3) << "async process var: " << varname;
      if (varname == BATCH_BARRIER_MESSAGE) {
M
MRXLT 已提交
68
        PADDLE_THROW(platform::errors::InvalidArgument(
T
tangwei12 已提交
69
            "async mode should not recv BATCH_BARRIER_MESSAGE or "
M
MRXLT 已提交
70
            "COMPLETE_MESSAGE"));
T
tangwei12 已提交
71 72
      }
      HeartBeatMonitor::GetInstance()->Update(trainer_id, varname, RUNNING);
73

T
tangwei12 已提交
74
      std::string run_varname = varname;
75

T
tangwei12 已提交
76 77
      string::Piece part_piece("@PIECE");
      string::Piece var_name_piece = string::Piece(varname);
78

T
tangwei12 已提交
79 80
      if (string::Contains(var_name_piece, part_piece)) {
        auto varname_splits = paddle::string::Split(varname, '@');
M
MRXLT 已提交
81 82 83 84
        PADDLE_ENFORCE_EQ(
            varname_splits.size(), 3,
            platform::errors::InvalidArgument(
                "varname: %s should be separated into 3 parts by @", varname));
T
tangwei12 已提交
85 86 87
        run_varname = varname_splits[0];
        scope->Rename(varname, run_varname);
      }
88

89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
      auto *var = scope->FindVar(run_varname);

      // for sparse ids
      if (var->IsType<framework::SelectedRows>()) {
        if (distributed_mode_ == DistributedMode::kAsync ||
            distributed_mode_ == DistributedMode::kHalfAsync) {
          auto *ins = distributed::LargeScaleKV::GetInstance();
          if (ins->GradInLargeScale(run_varname)) {
            auto *large_scale_var = ins->GetByGrad(run_varname);

            for (auto name : large_scale_var->CachedVarnames()) {
              scope->Var(name);
            }
          }
        }
        if (distributed_mode_ == DistributedMode::kGeo) {
          if (AsyncSparseParamUpdateRecorder::GetInstance()->HasGrad(
                  run_varname)) {
            auto &grad_slr =
                scope->FindVar(run_varname)->Get<framework::SelectedRows>();
            AsyncSparseParamUpdateRecorder::GetInstance()->Update(
                run_varname, grad_slr.rows());
          }
        }
T
tangwei12 已提交
113
      }
114

T
tangwei12 已提交
115 116 117 118 119 120 121 122 123 124 125
      executor_->RunPreparedContext((*grad_to_prepared_ctx_)[run_varname].get(),
                                    scope);
      return true;
    } else {  // sync
      rpc_server_->WaitCond(kRequestSend);
      VLOG(3) << "sync: processing received var: " << varname;
      PADDLE_ENFORCE_NOT_NULL(
          invar, platform::errors::NotFound(
                     "sync: Can not find server side var %s.", varname));
    }
  }
126 127 128
  return true;
}

129 130 131 132
bool RequestGetHandler::Handle(const std::string &varname,
                               framework::Scope *scope,
                               framework::Variable *invar,
                               framework::Variable **outvar,
W
Wu Yi 已提交
133
                               const int trainer_id,
134 135
                               const std::string &out_var_name,
                               const std::string &table_name) {
Q
Qiao Longfei 已提交
136 137 138
  VLOG(3) << "RequestGetHandler:" << varname
          << " out_var_name: " << out_var_name << " trainer_id: " << trainer_id
          << " table_name: " << table_name;
139

1
123malin 已提交
140
  if (distributed_mode_ == DistributedMode::kSync) {
T
tangwei12 已提交
141 142 143 144 145 146
    if (varname == FETCH_BARRIER_MESSAGE) {
      VLOG(3) << "sync: recv fetch barrier message";
      rpc_server_->IncreaseBatchBarrier(kRequestGet);
    } else {
      rpc_server_->WaitCond(kRequestGet);
      *outvar = scope_->FindVar(varname);
T
tangwei12 已提交
147
    }
T
tangwei12 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161
  } else {
    if (varname != FETCH_BARRIER_MESSAGE && varname != COMPLETE_MESSAGE) {
      if (enable_dc_asgd_) {
        // NOTE: the format is determined by distribute_transpiler.py
        std::string param_bak_name =
            string::Sprintf("%s.trainer_%d_bak", varname, trainer_id);
        VLOG(3) << "getting " << param_bak_name << " trainer_id " << trainer_id;
        auto var = scope_->FindVar(varname);
        auto t_orig = var->Get<framework::LoDTensor>();
        auto param_bak = scope_->Var(param_bak_name);
        auto t = param_bak->GetMutable<framework::LoDTensor>();
        t->mutable_data(dev_ctx_->GetPlace(), t_orig.type());
        VLOG(3) << "copying " << varname << " to " << param_bak_name;
        framework::TensorCopy(t_orig, dev_ctx_->GetPlace(), t);
T
tangwei12 已提交
162
      }
163

T
tangwei12 已提交
164 165 166
      if (distributed_mode_ == DistributedMode::kGeo &&
          AsyncSparseParamUpdateRecorder::GetInstance()->HasParam(varname) &&
          !table_name.empty()) {
167 168
        VLOG(3) << "AsyncSparseParamUpdateRecorder " << varname << " exist ";

T
tangwei12 已提交
169 170 171
        std::vector<int64_t> updated_rows;
        AsyncSparseParamUpdateRecorder::GetInstance()->GetAndClear(
            varname, trainer_id, &updated_rows);
172

T
tangwei12 已提交
173 174 175
        if (VLOG_IS_ON(3)) {
          std::ostringstream sstream;
          sstream << "[";
176
          for (auto &row_id : updated_rows) {
T
tangwei12 已提交
177 178 179 180 181 182
            sstream << row_id << ", ";
          }
          sstream << "]";
          VLOG(3) << "updated_rows size: " << updated_rows.size() << " "
                  << sstream.str();
        }
183 184

        auto &origin_tensor =
T
tangwei12 已提交
185
            scope_->FindVar(varname)->Get<framework::LoDTensor>();
186 187
        auto *origin_tensor_data = origin_tensor.data<float>();
        auto &dims = origin_tensor.dims();
T
tangwei12 已提交
188
        *outvar = scope->Var();
189
        auto *out_slr = (*outvar)->GetMutable<framework::SelectedRows>();
T
tangwei12 已提交
190 191 192 193
        out_slr->set_rows(updated_rows);
        out_slr->set_height(dims[0]);
        auto out_dims = framework::make_ddim(
            {static_cast<int64_t>(updated_rows.size()), dims[1]});
194
        auto *data = out_slr->mutable_value()->mutable_data<float>(
T
tangwei12 已提交
195 196 197
            out_dims, origin_tensor.place());
        auto width = dims[1];
        for (size_t i = 0; i < updated_rows.size(); ++i) {
M
MRXLT 已提交
198 199 200 201 202
          PADDLE_ENFORCE_LT(
              updated_rows[i], dims[0],
              platform::errors::OutOfRange(
                  "The value of updated_rows: %s out of Tensor %s dims[0]: %s",
                  updated_rows[i], varname, dims[0]));
T
tangwei12 已提交
203 204 205 206 207
          memcpy(data + i * width, origin_tensor_data + updated_rows[i] * width,
                 sizeof(float) * width);
        }
      } else {
        *outvar = scope_->FindVar(varname);
208
      }
209 210 211 212 213
    }
  }
  return true;
}

214 215 216 217
bool RequestGetNoBarrierHandler::Handle(const std::string &varname,
                                        framework::Scope *scope,
                                        framework::Variable *invar,
                                        framework::Variable **outvar,
218
                                        const int trainer_id,
219 220
                                        const std::string &out_var_name,
                                        const std::string &table_name) {
221 222 223 224 225 226 227 228 229 230 231 232 233 234
  VLOG(4) << "RequestGetNoBarrierHandler:" << varname
          << " out_var_name: " << out_var_name;

  // get var from pserver immediately without barriers
  string::Piece without_barrier_piece(WITHOUT_BARRIER_MESSAGE);
  string::Piece var_name_piece = string::Piece(varname);

  if (string::Contains(var_name_piece, without_barrier_piece)) {
    var_name_piece = string::TrimSuffix(var_name_piece, without_barrier_piece);
    VLOG(4) << "Get var " << var_name_piece << " with "
            << WITHOUT_BARRIER_MESSAGE;
    *outvar = scope_->FindVar(var_name_piece.ToString());
    return true;
  } else {
M
MRXLT 已提交
235 236
    PADDLE_THROW(platform::errors::InvalidArgument(
        "GetNoBarrier must contain %s", WITHOUT_BARRIER_MESSAGE));
237 238 239 240
  }
  return true;
}

241 242 243 244
bool RequestPrefetchHandler::Handle(const std::string &varname,
                                    framework::Scope *scope,
                                    framework::Variable *invar,
                                    framework::Variable **outvar,
W
Wu Yi 已提交
245
                                    const int trainer_id,
246 247
                                    const std::string &out_var_name,
                                    const std::string &table_name) {
M
minqiyang 已提交
248
  VLOG(4) << "RequestPrefetchHandler " << varname;
249

250 251 252 253 254 255 256 257 258 259 260
  (*outvar)->GetMutable<framework::LoDTensor>();

  VLOG(1) << "Prefetch "
          << "tablename: " << table_name << " ids:" << varname
          << " out: " << out_var_name;
  paddle::platform::CPUPlace cpu_place;
  auto *ins = distributed::LargeScaleKV::GetInstance();

  if (ins->ParamInLargeScale(table_name)) {
    auto lookup_table_op = PullLargeScaleOp(table_name, varname, out_var_name);
    lookup_table_op->Run(*scope, cpu_place);
Q
Qiao Longfei 已提交
261 262 263 264 265
  } else {
    auto lookup_table_op =
        BuildLookupTableOp(table_name, varname, out_var_name);
    lookup_table_op->Run(*scope, cpu_place);
  }
266

267 268 269
  return true;
}

270 271 272 273
bool RequestCheckpointHandler::Handle(const std::string &varname,
                                      framework::Scope *scope,
                                      framework::Variable *invar,
                                      framework::Variable **outvar,
W
Wu Yi 已提交
274
                                      const int trainer_id,
275 276
                                      const std::string &out_var_name,
                                      const std::string &table_name) {
277 278 279 280
  VLOG(4) << "receive save var " << varname << " with path " << out_var_name
          << " mode " << table_name;

  int mode = std::stoi(table_name);
281 282

  auto *ins = distributed::LargeScaleKV::GetInstance();
283
  ins->Get(varname)->Save(out_var_name, mode);
T
bug fix  
tangwei12 已提交
284 285
  return true;
}
T
tangwei12 已提交
286

287 288 289 290
bool RequestNotifyHandler::Handle(const std::string &varname,
                                  framework::Scope *scope,
                                  framework::Variable *invar,
                                  framework::Variable **outvar,
291
                                  const int trainer_id,
292 293 294 295
                                  const std::string &out_var_name,
                                  const std::string &table_name) {
  VLOG(3) << "RequestNotifyHandler: " << varname
          << ", trainer_id: " << trainer_id;
1
123malin 已提交
296

297
  string::Piece decay_piece(STEP_COUNTER);
1
123malin 已提交
298
  string::Piece var_name_piece = string::Piece(varname);
T
tangwei12 已提交
299
  if (string::Contains(var_name_piece, decay_piece)) {
1
123malin 已提交
300
    VLOG(3) << "LearningRate Decay Counter Update";
301 302

    auto *send_var = scope->FindVar(varname);
1
123malin 已提交
303
    auto send_var_tensor = send_var->Get<framework::LoDTensor>();
304
    auto *send_value =
1
123malin 已提交
305
        send_var_tensor.mutable_data<int64_t>(send_var_tensor.place());
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

    auto counter = decay_counters.at(trainer_id);
    counter += send_value[0];
    decay_counters.at(trainer_id) = counter;

    auto *global_step_var = this->scope()->FindVar(LEARNING_RATE_DECAY_COUNTER);
    if (global_step_var == nullptr) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "can not find LEARNING_RATE_DECAY_COUNTER "));
    }

    auto *tensor = global_step_var->GetMutable<framework::LoDTensor>();
    auto *value = tensor->mutable_data<int64_t>(platform::CPUPlace());

    auto global_counter = 0;
    for (auto &trainer_counter : decay_counters) {
      global_counter += trainer_counter.second;
    }
    value[0] = global_counter;

    if (lr_decay_prepared_ctx_.get() == nullptr) {
      PADDLE_THROW(platform::errors::InvalidArgument(
          "can not find decay block for executor"));
    }

331 332 333 334 335
    executor_->RunPreparedContext(lr_decay_prepared_ctx_.get(), scope_);
  }
  return true;
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
bool RequestSendAndRecvHandler::Handle(const std::string &varname,
                                       framework::Scope *Scope,
                                       framework::Variable *var,
                                       framework::Variable **outvar,
                                       const int trainer_id,
                                       const std::string &out_var_name,
                                       const std::string &table_name) {
  VLOG(3) << "SendAndRecvHandle: " << varname
          << " out_var_name: " << out_var_name
          << " , trainer_id:  " << trainer_id;

  executor_->RunPreparedContext((*grad_to_prepared_ctx_)[varname].get(), Scope);
  *outvar = Scope->FindVar(out_var_name);
  return true;
}

352
}  // namespace distributed
353 354
}  // namespace operators
}  // namespace paddle