request_handler_impl.cc 11.8 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
#include "paddle/fluid/operators/distributed/async_sparse_param_update_recorder.h"
T
tangwei12 已提交
31
#include "paddle/fluid/operators/distributed/barrier_monitor.h"
32 33
#include "paddle/fluid/operators/distributed/heart_beat_monitor.h"

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

T
tangwei12 已提交
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,
T
tangwei12 已提交
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
  if (invar == nullptr) {
    PADDLE_THROW(platform::errors::NotFound(
        "sync: Can not find server side var: %s", varname));
    return false;
  }
56

T
tangwei12 已提交
57 58 59
  if (distributed_mode_ == DistributedMode::kSync) {
    return true;
  }
60

T
tangwei12 已提交
61
  HeartBeatMonitor::GetInstance()->Update(trainer_id, varname, RUNNING);
62

T
tangwei12 已提交
63 64 65
  std::string run_varname = varname;
  string::Piece part_piece("@PIECE");
  string::Piece var_name_piece = string::Piece(varname);
66

T
tangwei12 已提交
67 68 69 70 71
  if (string::Contains(var_name_piece, part_piece)) {
    auto varname_splits = paddle::string::Split(varname, '@');
    run_varname = varname_splits[0];
    scope->Rename(varname, run_varname);
  }
72

T
tangwei12 已提交
73 74 75 76 77 78 79
  if (distributed_mode_ == DistributedMode::kGeo &&
      AsyncSparseParamUpdateRecorder::GetInstance()->HasGrad(run_varname)) {
    auto &grad_slr =
        scope->FindVar(run_varname)->Get<framework::SelectedRows>();
    AsyncSparseParamUpdateRecorder::GetInstance()->Update(run_varname,
                                                          grad_slr.rows());
  }
80

T
tangwei12 已提交
81 82
  executor_->RunPreparedContext((*grad_to_prepared_ctx_)[run_varname].get(),
                                scope);
83

84 85 86
  return true;
}

T
tangwei12 已提交
87 88 89 90
bool RequestGetHandler::Handle(const std::string &varname,
                               framework::Scope *scope,
                               framework::Variable *invar,
                               framework::Variable **outvar,
W
Wu Yi 已提交
91
                               const int trainer_id,
T
tangwei12 已提交
92 93
                               const std::string &out_var_name,
                               const std::string &table_name) {
Q
Qiao Longfei 已提交
94 95 96
  VLOG(3) << "RequestGetHandler:" << varname
          << " out_var_name: " << out_var_name << " trainer_id: " << trainer_id
          << " table_name: " << table_name;
97

1
123malin 已提交
98
  if (distributed_mode_ == DistributedMode::kSync) {
T
tangwei12 已提交
99
    *outvar = scope_->FindVar(varname);
Y
Yancey1989 已提交
100
  } else {
T
tangwei12 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    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);
    }

    if (distributed_mode_ == DistributedMode::kGeo &&
        AsyncSparseParamUpdateRecorder::GetInstance()->HasParam(varname) &&
        !table_name.empty()) {
      std::vector<int64_t> updated_rows;
      AsyncSparseParamUpdateRecorder::GetInstance()->GetAndClear(
          varname, trainer_id, &updated_rows);
      if (VLOG_IS_ON(3)) {
        std::ostringstream sstream;
        sstream << "[";
        for (auto &row_id : updated_rows) {
          sstream << row_id << ", ";
126
        }
T
tangwei12 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
        sstream << "]";
        VLOG(3) << "updated_rows size: " << updated_rows.size() << " "
                << sstream.str();
      }
      auto &origin_tensor =
          scope_->FindVar(varname)->Get<framework::LoDTensor>();
      auto *origin_tensor_data = origin_tensor.data<float>();
      auto &dims = origin_tensor.dims();
      *outvar = scope->Var();
      auto *out_slr = (*outvar)->GetMutable<framework::SelectedRows>();
      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]});
      auto *data = out_slr->mutable_value()->mutable_data<float>(
          out_dims, origin_tensor.place());
      auto width = dims[1];
      for (size_t i = 0; i < updated_rows.size(); ++i) {
        PADDLE_ENFORCE_LT(updated_rows[i], dims[0],
                          platform::errors::OutOfRange(
                              "expected >= 0 and < %ld, but got %ld.", dims[0],
                              updated_rows[i]));
        memcpy(data + i * width, origin_tensor_data + updated_rows[i] * width,
               sizeof(float) * width);
151
      }
T
tangwei12 已提交
152 153
    } else {
      *outvar = scope_->FindVar(varname);
154 155 156 157 158
    }
  }
  return true;
}

T
tangwei12 已提交
159 160 161 162
bool RequestGetNoBarrierHandler::Handle(const std::string &varname,
                                        framework::Scope *scope,
                                        framework::Variable *invar,
                                        framework::Variable **outvar,
163
                                        const int trainer_id,
T
tangwei12 已提交
164 165
                                        const std::string &out_var_name,
                                        const std::string &table_name) {
166 167 168 169 170 171 172 173 174 175 176 177 178 179
  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 {
T
tangwei12 已提交
180 181
    PADDLE_THROW(platform::errors::InvalidArgument(
        "GetNoBarrier must contain %s", WITHOUT_BARRIER_MESSAGE));
182 183 184 185
  }
  return true;
}

T
tangwei12 已提交
186 187 188 189
bool RequestPrefetchHandler::Handle(const std::string &varname,
                                    framework::Scope *scope,
                                    framework::Variable *invar,
                                    framework::Variable **outvar,
W
Wu Yi 已提交
190
                                    const int trainer_id,
T
tangwei12 已提交
191 192
                                    const std::string &out_var_name,
                                    const std::string &table_name) {
M
minqiyang 已提交
193
  VLOG(4) << "RequestPrefetchHandler " << varname;
194

Q
Qiao Longfei 已提交
195
  if (table_name.empty()) {
Q
Qiao Longfei 已提交
196 197
    auto var_desc = program_->Block(0).FindVar(out_var_name);
    InitializeVariable(*outvar, var_desc->GetType());
Q
Qiao Longfei 已提交
198 199 200
    executor_->RunPreparedContext(
        (*prefetch_var_name_to_prepared_ctx_)[varname].get(), scope);
  } else {
Q
Qiao Longfei 已提交
201
    (*outvar)->GetMutable<framework::LoDTensor>();
Q
Qiao Longfei 已提交
202 203 204 205 206
    auto lookup_table_op =
        BuildLookupTableOp(table_name, varname, out_var_name);
    paddle::platform::CPUPlace cpu_place;
    lookup_table_op->Run(*scope, cpu_place);
  }
207 208 209
  return true;
}

T
tangwei12 已提交
210 211 212 213
bool RequestCheckpointHandler::Handle(const std::string &varname,
                                      framework::Scope *scope,
                                      framework::Variable *invar,
                                      framework::Variable **outvar,
W
Wu Yi 已提交
214
                                      const int trainer_id,
T
tangwei12 已提交
215 216 217 218 219 220
                                      const std::string &out_var_name,
                                      const std::string &table_name) {
  PADDLE_ENFORCE_NE(
      checkpoint_notify_id, -1,
      platform::errors::Unavailable(
          "when checkpoint_notify_id = -1, there should be no RPC invoke."));
T
tangwei12 已提交
221

T
tangwei12 已提交
222
  // TODO(tangwei12): find out why scope will be error.
T
tangwei12 已提交
223
  auto *lt_var = scope_->FindVar(LOOKUP_TABLE_PATH)->GetMutable<std::string>();
T
tangwei12 已提交
224 225
  lt_var->clear();
  lt_var->append(out_var_name);
M
minqiyang 已提交
226 227
  VLOG(4) << "RequestCheckpointHandler update var kLookupTablePath to: "
          << out_var_name;
T
bug fix  
tangwei12 已提交
228
  executor_->RunPreparedContext(checkpoint_prepared_ctx_.get(), scope_);
T
bug fix  
tangwei12 已提交
229 230
  return true;
}
T
tangwei12 已提交
231

T
tangwei12 已提交
232 233 234 235
bool RequestNotifyHandler::Handle(const std::string &varname,
                                  framework::Scope *scope,
                                  framework::Variable *invar,
                                  framework::Variable **outvar,
236
                                  const int trainer_id,
T
tangwei12 已提交
237 238
                                  const std::string &out_var_name,
                                  const std::string &table_name) {
1
123malin 已提交
239 240 241
  VLOG(3) << "async process var: " << varname << ", trainer_id: " << trainer_id;

  string::Piece decay_piece(LEARNING_RATE_DECAY_COUNTER);
T
tangwei12 已提交
242 243 244 245
  string::Piece batch_piece(BATCH_BARRIER_MESSAGE);
  string::Piece fetch_piece(FETCH_BARRIER_MESSAGE);
  string::Piece complete_piece(COMPLETE_MESSAGE);

1
123malin 已提交
246
  string::Piece var_name_piece = string::Piece(varname);
T
tangwei12 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

  if (string::Contains(var_name_piece, batch_piece)) {
    return BarrierMonitor::GetInstance()->IncreaseBarrier(
        trainer_id, BATCH_BARRIER_MESSAGE);
  } else if (string::Contains(var_name_piece, fetch_piece)) {
    return BarrierMonitor::GetInstance()->IncreaseBarrier(
        trainer_id, FETCH_BARRIER_MESSAGE);
  } else if (string::Contains(var_name_piece, complete_piece)) {
    if (HeartBeatMonitor::GetInstance() != nullptr) {
      HeartBeatMonitor::GetInstance()->Update(trainer_id, "", COMPLETED);
    }
    rpc_server_->Complete();
    BarrierMonitor::GetInstance()->DecreaseWorker();
    return true;
  } else if (string::Contains(var_name_piece, decay_piece)) {
1
123malin 已提交
262
    VLOG(3) << "LearningRate Decay Counter Update";
263 264
    PADDLE_ENFORCE_NE(
        lr_decay_block_id, -1,
T
tangwei12 已提交
265 266 267
        platform::errors::InvalidArgument(
            "when lr_decay_block_id = -1, there should be no RPC invoke."));
    auto *origin_var = scope_->FindVar(varname);
1
123malin 已提交
268
    auto origin_var_tensor = origin_var->Get<framework::LoDTensor>();
T
tangwei12 已提交
269
    auto *send_var = scope->FindVar(varname);
1
123malin 已提交
270
    auto send_var_tensor = send_var->Get<framework::LoDTensor>();
T
tangwei12 已提交
271
    int64_t *origin_value =
1
123malin 已提交
272
        origin_var_tensor.mutable_data<int64_t>(origin_var_tensor.place());
T
tangwei12 已提交
273
    int64_t *send_value =
1
123malin 已提交
274 275
        send_var_tensor.mutable_data<int64_t>(send_var_tensor.place());
    origin_value[0] += send_value[0];
276
    executor_->RunPreparedContext(lr_decay_prepared_ctx_.get(), scope_);
T
tangwei12 已提交
277 278 279 280 281

    return true;
  } else {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "unkown varname %s with RequestNotifyHandler", varname));
282 283 284 285
  }
  return true;
}

286
}  // namespace distributed
287 288
}  // namespace operators
}  // namespace paddle