variable_response.cc 14.4 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.

15
#include "paddle/fluid/operators/distributed/variable_response.h"
Y
Yi Wang 已提交
16 17 18 19

#include <string>
#include <utility>
#include <vector>
T
typhoonzero 已提交
20 21 22
#ifdef PADDLE_WITH_CUDA
#include <nccl.h>
#endif
23
#include "paddle/fluid/platform/profiler.h"
Y
Yi Wang 已提交
24

25 26
#include "paddle/fluid/operators/distributed/send_recv.pb.h"
#include "paddle/fluid/operators/distributed/sendrecvop_utils.h"
27 28 29

namespace paddle {
namespace operators {
30
namespace distributed {
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

enum WireType {
  WIRETYPE_VARINT = 0,
  WIRETYPE_LENGTH_DELIMITED = 2,
};

inline int GetTagFieldNumber(uint32_t tag) { return tag >> 3; }

inline WireType GetTagWireType(uint32_t tag) {
  return static_cast<WireType>(tag & 0x7);
}

bool ReadVarintSizeAsInt(::google::protobuf::io::CodedInputStream* input,
                         int* result) {
  uint64_t v;
  if (input->ReadVarint64(&v) && v <= static_cast<uint64_t>(INT_MAX)) {
    *result = static_cast<int>(v);
    return true;
  } else {
    return false;
  }
}

bool ReadRaw(::google::protobuf::io::CodedInputStream* input,
             const platform::DeviceContext& dev_ctx, platform::Place place,
             void* dest, int size) {
  const void* data = NULL;
  int size_to_write = 0;
Y
yi.wu 已提交
59 60
  int length = size;
  int total_written = 0;
61 62 63 64 65 66 67 68

  if (platform::is_gpu_place(place)) {
#ifdef PADDLE_WITH_CUDA
    auto& gpu_dev_ctx =
        static_cast<const platform::CUDADeviceContext&>(dev_ctx);
    platform::CPUPlace cpu;

    char* p = reinterpret_cast<char*>(dest);
Y
yi.wu 已提交
69
    while (total_written < length) {
70 71 72
      if (!input->GetDirectBufferPointer(&data, &size_to_write)) {
        return false;
      }
Y
yi.wu 已提交
73 74 75 76 77 78
      // NOTE: if raw buffer is large and have two neighbor fields of raw
      // buffers GetDirectBufferPointer can get all of them, use length to
      // truncate it.
      if (total_written + size_to_write > length) {
        size_to_write = length - total_written;
      }
G
gongweibao 已提交
79 80
      // This log is useful to see how long a internal block size is of rpc.
      VLOG(7) << "copy " << size_to_write << " data to CUDAPlace";
81 82 83 84
      memory::Copy(boost::get<platform::CUDAPlace>(place),
                   reinterpret_cast<void*>(p), cpu, data, size_to_write,
                   gpu_dev_ctx.stream());
      p += size_to_write;
Y
yi.wu 已提交
85
      total_written += size_to_write;
86 87 88 89 90 91 92 93 94 95 96

      input->Skip(size_to_write);
    }
    gpu_dev_ctx.Wait();
#else
    PADDLE_THROW("Unexpected branch");
#endif
    return true;
  }

  char* p = reinterpret_cast<char*>(dest);
Y
yi.wu 已提交
97
  while (total_written < length) {
98 99 100
    if (!input->GetDirectBufferPointer(&data, &size_to_write)) {
      return false;
    }
Y
yi.wu 已提交
101 102 103 104 105
    // NOTE: if raw buffer is large and have two neighbor fields of raw buffers
    // GetDirectBufferPointer can get all of them, use length to truncate it.
    if (total_written + size_to_write > length) {
      size_to_write = length - total_written;
    }
106 107
    // TODO(gongwb): can we avoid copy?
    platform::CPUPlace cpu;
G
gongweibao 已提交
108 109
    // This log is useful to see how long a internal block size is of rpc.
    VLOG(7) << "copy " << size_to_write << " data to CPUPlace";
110 111 112
    memory::Copy(cpu, reinterpret_cast<void*>(p), cpu, data, size_to_write);

    p += size_to_write;
Y
yi.wu 已提交
113
    total_written += size_to_write;
114 115 116 117 118 119 120 121 122

    input->Skip(size_to_write);
  }

  return true;
}

bool VariableResponse::CopyLodTensorData(
    ::google::protobuf::io::CodedInputStream* input,
Y
Yancey1989 已提交
123 124
    const platform::DeviceContext& ctx, const framework::DDim& dims,
    int length) {
125
  auto* tensor = GetVar()->GetMutable<framework::LoDTensor>();
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
  tensor->Resize(dims);

  framework::LoD lod;
  for (int i = 0; i < meta_.lod_level(); ++i) {
    framework::Vector<size_t> v;
    for (int j = 0; j < meta_.lod(i).lod_data_size(); ++j) {
      v.push_back(meta_.lod(i).lod_data(j));
    }
    lod.push_back(v);
  }
  tensor->set_lod(lod);

  void* tensor_data =
      tensor->mutable_data(ctx.GetPlace(), ToTypeIndex(meta_.data_type()));

  if (!ReadRaw(input, ctx, tensor->place(), tensor_data, length)) {
    return false;
  }

  return true;
}

inline framework::DDim GetDims(
    const ::google::protobuf::RepeatedField<::google::protobuf::int64>& dims) {
  std::vector<int> vecdims;
  for (auto& d : dims) {
    vecdims.push_back(d);
  }
  return framework::make_ddim(vecdims);
}

bool VariableResponse::CopySelectRowsTensorData(
    ::google::protobuf::io::CodedInputStream* input,
Y
Yancey1989 已提交
159 160
    const platform::DeviceContext& ctx, const framework::DDim& dims,
    int length) {
161
  auto* slr = GetVar()->GetMutable<framework::SelectedRows>();
162
  slr->set_height(meta_.slr_height());
163 164
  auto* tensor = slr->mutable_value();
  tensor->Resize(dims);
165 166 167 168
  PADDLE_ENFORCE_EQ(static_cast<size_t>(tensor->numel()),
                    length / framework::SizeOfType(
                                 paddle::operators::distributed::ToTypeIndex(
                                     meta_.data_type())));
169 170
  void* tensor_data = tensor->mutable_data(
      ctx.GetPlace(),
171
      paddle::operators::distributed::ToTypeIndex(meta_.data_type()));
172 173 174 175 176 177 178 179 180 181 182

  if (!ReadRaw(input, ctx, tensor->place(), tensor_data, length)) {
    return false;
  }

  return true;
}

bool VariableResponse::CopySelectRowsData(
    ::google::protobuf::io::CodedInputStream* input,
    const platform::DeviceContext& ctx, int length) {
183
  auto* slr = GetVar()->GetMutable<framework::SelectedRows>();
T
typhoonzero 已提交
184 185
  slr->mutable_rows()->resize(length /
                              framework::SizeOfType(typeid(int64_t)));  // int64
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
  int64_t* rows_data = slr->mutable_rows()->data();

  // copy rows CPU data, GPU data will be copied lazily.
  platform::CPUPlace cpu;
  if (!ReadRaw(input, ctx, cpu, rows_data, length)) {
    return false;
  }

  return true;
}

bool ParseLodData(::google::protobuf::io::CodedInputStream* input,
                  std::vector<int64_t>* lod) {
  while (true) {
    auto p = input->ReadTagWithCutoff(127);
    int tag = GetTagFieldNumber(p.first);
    WireType wt = GetTagWireType(p.first);

    if (!p.second) {
      return (tag == 0);
    }

    switch (tag) {
      case sendrecv::VariableMessage_LodData::kLodDataFieldNumber: {
        uint64_t v;
        if (wt == WIRETYPE_VARINT) {
          if (!input->ReadVarint64(&v)) {
            return false;
          }
          lod->push_back(v);
          break;
        }

        if (wt == WIRETYPE_LENGTH_DELIMITED) {
T
typhoonzero 已提交
220 221
          int num_bytes = 0;
          if (!input->ReadVarintSizeAsInt(&num_bytes)) {
222 223
            return tag;
          }
T
typhoonzero 已提交
224 225
          int start_pos = input->CurrentPosition();
          while (input->CurrentPosition() - start_pos < num_bytes) {
226 227
            uint64_t v;
            if (!input->ReadVarint64(&v)) {
T
typhoonzero 已提交
228
              return tag;
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
            }
            lod->push_back(v);
          }
          break;
        }

        return false;
      }
      default: { return false; }
    }
  }

  return true;
}

int VariableResponse::Parse(const ::grpc::ByteBuffer& byte_buffer) {
  GrpcByteBufferSource source;
  source.Init(byte_buffer);
  GrpcByteBufferSourceWrapper r(&source);

  return Parse(&r);
}

int VariableResponse::Parse(Source* source) {
  ::google::protobuf::io::ZeroCopyInputStream* input_stream =
      source->contents();
  ::google::protobuf::io::CodedInputStream input(input_stream);
  input.SetTotalBytesLimit(INT_MAX, INT_MAX);

  while (true) {
    auto p = input.ReadTagWithCutoff(127);
    int tag = GetTagFieldNumber(p.first);
    WireType wt = GetTagWireType(p.first);
    if (!p.second) {
      if (tag != 0) {
        return -1;
      }
      return 0;
    }

    switch (tag) {
      case sendrecv::VariableMessage::kVarnameFieldNumber: {
        uint32_t length;
        if ((wt != WIRETYPE_LENGTH_DELIMITED) || !input.ReadVarint32(&length)) {
          return tag;
        }

        std::string temp;
        if (!input.ReadString(&temp, length)) {
          return tag;
        }

        meta_.set_varname(temp);
        break;
      }
      case sendrecv::VariableMessage::kTypeFieldNumber: {
T
typhoonzero 已提交
285 286
        uint32_t v;
        if ((wt != WIRETYPE_VARINT) || !input.ReadVarint32(&v)) {
287 288 289 290 291 292 293
          return tag;
        }

        meta_.set_type(static_cast<::sendrecv::VarType>(v));
        break;
      }
      case sendrecv::VariableMessage::kDataTypeFieldNumber: {
T
typhoonzero 已提交
294 295
        uint32_t v = 0;
        if ((wt != WIRETYPE_VARINT) || !input.ReadVarint32(&v)) {
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
          return tag;
        }

        meta_.set_data_type(static_cast<::sendrecv::VariableMessage_Type>(v));
        break;
      }
      case sendrecv::VariableMessage::kDimsFieldNumber: {
        // not packed
        if (wt == WIRETYPE_VARINT) {
          uint64_t v;
          if (!input.ReadVarint64(&v)) {
            return tag;
          }
          meta_.add_dims(v);
          break;
        }

        // packed
        if (wt == WIRETYPE_LENGTH_DELIMITED) {
T
typhoonzero 已提交
315 316
          int num_bytes = 0;
          if (!input.ReadVarintSizeAsInt(&num_bytes)) {
317 318
            return tag;
          }
T
typhoonzero 已提交
319 320
          int start_pos = input.CurrentPosition();
          while (input.CurrentPosition() - start_pos < num_bytes) {
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
            uint64_t v;
            if (!input.ReadVarint64(&v)) {
              return tag;
            }
            meta_.add_dims(v);
          }
          break;
        }
        return tag;
      }
      case sendrecv::VariableMessage::kLodLevelFieldNumber: {
        uint64_t v = 0;
        if ((wt != WIRETYPE_VARINT) || !input.ReadVarint64(&v)) {
          return tag;
        }
        meta_.set_lod_level(static_cast<int64_t>(v));
        break;
      }
      case sendrecv::VariableMessage::kLodFieldNumber: {
        int length = 0;
        if (wt != WIRETYPE_LENGTH_DELIMITED ||
            !ReadVarintSizeAsInt(&input, &length)) {
          return tag;
        }

        std::pair<::google::protobuf::io::CodedInputStream::Limit, int> p =
            input.IncrementRecursionDepthAndPushLimit(length);

        std::vector<int64_t> lod_data;
        if (p.second < 0 || !ParseLodData(&input, &lod_data)) {
          return tag;
        }

        if (!input.DecrementRecursionDepthAndPopLimit(p.first)) {
          return false;
        }

        if (lod_data.size() == 0) {
          break;
        }

        auto lod = meta_.add_lod();
        for (uint32_t i = 0; i < lod_data.size(); i++) {
          lod->add_lod_data(lod_data[i]);
        }
        break;
      }
368 369 370 371 372 373 374 375
      case sendrecv::VariableMessage::kSlrHeightFieldNumber: {
        uint64_t v = 0;
        if ((wt != WIRETYPE_VARINT) || !input.ReadVarint64(&v)) {
          return tag;
        }
        meta_.set_slr_height(static_cast<int64_t>(v));
        break;
      }
376 377
      case sendrecv::VariableMessage::kSerializedFieldNumber: {
        PADDLE_ENFORCE((meta_.type() == sendrecv::SELECTED_ROWS ||
T
typhoonzero 已提交
378 379
                        meta_.type() == sendrecv::LOD_TENSOR ||
                        meta_.type() == sendrecv::NCCL_ID) &&
380 381 382
                           meta_.varname() != "",
                       "meta info should be got first!");

T
typhoonzero 已提交
383
        int num_bytes = 0;
T
typhoonzero 已提交
384
        if (wt != WIRETYPE_LENGTH_DELIMITED ||
T
typhoonzero 已提交
385
            !ReadVarintSizeAsInt(&input, &num_bytes)) {
T
typhoonzero 已提交
386 387 388
          return tag;
        }

T
typhoonzero 已提交
389
        if (meta_.type() == sendrecv::NCCL_ID) {
T
typhoonzero 已提交
390
#ifdef PADDLE_WITH_CUDA
T
typhoonzero 已提交
391 392 393
          auto* var = scope_->FindVar(meta_.varname());
          if (var != nullptr) {
            ncclUniqueId* id = var->GetMutable<ncclUniqueId>();
T
typhoonzero 已提交
394
            if (!ReadRaw(&input, *dev_ctx_, platform::CPUPlace(), id->internal,
395
                         num_bytes)) {
T
typhoonzero 已提交
396 397
              return tag;
            }
T
typhoonzero 已提交
398
          }
T
typhoonzero 已提交
399
          break;
T
typhoonzero 已提交
400 401 402
#else
          PADDLE_THROW("Not compiled with CUDA!");
#endif
403 404 405 406 407 408
        }

        framework::DDim dims = GetDims(meta_.dims());
        if (meta_.type() == sendrecv::LOD_TENSOR) {
          PADDLE_ENFORCE(meta_.lod_size() >= 0,
                         "lod info should be got first!");
T
typhoonzero 已提交
409
          if (!CopyLodTensorData(&input, *dev_ctx_, dims, num_bytes)) {
410 411 412 413 414 415
            return tag;
          }
          break;
        }

        if (meta_.type() == sendrecv::SELECTED_ROWS) {
T
typhoonzero 已提交
416
          if (!CopySelectRowsTensorData(&input, *dev_ctx_, dims, num_bytes)) {
417 418 419 420 421 422 423 424 425 426 427 428 429
            return tag;
          }
          break;
        }

        return tag;
      }
      case sendrecv::VariableMessage::kRowsFieldNumber: {
        PADDLE_ENFORCE((meta_.type() == sendrecv::SELECTED_ROWS ||
                        meta_.type() == sendrecv::LOD_TENSOR) &&
                           meta_.varname() != "",
                       "meta info should be got first!");

T
typhoonzero 已提交
430
        int num_bytes = 0;
431
        if (wt != WIRETYPE_LENGTH_DELIMITED ||
T
typhoonzero 已提交
432
            !ReadVarintSizeAsInt(&input, &num_bytes)) {
433 434 435
          return tag;
        }

T
typhoonzero 已提交
436
        if (!CopySelectRowsData(&input, *dev_ctx_, num_bytes)) {
437 438 439 440
          return tag;
        }
        break;
      }
Y
Yancey1989 已提交
441 442 443 444 445 446 447 448 449 450 451 452 453 454
      case sendrecv::VariableMessage::kOutVarnameFieldNumber: {
        uint32_t length;
        if ((wt != WIRETYPE_LENGTH_DELIMITED) || !input.ReadVarint32(&length)) {
          return tag;
        }

        std::string temp;
        if (!input.ReadString(&temp, length)) {
          return tag;
        }

        meta_.set_out_varname(temp);
        break;
      }
455
      case sendrecv::VariableMessage::kProfileFieldNumber: {
X
Xin Pan 已提交
456 457
        uint64_t profiling = 0;
        if (!input.ReadVarint64(&profiling)) {
458 459 460
          return tag;
        }
        meta_.set_profile(profiling);
X
Xin Pan 已提交
461 462
        int64_t listener_id = platform::ListenerId();
        if (listener_id <= 0) {
463 464
          break;
        }
X
Xin Pan 已提交
465 466
        if (profiling == platform::kEnableProfiler &&
            !platform::IsProfileEnabled()) {
467
          platform::EnableProfiler(platform::ProfilerState::kCPU);
X
Xin Pan 已提交
468 469
        } else if (profiling == platform::kDisableProfiler &&
                   platform::IsProfileEnabled()) {
470 471 472
          // TODO(panyx0718): Should we allow to customize file dir.
          platform::DisableProfiler(
              platform::EventSortingKey::kDefault,
X
Xin Pan 已提交
473
              string::Sprintf("/tmp/profile_ps_%lld", listener_id));
474 475 476
        }
        break;
      }
477 478 479 480 481 482 483 484 485 486
      default: {
        // Unknown tag, return unknown error.
        return -1;
      }
    }
  }

  return 0;
}

487
};  // namespace distributed
488 489
};  // namespace operators
};  // namespace paddle