positive_negative_pair_op.h 4.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 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. */

#pragma once
#include <unordered_map>
#include <vector>
Y
Yi Wang 已提交
15 16
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
X
Xin Pan 已提交
17
#include "paddle/legacy/utils/Logging.h"
18 19 20 21 22 23 24

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;

Q
QI JUN 已提交
25
template <typename DeviceContext, typename T>
26 27
class PositiveNegativePairKernel : public framework::OpKernel<T> {
 public:
28 29 30 31 32 33 34 35
  struct PredictionResult {
    PredictionResult(T score, T label, T weight)
        : score(score), label(label), weight(weight) {}
    T score;
    T label;
    T weight;
  };

36 37 38
  void Compute(const framework::ExecutionContext& context) const override {
    auto score_t = context.Input<Tensor>("Score");
    auto label_t = context.Input<Tensor>("Label");
39 40 41 42
    auto query_t = context.Input<Tensor>("QueryID");
    auto acc_positive_t = context.Input<Tensor>("AccumulatePositivePair");
    auto acc_negative_t = context.Input<Tensor>("AccumulateNegativePair");
    auto acc_neutral_t = context.Input<Tensor>("AccumulateNeutralPair");
43 44 45
    auto positive_t = context.Output<Tensor>("PositivePair");
    auto negative_t = context.Output<Tensor>("NegativePair");
    auto neutral_t = context.Output<Tensor>("NeutralPair");
46
    auto weight_t = context.Input<Tensor>("Weight");
47

48 49
    auto score = score_t->data<T>();
    auto label = label_t->data<T>();
Z
zhouxiao-coder 已提交
50
    auto query = query_t->data<int64_t>();
51
    const T* weight = nullptr;
Z
zhouxiao-coder 已提交
52
    if (weight_t != nullptr) {
53 54
      weight = weight_t->data<T>();
    }
55 56 57 58 59 60
    T* positive = positive_t->mutable_data<T>(context.GetPlace());
    T* negative = negative_t->mutable_data<T>(context.GetPlace());
    T* neutral = neutral_t->mutable_data<T>(context.GetPlace());

    auto score_dim = score_t->dims();
    auto batch_size = score_dim[0];
61 62 63 64 65
    auto width = score_dim[1];
    auto column = context.Attr<int32_t>("column");
    if (column < 0) {
      column += width;
    }
66 67

    // construct document instances for each query: Query => List[<score#0,
Z
zhouxiao-coder 已提交
68 69
    // label#0, weight#0>, ...]
    std::unordered_map<int64_t, std::vector<PredictionResult>> predictions;
70 71 72
    for (auto i = 0; i < batch_size; ++i) {
      if (predictions.find(query[i]) == predictions.end()) {
        predictions.emplace(
73
            std::make_pair(query[i], std::vector<PredictionResult>()));
74
      }
Z
zhouxiao-coder 已提交
75 76
      predictions[query[i]].emplace_back(score[i * width + column], label[i],
                                         weight_t != nullptr ? weight[i] : 1.0);
77 78 79 80
    }

    // for each query, accumulate pair counts
    T pos = 0, neg = 0, neu = 0;
81 82 83 84 85 86
    if (acc_positive_t != nullptr && acc_negative_t != nullptr &&
        acc_neutral_t != nullptr) {
      pos = acc_positive_t->data<T>()[0];
      neg = acc_negative_t->data<T>()[0];
      neu = acc_neutral_t->data<T>()[0];
    }
87
    auto evaluate_one_list = [&pos, &neg,
88
                              &neu](std::vector<PredictionResult> vec) {
89 90
      for (auto ite1 = vec.begin(); ite1 != vec.end(); ++ite1) {
        for (auto ite2 = ite1 + 1; ite2 != vec.end(); ++ite2) {
91
          if (ite1->label == ite2->label) {  // labels are equal, ignore.
92 93
            continue;
          }
94 95 96
          T w = (ite1->weight + ite2->weight) * 0.5;
          if (ite1->score == ite2->score) {
            neu += w;
97
          }
98 99 100
          (ite1->score - ite2->score) * (ite1->label - ite2->label) > 0.0
              ? pos += w
              : neg += w;
101 102 103 104 105 106 107 108 109 110 111 112 113 114
        }
      }
    };
    for (auto prediction : predictions) {
      evaluate_one_list(prediction.second);
    }
    *positive = pos;
    *negative = neg;
    *neutral = neu;
  }
};

}  // namespace operators
}  // namespace paddle