beam_search_op.cc 11.4 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

15
#include <algorithm>
Y
Yan Chunwei 已提交
16
#include <map>
17 18
#include <string>
#include <vector>
19

Y
Yi Wang 已提交
20 21
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
22
#include "paddle/fluid/operators/beam_search_op.h"
Y
Yan Chunwei 已提交
23 24 25 26 27

namespace paddle {
namespace operators {

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

34
  auto items = SelectTopBeamSizeItems(pre_ids, pre_scores);
Q
Qiao Longfei 已提交
35
  auto selected_items = ToMap(items, high_level.back());
M
minqiyang 已提交
36
  VLOG(3) << "selected_items:";
Q
Qiao Longfei 已提交
37
  for (size_t i = 0; i < selected_items.size(); ++i) {
M
minqiyang 已提交
38
    VLOG(3) << "offset:" << i;
Q
Qiao Longfei 已提交
39
    for (auto &item : selected_items[i]) {
M
minqiyang 已提交
40
      VLOG(3) << ItemToString(item);
Q
Qiao Longfei 已提交
41 42
    }
  }
43 44

  PruneEndBeams(pre_ids, &selected_items);
Y
Yan Chunwei 已提交
45 46
  // 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 66 67 68 69 70 71
  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);
    for (auto &item : items) {
      ids_data[low_offset] = item.id;
      scores_data[low_offset] = item.score;
      low_offset++;
    }
  }
Y
Yan Chunwei 已提交
72 73
  low_level.push_back(low_offset);

Y
Yan Chunwei 已提交
74 75 76 77
  // 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 已提交
78 79 80
  if (!framework::CheckLoD(lod)) {
    PADDLE_THROW("lod %s is not right", framework::LoDToString(lod));
  }
Y
Yan Chunwei 已提交
81 82 83 84
  selected_ids->set_lod(lod);
  selected_scores->set_lod(lod);
}

85 86 87 88 89
void BeamSearch::PruneEndBeams(const framework::LoDTensor &pre_ids,
                               std::vector<std::vector<Item>> *items) {
  auto *pre_ids_data = pre_ids.data<int64_t>();
  auto abs_lod = framework::ToAbsOffset(ids_->lod());
  auto &high_level = abs_lod[lod_level_];
90
  for (size_t src_idx = 0; src_idx < high_level.size() - 1; ++src_idx) {
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    size_t src_prefix_start = high_level[src_idx];
    size_t src_prefix_end = high_level[src_idx + 1];
    bool finish_flag = true;
    for (size_t offset = src_prefix_start; offset < src_prefix_end; offset++) {
      for (auto &item : items->at(offset)) {
        if (item.id != static_cast<size_t>(end_id_) ||
            pre_ids_data[offset] != end_id_) {
          finish_flag = false;
          break;
        }
      }
      if (!finish_flag) break;
    }
    if (finish_flag) {  // all branchs of the beam (source sentence) end and
                        // prune this beam
      for (size_t offset = src_prefix_start; offset < src_prefix_end; offset++)
        items->at(offset).clear();
    }
  }
}

Y
Yan Chunwei 已提交
112
std::vector<std::vector<BeamSearch::Item>> BeamSearch::ToMap(
Q
Qiao Longfei 已提交
113
    const std::vector<std::vector<Item>> &items, size_t element_num) {
Y
Yan Chunwei 已提交
114
  std::vector<std::vector<Item>> result;
Q
Qiao Longfei 已提交
115
  result.resize(element_num);
Y
Yan Chunwei 已提交
116 117 118 119 120 121 122 123
  for (auto &entries : items) {
    for (const auto &item : entries) {
      result[item.offset].push_back(item);
    }
  }
  return result;
}

124 125 126
std::vector<std::vector<BeamSearch::Item>> BeamSearch::SelectTopBeamSizeItems(
    const framework::LoDTensor &pre_ids,
    const framework::LoDTensor &pre_scores) {
Y
Yan Chunwei 已提交
127 128 129 130
  std::vector<std::vector<Item>> result;
  std::vector<Item> items;
  // for each source sentence, select the top beam_size items across all
  // candidate sets.
131
  while (NextItemSet(pre_ids, pre_scores, &items)) {
132 133 134
    std::nth_element(
        std::begin(items), std::begin(items) + beam_size_, std::end(items),
        [](const Item &a, const Item &b) { return a.score > b.score; });
Y
Yan Chunwei 已提交
135 136 137 138 139 140
    // prune the top beam_size items.
    if (items.size() > beam_size_) {
      items.resize(beam_size_);
    }
    result.emplace_back(items);
  }
M
minqiyang 已提交
141
  VLOG(3) << "SelectTopBeamSizeItems result size " << result.size();
Q
Qiao Longfei 已提交
142
  for (auto &items : result) {
M
minqiyang 已提交
143
    VLOG(3) << "item set:";
Q
Qiao Longfei 已提交
144
    for (auto &item : items) {
M
minqiyang 已提交
145
      VLOG(3) << ItemToString(item);
Q
Qiao Longfei 已提交
146 147 148
    }
  }

Y
Yan Chunwei 已提交
149 150 151 152
  return result;
}

// the candidates of a source
153 154 155
bool BeamSearch::NextItemSet(const framework::LoDTensor &pre_ids,
                             const framework::LoDTensor &pre_scores,
                             std::vector<BeamSearch::Item> *items) {
Y
Yan Chunwei 已提交
156 157 158 159 160 161 162 163 164
  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());

165
  auto *ids_data = ids.data<int64_t>();
Y
Yan Chunwei 已提交
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];
  }

173 174
  auto *pre_ids_data = pre_ids.data<int64_t>();
  auto *pre_scores_data = pre_scores.data<float>();
Y
Yan Chunwei 已提交
175 176 177 178
  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++) {
179 180 181 182
    auto pre_id = pre_ids_data[offset];
    auto pre_score = pre_scores_data[offset];
    if (pre_id == end_id_) {
      // Allocate all probability mass to eos_id for finished branchs and the
183
      // other candidate ids can be ignored.
184 185 186 187 188 189 190
      items->emplace_back(offset, end_id_, pre_score);
    } else {
      for (size_t d = 0; d < instance_dim; d++) {
        const size_t dim_offset = offset * instance_dim + d;
        items->emplace_back(offset, ids_data[dim_offset],
                            scores_data[dim_offset]);
      }
Y
Yan Chunwei 已提交
191 192 193 194 195 196 197
    }
  }

  sent_offset_++;
  return true;
}

Q
Qiao Longfei 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
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 已提交
214
class BeamSearchOpMaker : public framework::OpProtoAndCheckerMaker {
Y
Yan Chunwei 已提交
215
 public:
Y
Yu Yang 已提交
216
  void Make() override {
Y
Yan Chunwei 已提交
217
    // inputs and outputs stored in proto
218 219 220 221 222 223 224 225 226 227 228 229
    AddInput("pre_ids",
             "(LoDTensor) The LoDTensor containing the selected ids at the "
             "previous step. It should be a tensor with shape (batch_size, 1) "
             "and lod `[[0, 1, ... , batch_size], [0, 1, ..., batch_size]]` at "
             "thefirst step.");
    AddInput("pre_scores",
             "(LoDTensor) The LoDTensor containing the accumulated "
             "scores corresponding to the selected ids at the previous step.");
    AddInput("ids",
             "(LoDTensor) The LoDTensor containing the candidates ids. Its "
             "shape should be (batch_size * beam_size, K), where K supposed to "
             "be beam_size.");
Y
Yan Chunwei 已提交
230
    AddInput("scores",
231 232 233
             "(LoDTensor) The LodTensor containing the accumulated scores "
             "corresponding to Input(ids) and its shape is the same as the "
             "shape of Input(ids).");
Y
Yan Chunwei 已提交
234
    AddOutput("selected_ids",
235 236 237 238
              "A LodTensor that stores the IDs selected by beam search.");
    AddOutput("selected_scores",
              "A LoDTensor containing the accumulated scores corresponding to "
              "Output(selected_ids).");
Y
Yan Chunwei 已提交
239 240 241 242 243 244 245

    // 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");

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    AddComment(R"DOC(
This operator does the search in beams for one time step. 
Specifically, it selects the top-K candidate word ids of current step from
Input(ids) according to their Input(scores) for all source sentences,
where K is Attr(beam_size) and Input(ids), Input(scores) are predicted results
from the computation cell. Additionally, Input(pre_ids) and Input(pre_scores)
are the output of beam_search at previous step, they are needed for special use
to handle ended candidate translations. The paths linking prefixes and selected
candidates are organized and reserved in lod.

Note that the Input(scores) passed in should be accumulated scores, and
length penalty should be done with extra operators before calculating the
accumulated scores if needed, also suggest finding top-K before it and
using the top-K candidates following.
)DOC");
Y
Yan Chunwei 已提交
261 262 263
  }
};

K
ktlichkid 已提交
264
class BeamSearchOp : public framework::OperatorWithKernel {
K
ktlichkid 已提交
265 266
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;
K
ktlichkid 已提交
267

K
ktlichkid 已提交
268
 protected:
K
ktlichkid 已提交
269
  void InferShape(framework::InferShapeContext *ctx) const override {
K
ktlichkid 已提交
270 271
    for (const std::string &arg :
         std::vector<std::string>({"pre_ids", "ids", "scores"})) {
K
ktlichkid 已提交
272 273
      PADDLE_ENFORCE(ctx->HasInput(arg), "BeamSearch need input argument '%s'",
                     arg);
K
ktlichkid 已提交
274 275 276
    }
    for (const std::string &arg :
         std::vector<std::string>({"selected_ids", "selected_scores"})) {
K
ktlichkid 已提交
277
      PADDLE_ENFORCE(ctx->HasOutput(arg),
K
ktlichkid 已提交
278 279
                     "BeamSearch need output argument '%s'", arg);
    }
280 281 282 283
  }

  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
284
    framework::OpKernelType kt = framework::OpKernelType(
M
minqiyang 已提交
285
        ctx.Input<framework::LoDTensor>("pre_ids")->type(),
K
ktlichkid 已提交
286
        platform::CPUPlace());
287
    return kt;
K
ktlichkid 已提交
288 289 290
  }
};

Q
Qiao Longfei 已提交
291 292 293 294 295
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")) {
296 297
      auto &selected_ids = block->FindRecursiveOrCreateVar(o);
      selected_ids.SetType(framework::proto::VarType::LOD_TENSOR);
Q
Qiao Longfei 已提交
298 299
    }
    for (auto &o : op_desc.Output("selected_scores")) {
300 301
      auto &selected_scores = block->FindRecursiveOrCreateVar(o);
      selected_scores.SetType(framework::proto::VarType::LOD_TENSOR);
Q
Qiao Longfei 已提交
302 303 304
    }
  }
};
K
ktlichkid 已提交
305

Y
Yan Chunwei 已提交
306 307
}  // namespace operators
}  // namespace paddle
K
ktlichkid 已提交
308

K
ktlichkid 已提交
309
namespace ops = paddle::operators;
K
ktlichkid 已提交
310 311 312

REGISTER_OPERATOR(beam_search, ops::BeamSearchOp, ops::BeamSearchOpMaker,
                  ops::BeamSearchInferVarType);
K
ktlichkid 已提交
313 314 315
REGISTER_OP_CPU_KERNEL(
    beam_search,
    ops::BeamSearchOpKernel<paddle::platform::CPUDeviceContext, float>,
K
ktlichkid 已提交
316 317 318
    ops::BeamSearchOpKernel<paddle::platform::CPUDeviceContext, double>,
    ops::BeamSearchOpKernel<paddle::platform::CPUDeviceContext, int>,
    ops::BeamSearchOpKernel<paddle::platform::CPUDeviceContext, int64_t>);