beam_search_op.h 2.2 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yan Chunwei 已提交
2 3 4 5 6

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

7
    http://www.apache.org/licenses/LICENSE-2.0
Y
Yan Chunwei 已提交
8 9 10 11 12 13 14 15 16

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

Y
Yi Wang 已提交
17
#include "paddle/fluid/framework/operator.h"
18
#include "paddle/fluid/operators/math/beam_search.h"
Y
Yan Chunwei 已提交
19 20 21 22

namespace paddle {
namespace operators {

K
ktlichkid 已提交
23
template <typename DeviceContext, typename T>
K
ktlichkid 已提交
24
class BeamSearchOpKernel : public framework::OpKernel<T> {
K
ktlichkid 已提交
25 26
 public:
  void Compute(const framework::ExecutionContext& context) const override {
27 28 29 30
    auto* ids = context.Input<framework::LoDTensor>("ids");
    auto* scores = context.Input<framework::LoDTensor>("scores");
    auto* pre_ids = context.Input<framework::LoDTensor>("pre_ids");
    auto* pre_scores = context.Input<framework::LoDTensor>("pre_scores");
31

32 33 34
    PADDLE_ENFORCE_NOT_NULL(scores);
    PADDLE_ENFORCE_NOT_NULL(pre_ids);
    PADDLE_ENFORCE_NOT_NULL(pre_scores);
Y
Yan Chunwei 已提交
35

K
ktlichkid 已提交
36 37 38
    size_t level = context.Attr<int>("level");
    size_t beam_size = context.Attr<int>("beam_size");
    int end_id = context.Attr<int>("end_id");
39 40
    bool is_accumulated = context.Attr<bool>("is_accumulated");

41 42
    auto selected_ids = context.Output<framework::LoDTensor>("selected_ids");
    auto selected_scores =
43
        context.Output<framework::LoDTensor>("selected_scores");
44
    auto* parent_idx = context.Output<framework::Tensor>("parent_idx");
45 46
    PADDLE_ENFORCE_NOT_NULL(selected_ids);
    PADDLE_ENFORCE_NOT_NULL(selected_scores);
47
    PADDLE_ENFORCE_NOT_NULL(parent_idx);
48 49 50

    math::BeamSearchFunctor<DeviceContext, T> alg;
    alg(context.template device_context<DeviceContext>(), pre_ids, pre_scores,
51 52
        ids, scores, selected_ids, selected_scores, parent_idx, level,
        beam_size, end_id, is_accumulated);
K
ktlichkid 已提交
53
  }
K
ktlichkid 已提交
54
};
55

Y
Yan Chunwei 已提交
56 57
}  // namespace operators
}  // namespace paddle