nce_op.h 8.0 KB
Newer Older
W
wanghaoshuang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

   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

W
wanghaoshuang 已提交
17
#include <math.h>
W
wanghaoshuang 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <random>
#include "paddle/framework/eigen.h"
#include "paddle/framework/op_registry.h"
#include "unsupported/Eigen/CXX11/Tensor"
namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;

template <typename Place, typename T>
void PrepareSamples(const framework::ExecutionContext& context) {
  auto label = context.Input<Tensor>("Label");
W
wanghaoshuang 已提交
34
  const int64_t* label_data = label->data<int64_t>();
W
wanghaoshuang 已提交
35 36
  auto label_dims = label->dims();
  int num_classes = context.Attr<int>("num_classes");
W
wanghaoshuang 已提交
37 38 39
  // for unitest
  std::vector<int> sampled_labels =
      context.Attr<std::vector<int>>("sampled_labels");
W
wanghaoshuang 已提交
40 41 42 43 44 45 46
  // random machine
  std::random_device rd;
  std::mt19937 rng(rd());
  std::uniform_int_distribution<int> rand(0, num_classes - 1);

  auto sample_labels = context.Output<Tensor>("SampleLabels");
  auto sample_labels_dims = sample_labels->dims();
W
wanghaoshuang 已提交
47 48
  int64_t* sample_labels_data =
      sample_labels->mutable_data<int64_t>(context.GetPlace());
W
wanghaoshuang 已提交
49 50

  int num_label = label_dims.size() == 2 ? label_dims[1] : 1;
W
wanghaoshuang 已提交
51
  int index = 0;
W
wanghaoshuang 已提交
52 53 54
  for (size_t i = 0; i < label_dims[0]; ++i) {
    int j = 0;
    for (; j < num_label; ++j) {
W
wanghaoshuang 已提交
55
      sample_labels_data[index++] = label_data[i * num_label + j];
W
wanghaoshuang 已提交
56
    }
W
wanghaoshuang 已提交
57 58 59 60 61 62 63 64
    if (sampled_labels.size() > 0) {
      for (auto label : sampled_labels) {
        sample_labels_data[index++] = label;
      }
    } else {
      for (; j < sample_labels_dims[1]; ++j) {
        sample_labels_data[index++] = rand(rng);
      }
W
wanghaoshuang 已提交
65 66 67 68 69 70 71 72 73 74
    }
  }
}

template <typename Place, typename T>
class NCEKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    PrepareSamples<Place, T>(context);
    auto sample_labels = context.Output<Tensor>("SampleLabels");
W
wanghaoshuang 已提交
75
    const int64_t* sample_labels_data = sample_labels->data<int64_t>();
W
wanghaoshuang 已提交
76 77 78 79 80 81 82 83
    auto sample_out = context.Output<Tensor>("SampleLogits");
    T* sample_out_data = sample_out->mutable_data<T>(context.GetPlace());
    auto label = context.Input<Tensor>("Label");
    auto sample_weight = context.Input<Tensor>("SampleWeight");
    const T* sample_weight_data = nullptr;
    if (sample_weight != nullptr) {
      sample_weight_data = sample_weight->data<T>();
    }
W
wanghaoshuang 已提交
84
    auto out = context.Output<Tensor>("Cost");
W
wanghaoshuang 已提交
85 86 87 88 89 90 91 92 93
    T* out_data = out->mutable_data<T>(context.GetPlace());
    int num_smalped_classes = context.Attr<int>("num_sampled_classes");
    int num_classes = context.Attr<int>("num_classes");
    int num_true_class = 1;
    if (label != nullptr) {
      num_true_class = label->dims()[1];
    }
    T b = 1. / num_classes * num_smalped_classes;
    // forward bias
W
wanghaoshuang 已提交
94
    auto bias = context.Input<Tensor>("Bias");
W
wanghaoshuang 已提交
95 96 97 98 99 100 101 102 103 104 105
    if (bias != nullptr) {
      const T* bias_data = bias->data<T>();
      for (size_t i = 0; i < sample_labels->numel(); ++i) {
        sample_out_data[i] = bias_data[sample_labels_data[i]];
      }
    } else {
      for (size_t i = 0; i < sample_labels->numel(); ++i) {
        sample_out_data[i] = 0;
      }
    }
    // forward mul
W
wanghaoshuang 已提交
106 107
    auto input_mat = EigenMatrix<T>::From(*(context.Input<Tensor>("Input")));
    auto weight_mat = EigenMatrix<T>::From(*(context.Input<Tensor>("Weight")));
W
wanghaoshuang 已提交
108 109 110 111 112 113 114
    for (size_t i = 0; i < sample_labels->numel(); ++i) {
      Eigen::Tensor<float, 0, Eigen::RowMajor, Eigen::DenseIndex> result =
          (input_mat.chip((int)(i / sample_labels->dims()[1]), 0) *
           weight_mat.chip(sample_labels_data[i], 0))
              .sum();
      sample_out_data[i] += result(0);
      // activation_->forward
W
wanghaoshuang 已提交
115
      sample_out_data[i] = (1. / (1. + exp(-sample_out_data[i])));
W
wanghaoshuang 已提交
116 117 118 119
    }
    // forward cost
    for (size_t i = 0; i < sample_labels->dims()[0]; ++i) {
      size_t j = 0;
W
wanghaoshuang 已提交
120 121
      out_data[i] = 0;
      T w = sample_weight == nullptr ? 1. : sample_weight_data[i];
W
wanghaoshuang 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
      // for true classes
      for (; j < num_true_class; ++j) {
        T o = sample_out_data[i * sample_out->dims()[1] + j];
        T cost = -log(o / (o + b));
        out_data[i] += w * cost;
      }
      // for sampled neg classes
      for (; j < sample_labels->dims()[1]; ++j) {
        T o = sample_out_data[i * sample_out->dims()[1] + j];
        T cost = -log(b / (o + b));
        out_data[i] += w * cost;
      }
    }
  }
};

template <typename Place, typename T>
class NCEGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
W
wanghaoshuang 已提交
142 143
    auto d_out = context.Input<Tensor>(framework::GradVarName("Cost"));
    const T* d_out_data = d_out->data<T>();
W
wanghaoshuang 已提交
144 145 146 147
    auto label = context.Input<Tensor>("Label");
    auto sample_out = context.Input<Tensor>("SampleLogits");
    const T* sample_out_data = sample_out->data<T>();
    auto sample_labels = context.Input<Tensor>("SampleLabels");
W
wanghaoshuang 已提交
148
    const int64_t* sample_labels_data = sample_labels->data<int64_t>();
W
wanghaoshuang 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
    auto sample_weight = context.Input<Tensor>("SampleWeight");
    const T* sample_weight_data = nullptr;
    if (sample_weight != nullptr) {
      sample_weight_data = sample_weight->data<T>();
    }
    int num_smalped_classes = context.Attr<int>("num_sampled_classes");
    int num_classes = context.Attr<int>("num_classes");
    int num_true_class = 1;
    if (label != nullptr) {
      num_true_class = label->dims()[1];
    }
    T b = 1. / num_classes * num_smalped_classes;
    Tensor sample_grad;  // tmp tensor
    T* sample_grad_data =
        sample_grad.mutable_data<T>(sample_labels->dims(), context.GetPlace());
    // backward cost
    for (size_t i = 0; i < sample_labels->numel(); ++i) {
      T o = sample_out_data[i];
      T w = sample_weight == nullptr
                ? 1
                : sample_weight_data[i / sample_labels->dims()[1]];
      sample_grad_data[i] = (i % sample_labels->dims()[1]) < num_true_class
W
wanghaoshuang 已提交
171 172 173
                                ? w * (b / (o + b)) * (o - 1)
                                : w * (o * (1 - o) / (o + b));
      sample_grad_data[i] *= d_out_data[i / sample_labels->dims()[1]];
W
wanghaoshuang 已提交
174 175
    }
    // get d_bias
W
wanghaoshuang 已提交
176
    auto d_bias = context.Output<Tensor>(framework::GradVarName("Bias"));
W
wanghaoshuang 已提交
177 178 179 180 181 182 183
    if (d_bias != nullptr) {
      T* d_bias_data = d_bias->mutable_data<T>(context.GetPlace());
      for (size_t i = 0; i < sample_labels->numel(); ++i) {
        d_bias_data[sample_labels_data[i]] += sample_grad_data[i];
      }
    }
    // get d_w
W
wanghaoshuang 已提交
184
    auto d_w = context.Output<Tensor>(framework::GradVarName("Weight"));
W
wanghaoshuang 已提交
185
    if (d_w != nullptr) {
W
wanghaoshuang 已提交
186
      d_w->mutable_data<T>(context.GetPlace());
W
wanghaoshuang 已提交
187
      auto d_w_matrix = EigenMatrix<T>::From(*d_w);
W
wanghaoshuang 已提交
188
      auto x_matrix = EigenMatrix<T>::From(*(context.Input<Tensor>("Input")));
W
wanghaoshuang 已提交
189
      for (size_t i = 0; i < sample_labels->numel(); ++i) {
W
wanghaoshuang 已提交
190
        d_w_matrix.chip(sample_labels_data[i], 0) +=
W
wanghaoshuang 已提交
191 192 193 194 195
            x_matrix.chip((int)(i / sample_labels->dims()[1]), 0) *
            sample_grad_data[i];
      }
    }
    // get d_x
W
wanghaoshuang 已提交
196
    auto d_x = context.Output<Tensor>(framework::GradVarName("Input"));
W
wanghaoshuang 已提交
197
    if (d_x != nullptr) {
W
wanghaoshuang 已提交
198
      d_x->mutable_data<T>(context.GetPlace());
W
wanghaoshuang 已提交
199
      auto d_x_matrix = EigenMatrix<T>::From(*d_x);
W
wanghaoshuang 已提交
200
      auto w_matrix = EigenMatrix<T>::From(*(context.Input<Tensor>("Weight")));
W
wanghaoshuang 已提交
201 202 203 204 205 206 207 208 209
      for (size_t i = 0; i < sample_labels->numel(); ++i) {
        d_x_matrix.chip((int)(i / sample_labels->dims()[1]), 0) +=
            w_matrix.chip(sample_labels_data[i], 0) * sample_grad_data[i];
      }
    }
  }
};
}  // namespace operators
}  // namespace paddle