concurrency_test.cc 10.2 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 <thread>  // NOLINT
16 17 18 19 20 21 22 23 24 25 26 27 28

#include "gtest/gtest.h"
#include "paddle/fluid/framework/block_desc.h"
#include "paddle/fluid/framework/channel.h"
#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/framework/op_registry.h"

USE_NO_KERNEL_OP(go);
USE_NO_KERNEL_OP(channel_close);
USE_NO_KERNEL_OP(channel_create);
USE_NO_KERNEL_OP(channel_recv);
USE_NO_KERNEL_OP(channel_send);
USE_NO_KERNEL_OP(elementwise_add);
T
Thuan Nguyen 已提交
29 30 31 32 33 34
USE_NO_KERNEL_OP(select);
USE_NO_KERNEL_OP(conditional_block);
USE_NO_KERNEL_OP(equal);
USE_NO_KERNEL_OP(assign);
USE_NO_KERNEL_OP(while);
USE_NO_KERNEL_OP(print);
35 36 37 38 39 40 41 42

namespace f = paddle::framework;
namespace p = paddle::platform;

namespace paddle {
namespace framework {

template <typename T>
43 44
LoDTensor *CreateVariable(Scope *scope, const p::CPUPlace &place,
                          std::string name, T value) {
T
Thuan Nguyen 已提交
45
  // Create LoDTensor<int> of dim [1]
46
  auto var = scope->Var(name);
47
  auto tensor = var->GetMutable<LoDTensor>();
T
Thuan Nguyen 已提交
48
  tensor->Resize({1});
49 50
  T *expect = tensor->mutable_data<T>(place);
  expect[0] = value;
T
Thuan Nguyen 已提交
51
  return tensor;
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
}

void AddOp(const std::string &type, const VariableNameMap &inputs,
           const VariableNameMap &outputs, AttributeMap attrs,
           BlockDesc *block) {
  // insert op
  auto op = block->AppendOp();
  op->SetType(type);
  for (auto &kv : inputs) {
    op->SetInput(kv.first, kv.second);
  }
  for (auto &kv : outputs) {
    op->SetOutput(kv.first, kv.second);
  }
  op->SetAttrMap(attrs);
}

T
Thuan Nguyen 已提交
69 70 71 72 73 74 75 76 77 78 79
void AddCase(ProgramDesc *program, Scope *scope, p::CPUPlace *place,
             BlockDesc *casesBlock, int caseId, int caseType,
             std::string caseChannel, std::string caseVarName,
             std::function<void(BlockDesc *, Scope *)> func) {
  std::string caseCondName = std::string("caseCond") + std::to_string(caseId);
  std::string caseCondXVarName =
      std::string("caseCondX") + std::to_string(caseId);

  BlockDesc *caseBlock = program->AppendBlock(*casesBlock);
  func(caseBlock, scope);

80 81 82
  CreateVariable(scope, *place, caseCondName, false);
  CreateVariable(scope, *place, caseCondXVarName, caseId);
  CreateVariable(scope, *place, caseVarName, caseId);
T
Thuan Nguyen 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

  scope->Var("step_scope");

  AddOp("equal", {{"X", {caseCondXVarName}}, {"Y", {"caseToExecute"}}},
        {{"Out", {caseCondName}}}, {}, casesBlock);

  AddOp("conditional_block", {{"X", {caseCondName}}, {"Params", {}}},
        {{"Out", {}}, {"Scope", {"step_scope"}}},
        {{"sub_block", caseBlock}, {"is_scalar_condition", true}}, casesBlock);
}

void AddFibonacciSelect(Scope *scope, p::CPUPlace *place, ProgramDesc *program,
                        BlockDesc *parentBlock, std::string dataChanName,
                        std::string quitChanName) {
  BlockDesc *whileBlock = program->AppendBlock(*parentBlock);

99 100 101
  CreateVariable(scope, *place, "whileExitCond", true);
  CreateVariable(scope, *place, "caseToExecute", -1);
  CreateVariable(scope, *place, "case1var", 0);
T
Thuan Nguyen 已提交
102

103
  CreateVariable(scope, *place, "xtemp", 0);
T
Thuan Nguyen 已提交
104 105 106 107 108

  // TODO(thuan): Need to create fibXToSend, since channel send moves the actual
  // data,
  // which causes the data to be no longer accessible to do the fib calculation
  // TODO(abhinav): Change channel send to do a copy instead of a move!
109
  CreateVariable(scope, *place, "fibXToSend", 0);
T
Thuan Nguyen 已提交
110

111 112 113
  CreateVariable(scope, *place, "fibX", 0);
  CreateVariable(scope, *place, "fibY", 1);
  CreateVariable(scope, *place, "quitVar", 0);
T
Thuan Nguyen 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

  BlockDesc *casesBlock = program->AppendBlock(*whileBlock);
  std::function<void(BlockDesc * caseBlock)> f = [](BlockDesc *caseBlock) {};

  // TODO(thuan): Remove this once we change channel send to do a copy instead
  // of move
  AddOp("assign", {{"X", {"fibX"}}}, {{"Out", {"fibXToSend"}}}, {}, whileBlock);

  // Case 0: Send to dataChanName
  std::function<void(BlockDesc * caseBlock, Scope * scope)> case0Func = [&](
      BlockDesc *caseBlock, Scope *scope) {
    AddOp("assign", {{"X", {"fibX"}}}, {{"Out", {"xtemp"}}}, {}, caseBlock);
    AddOp("assign", {{"X", {"fibY"}}}, {{"Out", {"fibX"}}}, {}, caseBlock);
    AddOp("elementwise_add", {{"X", {"xtemp"}}, {"Y", {"fibY"}}},
          {{"Out", {"fibY"}}}, {}, caseBlock);
  };
  AddCase(program, scope, place, casesBlock, 0, 1, dataChanName, "fibXToSend",
          case0Func);
  std::string case0Config =
      std::string("0,1,") + dataChanName + std::string(",fibXToSend");

  // Case 1: Receive from quitChanName
  std::function<void(BlockDesc * caseBlock, Scope * scope)> case2Func = [&](
      BlockDesc *caseBlock, Scope *scope) {
    // Exit the while loop after we receive from quit channel.
    // We assign a false to "whileExitCond" variable, which will
    // break out of while_op loop
141
    CreateVariable(scope, *place, "whileFalse", false);
T
Thuan Nguyen 已提交
142 143 144 145 146 147 148 149 150 151 152
    AddOp("assign", {{"X", {"whileFalse"}}}, {{"Out", {"whileExitCond"}}}, {},
          caseBlock);
  };
  AddCase(program, scope, place, casesBlock, 1, 2, quitChanName, "quitVar",
          case2Func);
  std::string case1Config =
      std::string("1,2,") + quitChanName + std::string(",quitVar");

  // Select block
  AddOp("select", {{"X", {dataChanName, quitChanName}},
                   {"case_to_execute", {"caseToExecute"}}},
153 154 155
        {{"Out", {}}},
        {{"sub_block", casesBlock},
         {"cases", std::vector<std::string>{case0Config, case1Config}}},
T
Thuan Nguyen 已提交
156 157 158 159 160 161 162 163 164
        whileBlock);

  scope->Var("stepScopes");
  AddOp("while",
        {{"X", {dataChanName, quitChanName}}, {"Condition", {"whileExitCond"}}},
        {{"Out", {}}, {"StepScopes", {"stepScopes"}}},
        {{"sub_block", whileBlock}}, parentBlock);
}

165 166 167 168 169
TEST(Concurrency, Go_Op) {
  Scope scope;
  p::CPUPlace place;

  // Initialize scope variables
T
Thuan Nguyen 已提交
170 171 172 173 174 175 176
  p::CPUDeviceContext ctx(place);

  // Create channel variable
  scope.Var("Channel");

  // Create Variables, x0 will be put into channel,
  // result will be pulled from channel
177 178 179
  CreateVariable(&scope, place, "Status", false);
  CreateVariable(&scope, place, "x0", 99);
  CreateVariable(&scope, place, "result", 0);
180 181 182 183 184 185 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

  framework::Executor executor(place);
  ProgramDesc program;
  BlockDesc *block = program.MutableBlock(0);

  // Create channel OP
  AddOp("channel_create", {}, {{"Out", {"Channel"}}},
        {{"capacity", 10}, {"data_type", f::proto::VarType::LOD_TENSOR}},
        block);

  // Create Go Op routine
  BlockDesc *goOpBlock = program.AppendBlock(program.Block(0));
  AddOp("channel_send", {{"Channel", {"Channel"}}, {"X", {"x0"}}},
        {{"Status", {"Status"}}}, {}, goOpBlock);

  // Create Go Op
  AddOp("go", {{"X", {"Channel", "x0"}}}, {}, {{"sub_block", goOpBlock}},
        block);

  // Create Channel Receive Op
  AddOp("channel_recv", {{"Channel", {"Channel"}}},
        {{"Status", {"Status"}}, {"Out", {"result"}}}, {}, block);

  // Create Channel Close Op
  AddOp("channel_close", {{"Channel", {"Channel"}}}, {}, {}, block);

  // Check the result tensor to make sure it is set to 0
  const LoDTensor &tensor = (scope.FindVar("result"))->Get<LoDTensor>();
  auto *initialData = tensor.data<int>();
  EXPECT_EQ(initialData[0], 0);

  executor.Run(program, &scope, 0, true, true);

213 214
  // After we call executor.run, the Go operator should do a channel_send to
  // set the "result" variable to 99.
215 216 217
  auto *finalData = tensor.data<int>();
  EXPECT_EQ(finalData[0], 99);
}
T
Thuan Nguyen 已提交
218 219 220 221 222 223 224 225 226 227 228

/**
 * This test implements the fibonacci function using go_op and select_op
 */
TEST(Concurrency, Select) {
  Scope scope;
  p::CPUPlace place;

  // Initialize scope variables
  p::CPUDeviceContext ctx(place);

229 230 231
  CreateVariable(&scope, place, "Status", false);
  CreateVariable(&scope, place, "result", 0);
  CreateVariable(&scope, place, "currentXFib", 0);
T
Thuan Nguyen 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248

  framework::Executor executor(place);
  ProgramDesc program;
  BlockDesc *block = program.MutableBlock(0);

  // Create channel OP
  std::string dataChanName = "Channel";
  scope.Var(dataChanName);
  AddOp("channel_create", {}, {{"Out", {dataChanName}}},
        {{"capacity", 0}, {"data_type", f::proto::VarType::LOD_TENSOR}}, block);

  std::string quitChanName = "Quit";
  scope.Var(quitChanName);
  AddOp("channel_create", {}, {{"Out", {quitChanName}}},
        {{"capacity", 0}, {"data_type", f::proto::VarType::LOD_TENSOR}}, block);

  // Create Go Op routine, which loops 10 times over fibonacci sequence
249
  CreateVariable(&scope, place, "xReceiveVar", 0);
T
Thuan Nguyen 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

  BlockDesc *goOpBlock = program.AppendBlock(program.Block(0));
  for (int i = 0; i < 10; ++i) {
    AddOp("channel_recv", {{"Channel", {dataChanName}}},
          {{"Status", {"Status"}}, {"Out", {"currentXFib"}}}, {}, goOpBlock);
    AddOp("print", {{"In", {"currentXFib"}}}, {{"Out", {"currentXFib"}}},
          {{"first_n", 100},
           {"summarize", -1},
           {"print_tensor_name", false},
           {"print_tensor_type", true},
           {"print_tensor_shape", false},
           {"print_tensor_lod", false},
           {"print_phase", std::string("FORWARD")},
           {"message", std::string("X: ")}},
          goOpBlock);
  }

267
  CreateVariable(&scope, place, "quitSignal", 0);
T
Thuan Nguyen 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
  AddOp("channel_send", {{"Channel", {quitChanName}}, {"X", {"quitSignal"}}},
        {{"Status", {"Status"}}}, {}, goOpBlock);

  // Create Go Op
  AddOp("go", {{"X", {dataChanName, quitChanName}}}, {},
        {{"sub_block", goOpBlock}}, block);

  AddFibonacciSelect(&scope, &place, &program, block, dataChanName,
                     quitChanName);

  // Create Channel Close Op
  AddOp("channel_close", {{"Channel", {dataChanName}}}, {}, {}, block);
  AddOp("channel_close", {{"Channel", {quitChanName}}}, {}, {}, block);

  executor.Run(program, &scope, 0, true, true);

  // After we call executor.run, "result" variable should be equal to 34
  // (which is 10 loops through fibonacci sequence)
  const LoDTensor &tensor = (scope.FindVar("currentXFib"))->Get<LoDTensor>();
  auto *finalData = tensor.data<int>();
  EXPECT_EQ(finalData[0], 34);
}

291 292
}  // namespace framework
}  // namespace paddle