beam_search_op.cc 11.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yan Chunwei 已提交
2

L
Luo Tao 已提交
3 4 5
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
Y
Yan Chunwei 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Y
Yan Chunwei 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
Y
Yan Chunwei 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/beam_search_op.h"
Y
Yan Chunwei 已提交
16

17
#include <algorithm>
Y
Yan Chunwei 已提交
18
#include <map>
19 20
#include <string>
#include <vector>
Y
Yi Wang 已提交
21 22
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
Y
Yan Chunwei 已提交
23

24 25
#include <iostream>

Y
Yan Chunwei 已提交
26 27 28 29 30 31
namespace paddle {
namespace operators {

void BeamSearch::operator()(const framework::LoDTensor &pre_ids,
                            framework::LoDTensor *selected_ids,
                            framework::LoDTensor *selected_scores) {
Q
Qiao Longfei 已提交
32 33 34
  auto abs_lod = framework::ToAbsOffset(ids_->lod());
  auto &high_level = abs_lod[lod_level_];

Y
Yan Chunwei 已提交
35
  auto items = SelectTopBeamSizeItems();
Q
Qiao Longfei 已提交
36 37 38 39 40 41 42 43
  auto selected_items = ToMap(items, high_level.back());
  VLOG(3) << "selected_items:";
  for (size_t i = 0; i < selected_items.size(); ++i) {
    VLOG(3) << "offset:" << i;
    for (auto &item : selected_items[i]) {
      VLOG(3) << ItemToString(item);
    }
  }
Y
Yan Chunwei 已提交
44 45 46
  PruneEndidCandidates(pre_ids, &selected_items);
  // calculate the output tensor's height
  size_t num_instances = std::accumulate(
Y
Yan Chunwei 已提交
47
      std::begin(selected_items), std::end(selected_items), 0,
Y
Yan Chunwei 已提交
48 49 50 51 52 53 54 55 56
      [](size_t a, std::vector<Item> &b) { return a + b.size(); });
  // the output tensor shape should be [num_instances, 1]
  auto dims = framework::make_ddim(
      std::vector<int64_t>({static_cast<int>(num_instances), 1}));
  selected_ids->Resize(dims);
  selected_scores->Resize(dims);

  std::map<size_t /*offset*/, std::vector<Item>> hash;
  framework::LoD new_lod;
57
  auto *ids_data = selected_ids->mutable_data<int64_t>(platform::CPUPlace());
Y
Yan Chunwei 已提交
58 59 60 61 62 63 64 65
  auto *scores_data =
      selected_scores->mutable_data<float>(platform::CPUPlace());

  // fill in data
  std::vector<size_t> low_level;
  size_t low_offset = 0;
  for (auto &items : selected_items) {
    low_level.push_back(low_offset);
Y
Yan Chunwei 已提交
66 67 68 69 70 71
    sort(items.begin(), items.end(), [](const Item &a, const Item &b) {
      if (a.offset < b.offset) {
        return true;
      }
      return a.id < b.id;
    });
Y
Yan Chunwei 已提交
72 73 74 75 76 77
    for (auto &item : items) {
      ids_data[low_offset] = item.id;
      scores_data[low_offset] = item.score;
      low_offset++;
    }
  }
Y
Yan Chunwei 已提交
78 79
  low_level.push_back(low_offset);

Y
Yan Chunwei 已提交
80 81 82 83
  // fill lod
  framework::LoD lod(2);
  lod[0].assign(high_level.begin(), high_level.end());
  lod[1].assign(low_level.begin(), low_level.end());
Q
Qiao Longfei 已提交
84 85 86
  if (!framework::CheckLoD(lod)) {
    PADDLE_THROW("lod %s is not right", framework::LoDToString(lod));
  }
Y
Yan Chunwei 已提交
87 88 89 90
  selected_ids->set_lod(lod);
  selected_scores->set_lod(lod);
}

Y
Yan Chunwei 已提交
91 92
int BeamSearch::PruneEndidCandidates(const framework::LoDTensor &pre_ids,
                                     std::vector<std::vector<Item>> *items) {
93
  auto *pre_ids_data = pre_ids.data<int64_t>();
Y
Yan Chunwei 已提交
94

Y
Yan Chunwei 已提交
95
  int res = 0;
Y
Yan Chunwei 已提交
96 97 98 99
  for (size_t offset = 0; offset < items->size(); offset++) {
    auto prefix_id = pre_ids_data[offset];
    if (prefix_id == end_id_) {
      items->at(offset).clear();
Y
Yan Chunwei 已提交
100 101
    } else {
      res++;
Y
Yan Chunwei 已提交
102 103
    }
  }
Y
Yan Chunwei 已提交
104 105

  return res;
Y
Yan Chunwei 已提交
106 107 108
}

std::vector<std::vector<BeamSearch::Item>> BeamSearch::ToMap(
Q
Qiao Longfei 已提交
109
    const std::vector<std::vector<Item>> &items, size_t element_num) {
Y
Yan Chunwei 已提交
110
  std::vector<std::vector<Item>> result;
Q
Qiao Longfei 已提交
111
  result.resize(element_num);
Y
Yan Chunwei 已提交
112 113 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
  for (auto &entries : items) {
    for (const auto &item : entries) {
      result[item.offset].push_back(item);
    }
  }
  return result;
}

std::vector<std::vector<BeamSearch::Item>>
BeamSearch::SelectTopBeamSizeItems() {
  std::vector<std::vector<Item>> result;
  std::vector<Item> items;
  // for each source sentence, select the top beam_size items across all
  // candidate sets.
  while (NextItemSet(&items)) {
    std::nth_element(std::begin(items), std::begin(items) + beam_size_,
                     std::end(items), [](const Item &a, const Item &b) {
                       // TODO(superjom) make score's comparation customizable.
                       // partial sort in descending order
                       return a.score > b.score;
                     });
    // prune the top beam_size items.
    if (items.size() > beam_size_) {
      items.resize(beam_size_);
    }
    result.emplace_back(items);
  }
Q
Qiao Longfei 已提交
139 140 141 142 143 144 145 146
  VLOG(3) << "SelectTopBeamSizeItems result size " << result.size();
  for (auto &items : result) {
    VLOG(3) << "item set:";
    for (auto &item : items) {
      VLOG(3) << ItemToString(item);
    }
  }

Y
Yan Chunwei 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160
  return result;
}

// the candidates of a source
bool BeamSearch::NextItemSet(std::vector<BeamSearch::Item> *items) {
  if (sent_offset_ >= ids_->NumElements(lod_level_)) {
    return false;
  }
  // find the current candidates
  auto ids = *ids_;
  auto scores = *scores_;

  auto abs_lod = framework::ToAbsOffset(ids.lod());

161
  auto *ids_data = ids.data<int64_t>();
Y
Yan Chunwei 已提交
162 163 164 165 166 167 168 169 170 171 172
  auto *scores_data = scores.data<float>();

  size_t instance_dim = 1;
  for (int i = 1; i < ids.dims().size(); i++) {
    instance_dim *= ids.dims()[i];
  }

  items->clear();
  items->reserve(framework::product(ids.dims()));
  for (size_t offset = abs_lod[lod_level_][sent_offset_];
       offset < abs_lod[lod_level_][sent_offset_ + 1]; offset++) {
173
    for (size_t d = 0; d < instance_dim; d++) {
Y
Yan Chunwei 已提交
174 175 176 177 178 179 180 181 182 183
      const size_t dim_offset = offset * instance_dim + d;
      items->emplace_back(offset, ids_data[dim_offset],
                          scores_data[dim_offset]);
    }
  }

  sent_offset_++;
  return true;
}

Q
Qiao Longfei 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
std::ostream &operator<<(std::ostream &os, const BeamSearch::Item &item) {
  os << "{";
  os << "offset: " << item.offset << ", ";
  os << "id: " << item.id << ", ";
  os << "score: " << item.score << "";
  os << "}";

  return os;
}

std::string ItemToString(const BeamSearch::Item &item) {
  std::ostringstream stream;
  stream << item;
  return stream.str();
}

K
ktlichkid 已提交
200
class BeamSearchOpMaker
Y
Yan Chunwei 已提交
201 202
    : public framework::OpProtoAndCheckerMaker {
 public:
K
ktlichkid 已提交
203
  BeamSearchOpMaker(OpProto *proto, OpAttrChecker *op_checker)
Y
Yan Chunwei 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
      : OpProtoAndCheckerMaker(proto, op_checker) {
    // inputs and outputs stored in proto
    AddInput("pre_ids", "ids in previous step");
    AddInput("ids", "a LoDTensor of shape of [None,k]");
    AddInput("scores",
             "a LoDTensor that has the same shape and LoD with `ids`");
    AddOutput("selected_ids",
              "a LoDTensor that stores the IDs selected by beam search");
    AddOutput(
        "selected_scores",
        "a LoDTensor that has the same shape and LoD with `selected_ids`");

    // Attributes stored in AttributeMap
    AddAttr<int>("level", "the level of LoDTensor");
    AddAttr<int>("beam_size", "beam size for beam search");
    AddAttr<int>("end_id",
                 "the token id which indicates the end of a sequence");

    AddComment(
        "This is a beam search operator that help to generate sequences.");
  }
};

K
ktlichkid 已提交
227
class BeamSearchOp : public framework::OperatorWithKernel {
K
ktlichkid 已提交
228
 /*
K
ktlichkid 已提交
229 230 231 232 233
 public:
  BeamSearchOp(const std::string& type,
               const framework::VariableNameMap& inputs,
               const framework::VariableNameMap& outputs,
               const framework::AttributeMap& attrs)
K
ktlichkid 已提交
234
      : OperatorWithKernel(type, inputs, outputs, attrs) {}
K
ktlichkid 已提交
235 236

  BeamSearchOp(const BeamSearchOp& o)
K
ktlichkid 已提交
237
      : framework::OperatorWithKernel(
K
ktlichkid 已提交
238 239 240
            static_cast<const framework::OperatorBase&>(o)) {
    PADDLE_THROW("Not Implemented");
  }
K
ktlichkid 已提交
241 242 243
 */
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
K
ktlichkid 已提交
244

K
ktlichkid 已提交
245
 protected:
K
ktlichkid 已提交
246
  void InferShape(framework::InferShapeContext* ctx) const override {
K
ktlichkid 已提交
247 248
    for (const std::string &arg :
         std::vector<std::string>({"pre_ids", "ids", "scores"})) {
K
ktlichkid 已提交
249
      PADDLE_ENFORCE(ctx->HasInput(arg),
K
ktlichkid 已提交
250 251 252 253
                     "BeamSearch need input argument '%s'", arg);
    }
    for (const std::string &arg :
         std::vector<std::string>({"selected_ids", "selected_scores"})) {
K
ktlichkid 已提交
254
      PADDLE_ENFORCE(ctx->HasOutput(arg),
K
ktlichkid 已提交
255 256
                     "BeamSearch need output argument '%s'", arg);
    }
257 258 259 260 261 262 263 264 265 266 267
    std::cout << "Done Infer Shape\n";
  }

  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
    std::cout << "Get Expected type 1\n";
    framework::OpKernelType kt = OperatorWithKernel::GetExpectedKernelType(ctx);
    std::cout << "Get Expected type 2\n";
    kt.place_ = ctx.Input<framework::LoDTensor>("pre_ids")->place();
    std::cout << "Get Expected type 3\n";
    return kt;
K
ktlichkid 已提交
268
  }
K
ktlichkid 已提交
269
/*
K
ktlichkid 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
 private:
  void RunImpl(const framework::Scope& scope,
               const platform::Place& dev_place) const override {
    auto ids_var = scope.FindVar(Input("ids"));
    auto scores_var = scope.FindVar(Input("scores"));
    auto pre_ids_var = scope.FindVar(Input("pre_ids"));
    PADDLE_ENFORCE_NOT_NULL(ids_var);
    PADDLE_ENFORCE_NOT_NULL(scores_var);
    PADDLE_ENFORCE_NOT_NULL(pre_ids_var);

    auto& ids = ids_var->Get<framework::LoDTensor>();
    auto& scores = scores_var->Get<framework::LoDTensor>();
    auto& pre_ids = pre_ids_var->Get<framework::LoDTensor>();
    size_t level = Attr<int>("level");
    size_t beam_size = Attr<int>("beam_size");
    int end_id = Attr<int>("end_id");
    BeamSearch alg(ids, scores, level, beam_size, end_id);

    auto selected_ids_var = scope.FindVar(Output("selected_ids"));
    auto selected_scores_var = scope.FindVar(Output("selected_scores"));
    PADDLE_ENFORCE_NOT_NULL(selected_ids_var);
    PADDLE_ENFORCE_NOT_NULL(selected_scores_var);
    auto& selected_ids_tensor =
        *selected_ids_var->GetMutable<framework::LoDTensor>();
    auto& selected_scores_tensor =
        *selected_scores_var->GetMutable<framework::LoDTensor>();
    alg(pre_ids, &selected_ids_tensor, &selected_scores_tensor);
  }
K
ktlichkid 已提交
298
*/
K
ktlichkid 已提交
299 300 301 302
};


/*
Q
Qiao Longfei 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
class BeamSearchInferShape : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *context) const override {
    for (const std::string &arg :
         std::vector<std::string>({"pre_ids", "ids", "scores"})) {
      PADDLE_ENFORCE(context->HasInput(arg),
                     "BeamSearch need input argument '%s'", arg);
    }
    for (const std::string &arg :
         std::vector<std::string>({"selected_ids", "selected_scores"})) {
      PADDLE_ENFORCE(context->HasOutput(arg),
                     "BeamSearch need output argument '%s'", arg);
    }
  }
};

class BeamSearchInferVarType : public framework::VarTypeInference {
 public:
  void operator()(const framework::OpDesc &op_desc,
                  framework::BlockDesc *block) const override {
    for (auto &o : op_desc.Output("selected_ids")) {
324
      block->Var(o)->SetType(framework::proto::VarType::LOD_TENSOR);
Q
Qiao Longfei 已提交
325 326
    }
    for (auto &o : op_desc.Output("selected_scores")) {
327
      block->Var(o)->SetType(framework::proto::VarType::LOD_TENSOR);
Q
Qiao Longfei 已提交
328 329 330
    }
  }
};
K
ktlichkid 已提交
331
*/
Y
Yan Chunwei 已提交
332 333
}  // namespace operators
}  // namespace paddle
K
ktlichkid 已提交
334
/*
Q
Qiao Longfei 已提交
335 336 337 338 339
REGISTER_OPERATOR(beam_search, paddle::operators::BeamSearchOp,
                  paddle::operators::BeamSearchProtoAndCheckerMaker,
                  paddle::operators::BeamSearchInferShape,
                  paddle::operators::BeamSearchInferVarType,
                  paddle::framework::EmptyGradOpMaker);
K
ktlichkid 已提交
340 341 342 343 344 345 346 347
*/
namespace ops = paddle::operators;
REGISTER_OP_WITHOUT_GRADIENT(beam_search, ops::BeamSearchOp,
                             ops::BeamSearchOpMaker);
REGISTER_OP_CPU_KERNEL(
    beam_search,
    ops::BeamSearchOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::BeamSearchOpKernel<paddle::platform::CPUDeviceContext, double>);