beam_search_op.h 8.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yan Chunwei 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

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. */

#pragma once

#ifdef PADDLE_WITH_TESTING
#include "gtest/gtest.h"
#endif

21 22
#include <string>
#include <vector>
Y
Yi Wang 已提交
23 24
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/operator.h"
Y
Yan Chunwei 已提交
25

26 27
#include <iostream>

Y
Yan Chunwei 已提交
28 29 30 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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
namespace paddle {
namespace operators {

/*
 * This is an implementation of beam search.
 *
 * To explain the details, lets take machine translation task for example, in
 * this task, one source sentence is translated to multiple target sentences,
 * during this period, one sentence will be translated to multiple translation
 * prefixes(target sentence that have not ended), in each time step a prefix
 * will have some candidates, input the candidate ids and their corresponding
 * scores (probabilities), it will sort and select the top beam_size candidates
 * for each source sentence, and store the selected candidates's score and their
 * corresponding ids to LoDTensors.
 *
 * A detailed example:
 *
 * Input
 *
 * ids:
 * LoD (should have 2 levels)
 * first level: [0, 1, 4]
 * second level: [0, 1, 2, 3, 4]
 *
 * tensor's data
 * [
 * [4, 2, 5]
 * [2, 1, 3]
 * [3, 5, 2]
 * [8, 2, 1]
 * ]
 *
 * scores:
 * LoD same as `ids`
 * tensor's data
 * [
 * [0.5, 0.3, 0.2]
 * [0.6, 0.3, 0.1]
 * [0.9, 0.5, 0.1]
 * [0.7, 0.5, 0.1]
 * ]
 *
 * the inputs means that there are 2 source sentences to translate, and the
 * first source has 1 prefix, the second source has 2 prefix.
 *
 * lets assume beam size is 2, and the beam search's output should be
 * LoD
 * first level:
 * [0, 1, 2]
 * second level:
 * [0, 2, 4]
 *
Y
Yan Chunwei 已提交
80 81 82 83 84 85 86 87 88
 * id tensor's data
 * [[
 * 4,
 * 1,
 * 3,
 * 8,
 * ]]
 *
 * score tensor's data
Y
Yan Chunwei 已提交
89 90 91 92 93 94 95 96 97 98 99 100 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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
 * [[
 * 0.5,
 * 0.3,
 * 0.9,
 * 0.7
 * ]]
 *
 * TODO all the prune operations should be in the beam search, so it is better
 * to split the beam search algorithm into a sequence of smaller operators, and
 * the prune operators can be inserted in this sequence.
 */
class BeamSearch {
 public:
  // TODO(superjom) make type customizable
  using id_t = size_t;
  using score_t = float;
  /*
   * Input the arguments that needed by this class.
   */
  BeamSearch(const framework::LoDTensor& ids,
             const framework::LoDTensor& scores, size_t level, size_t beam_size,
             int end_id)
      : beam_size_(beam_size),
        ids_(&ids),
        scores_(&scores),
        lod_level_(level),
        end_id_(end_id) {}

  /*
   * The main function of beam search.
   *
   * @selected_ids: a [None, 1]-shaped tensor with LoD.
   *   In a machine translation model, it might be the candidate term id sets,
   *   each set stored as a varience-length sequence.
   *   The format might be described with a two-level LoD
   *   - [[0 1]
   *   -  [0 1 2]]
   *   - [[]
   *   -  [0 1]]
   *   the first level of LoD tells that there are two source sentences. The
   *   second level describes the details of the candidate id set's offsets in
   * the
   *   source sentences.
   *
   *  @selected_scores: a LoD tensor with the same shape and LoD with
   * selected_ids.
   *   It stores the corresponding scores of candidate ids in selected_ids.
   *
   * Return false if all the input tensor is empty, in machine translation task
   * that means no candidates is provided, and the task will stop running.
   */
  void operator()(const framework::LoDTensor& pre_ids,
                  framework::LoDTensor* selected_ids,
                  framework::LoDTensor* selected_scores);
  /*
   * The basic items help to sort.
   */
  struct Item {
    Item() {}
    Item(size_t offset, size_t id, float score)
        : offset(offset), id(id), score(score) {}
Y
Yan Chunwei 已提交
150
    // offset in the higher lod level.
Y
Yan Chunwei 已提交
151
    size_t offset;
Y
Yan Chunwei 已提交
152 153
    // // prefix id in the lower lod level.
    // size_t prefix;
Y
Yan Chunwei 已提交
154 155 156 157 158 159
    // the candidate id
    id_t id;
    // the corresponding score
    score_t score;
  };

Q
Qiao Longfei 已提交
160
 protected:
Y
Yan Chunwei 已提交
161 162 163 164 165
  /*
   * Delete all the records that follows the end token.
   */
  int PruneEndidCandidates(const framework::LoDTensor& pre_ids,
                           std::vector<std::vector<Item>>* items);
Y
Yan Chunwei 已提交
166 167 168 169 170 171

  /*
   * Transform the items into a map whose key is offset, value is the items.
   * NOTE low performance
   */
  std::vector<std::vector<Item>> ToMap(
Q
Qiao Longfei 已提交
172
      const std::vector<std::vector<Item>>& inputs, size_t element_num);
Y
Yan Chunwei 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

  /*
   * For each source, select top beam_size records.
   */
  std::vector<std::vector<Item>> SelectTopBeamSizeItems();

  /*
   * Get the items of next source sequence, return false if no remaining items.
   */
  bool NextItemSet(std::vector<Item>* items);

 private:
  size_t beam_size_;
  const framework::LoDTensor* ids_;
  const framework::LoDTensor* scores_;
  size_t lod_level_{0};
  size_t sent_offset_{0};
  int end_id_{0};
};

Q
Qiao Longfei 已提交
193 194 195 196
std::ostream& operator<<(std::ostream& os, const BeamSearch::Item& item);

std::string ItemToString(const BeamSearch::Item& item);

K
ktlichkid 已提交
197
template <typename DeviceContext, typename T>
K
ktlichkid 已提交
198
class BeamSearchOpKernel : public framework::OpKernel<T>{
K
ktlichkid 已提交
199 200
 public:
  void Compute(const framework::ExecutionContext& context) const override {
201
    std::cout << "Compute 1\n";
K
ktlichkid 已提交
202
    auto ids_var = context.Input<framework::LoDTensor>("ids");
203
    std::cout << "Compute 2\n";
K
ktlichkid 已提交
204
    auto scores_var = context.Input<framework::LoDTensor>("scores");
205
    std::cout << "Compute 3\n";
K
ktlichkid 已提交
206
    auto pre_ids_var = context.Input<framework::LoDTensor>("pre_ids");
207
    std::cout << "Compute 4\n";
K
ktlichkid 已提交
208
    PADDLE_ENFORCE_NOT_NULL(ids_var);
209
    std::cout << "Compute 5\n";
K
ktlichkid 已提交
210
    PADDLE_ENFORCE_NOT_NULL(scores_var);
211
    std::cout << "Compute 6\n";
K
ktlichkid 已提交
212
    PADDLE_ENFORCE_NOT_NULL(pre_ids_var);
213 214 215 216
    std::cout << "Compute 7\n";
    // auto& ids = ids_var->Get<framework::LoDTensor>();
    // auto& scores = scores_var->Get<framework::LoDTensor>();
    // auto& pre_ids = pre_ids_var->Get<framework::LoDTensor>();
Y
Yan Chunwei 已提交
217

K
ktlichkid 已提交
218
    size_t level = context.Attr<int>("level");
219
    std::cout << "Compute 8\n";
K
ktlichkid 已提交
220
    size_t beam_size = context.Attr<int>("beam_size");
221
    std::cout << "Compute 9\n";
K
ktlichkid 已提交
222
    int end_id = context.Attr<int>("end_id");
223
    std::cout << "Compute 10\n";
K
ktlichkid 已提交
224
    BeamSearch alg(*ids_var, *scores_var, level, beam_size, end_id);
225 226 227 228 229 230 231
    std::cout << "Compute 11\n";
    auto selected_ids_var =
        context.Output<framework::LoDTensor>("selected_ids");
    std::cout << "Compute 12\n";
    auto selected_scores_var =
        context.Output<framework::LoDTensor>("selected_scores");
    std::cout << "Compute 13\n";
K
ktlichkid 已提交
232
    PADDLE_ENFORCE_NOT_NULL(selected_ids_var);
233
    std::cout << "Compute 14\n";
K
ktlichkid 已提交
234
    PADDLE_ENFORCE_NOT_NULL(selected_scores_var);
235 236
    std::cout << "Compute 15\n";
    // auto& selected_ids_tensor =
K
ktlichkid 已提交
237
    //    *selected_ids_var->GetMutable<framework::LoDTensor>();
238
    // auto& selected_scores_tensor =
K
ktlichkid 已提交
239 240
    //    *selected_scores_var->GetMutable<framework::LoDTensor>();
    alg(*pre_ids_var, selected_ids_var, selected_scores_var);
241
    std::cout << "Compute 16\n";
K
ktlichkid 已提交
242
  }
K
ktlichkid 已提交
243
};
Y
Yan Chunwei 已提交
244

K
ktlichkid 已提交
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
/*
  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);
  }
*/

Y
Yan Chunwei 已提交
275 276
}  // namespace operators
}  // namespace paddle