cos_sim_op.h 8.0 KB
Newer Older
X
Xinghai Sun 已提交
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
#include "paddle/framework/op_registry.h"
C
chengduoZH 已提交
17
#include "paddle/operators/elementwise_op_function.h"
X
Xinghai Sun 已提交
18 19 20 21 22 23

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

C
refine  
chengduoZH 已提交
24 25 26 27 28 29 30 31 32 33 34
template <typename DeviceContext, typename T>
struct CosSimDyFunctor {
  CosSimDyFunctor(const T* x_norm, const T* y_norm, const T* x, const T* y,
                  const T* z, const T* dz, T* dy, int cols);
  inline void operator()(size_t) const;
};

template <typename Callback>
static void ForEachZip(size_t num, Callback callback) {
  for (size_t i = 0; i < num; ++i) {
    callback(i);
C
chengduoZH 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47
  }
}

template <typename T, bool same_row>
struct CosSimFunctor {
  CosSimFunctor(const T* x, const T* y, T* x_norm, T* y_norm, T* z, int cols)
      : x_norm_(x_norm),
        y_norm_(y_norm),
        x_(x),
        y_(y),
        z_(z),
        cols_(static_cast<size_t>(cols)) {}

C
refine  
chengduoZH 已提交
48 49 50
  inline HOSTDEVICE void operator()(size_t offset) const {
    auto* x = x_ + cols_ * offset;
    T xx = 0, xy = 0, yy = 0;
C
chengduoZH 已提交
51
    if (same_row) {
C
refine  
chengduoZH 已提交
52
      auto* y = y_ + cols_ * offset;
C
chengduoZH 已提交
53 54 55 56 57 58 59
      for (size_t i = 0; i < cols_; ++i) {
        xx += x[i] * x[i];
        yy += y[i] * y[i];
        xy += x[i] * y[i];
      }
      xx = sqrt(xx);
      yy = sqrt(yy);
C
refine  
chengduoZH 已提交
60 61 62
      y_norm_[offset] = yy;
      x_norm_[offset] = xx;
      z_[offset] = xy / (xx * yy);
C
chengduoZH 已提交
63
    } else {  // This can be wrote in a better way.
C
chengduoZH 已提交
64 65
      for (size_t i = 0; i < cols_; ++i) {
        xx += x[i] * x[i];
C
refine  
chengduoZH 已提交
66 67
        yy += y_[i] * y_[i];  // only need
        xy += x[i] * y_[i];
C
chengduoZH 已提交
68 69 70 71
      }
      xx = sqrt(xx);
      yy = sqrt(yy);
      y_norm_[0] = yy;
C
refine  
chengduoZH 已提交
72 73
      x_norm_[offset] = xx;
      z_[offset] = xy / (xx * yy);
C
chengduoZH 已提交
74 75
    }
  }
C
chengduoZH 已提交
76 77 78 79 80 81 82 83

  T* x_norm_;
  T* y_norm_;
  const T* x_;
  const T* y_;
  T* z_;
  const size_t cols_;
};
C
chengduoZH 已提交
84

Q
QI JUN 已提交
85
template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
86
class CosSimKernel : public framework::OpKernel<T> {
X
Xinghai Sun 已提交
87 88
 public:
  void Compute(const framework::ExecutionContext& context) const override {
89 90 91 92 93 94 95 96 97
    // get Tensor
    auto* in_x = context.Input<Tensor>("X");
    auto* in_y = context.Input<Tensor>("Y");
    auto* out_z = context.Output<Tensor>("Out");
    auto* out_x_norm = context.Output<Tensor>("XNorm");
    auto* out_y_norm = context.Output<Tensor>("YNorm");
    out_z->mutable_data<T>(context.GetPlace());
    out_x_norm->mutable_data<T>(context.GetPlace());
    out_y_norm->mutable_data<T>(context.GetPlace());
X
Xinghai Sun 已提交
98

99 100
    int rows_x = in_x->dims()[0];
    int rows_y = in_y->dims()[0];
C
chengduoZH 已提交
101 102

    int cols = framework::product(in_x->dims()) / rows_x;
C
chengduoZH 已提交
103 104 105 106 107

    if (rows_x == rows_y) {
      CosSimFunctor<T, true> functor(
          in_x->data<T>(), in_y->data<T>(), out_x_norm->data<T>(),
          out_y_norm->data<T>(), out_z->data<T>(), cols);
C
refine  
chengduoZH 已提交
108
      ForEachZip(rows_x, functor);
C
chengduoZH 已提交
109 110 111 112
    } else {
      CosSimFunctor<T, false> functor(
          in_x->data<T>(), in_y->data<T>(), out_x_norm->data<T>(),
          out_y_norm->data<T>(), out_z->data<T>(), cols);
C
refine  
chengduoZH 已提交
113
      ForEachZip(rows_x, functor);
C
chengduoZH 已提交
114
    }
X
Xinghai Sun 已提交
115 116 117
  }
};

C
chengduoZH 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130
template <typename T>
struct CosSimGradFunctor {
  CosSimGradFunctor(const T* x_norm, const T* y_norm, const T* x, const T* y,
                    const T* z, const T* dz, T* dx, int cols)
      : x_norm_(x_norm),
        y_norm_(y_norm),
        x_(x),
        y_(y),
        z_(z),
        dz_(dz),
        dx_(dx),
        cols_(static_cast<size_t>(cols)) {}

C
refine  
chengduoZH 已提交
131 132 133 134 135
  inline HOSTDEVICE void operator()(size_t offset) const {
    auto x_norm_square = x_norm_[offset] * x_norm_[offset];
    auto xy_norm_prod = x_norm_[offset] * y_norm_[offset];
    auto dz = dz_[offset];
    auto z = z_[offset];
C
chengduoZH 已提交
136

C
refine  
chengduoZH 已提交
137 138 139
    auto* dx = dx_ + cols_ * offset;
    auto* x = x_ + cols_ * offset;
    auto* y = y_ + cols_ * offset;
C
chengduoZH 已提交
140

C
chengduoZH 已提交
141 142
    auto reciprocal_xy_norm_prod = 1 / xy_norm_prod;
    auto reciprocal_x_norm_square = 1 / x_norm_square;
C
chengduoZH 已提交
143
    for (size_t i = 0; i < cols_; ++i) {
C
chengduoZH 已提交
144 145
      dx[i] = dz * (y[i] * reciprocal_xy_norm_prod -
                    z * x[i] * reciprocal_x_norm_square);
C
chengduoZH 已提交
146
    }
C
chengduoZH 已提交
147
  }
C
chengduoZH 已提交
148 149 150 151 152 153 154 155 156 157 158

  const T* x_norm_;
  const T* y_norm_;
  const T* x_;
  const T* y_;
  const T* z_;
  const T* dz_;
  T* dx_;
  const size_t cols_;
};

C
refine  
chengduoZH 已提交
159
template <typename T>
C
chengduoZH 已提交
160 161
struct CosSimDxFunctor {
  CosSimDxFunctor(const T* x_norm, const T* y_norm, const T* x, const T* y,
C
refine  
chengduoZH 已提交
162
                  const T* z, const T* dz, T* dx, int cols)
C
chengduoZH 已提交
163 164 165 166 167 168 169 170 171
      : x_norm_(x_norm),
        y_norm_(y_norm),
        x_(x),
        y_(y),
        z_(z),
        dz_(dz),
        dx_(dx),
        cols_(static_cast<size_t>(cols)) {}

C
refine  
chengduoZH 已提交
172 173 174 175 176
  inline HOSTDEVICE void operator()(size_t offset) const {
    auto xy_norm_prod = x_norm_[offset] * y_norm_[0];
    auto dz = dz_[offset];
    auto z = z_[offset];
    auto* x = x_ + cols_ * offset;
C
chengduoZH 已提交
177
    auto reciprocal_xy_norm_prod = 1 / xy_norm_prod;
C
refine  
chengduoZH 已提交
178 179 180
    auto x_norm_square = x_norm_[offset] * x_norm_[offset];
    auto* dx = dx_ + cols_ * offset;
    auto reciprocal_x_norm_square = 1 / x_norm_square;
C
chengduoZH 已提交
181

C
refine  
chengduoZH 已提交
182 183 184
    for (size_t i = 0; i < cols_; ++i) {
      dx[i] = dz * (y_[i] * reciprocal_xy_norm_prod -
                    z * x[i] * reciprocal_x_norm_square);
C
chengduoZH 已提交
185 186 187 188 189 190 191 192
    }
  }
  const T* x_norm_;
  const T* y_norm_;
  const T* x_;
  const T* y_;
  const T* z_;
  const T* dz_;
C
chengduoZH 已提交
193
  T* dx_;
C
chengduoZH 已提交
194 195
  const size_t cols_;
};
C
chengduoZH 已提交
196

Q
QI JUN 已提交
197
template <typename DeviceContext, typename T>
Y
Yu Yang 已提交
198
class CosSimGradKernel : public framework::OpKernel<T> {
X
Xinghai Sun 已提交
199 200
 public:
  void Compute(const framework::ExecutionContext& context) const override {
201 202 203 204 205 206 207 208 209
    // get Tensor
    auto* in_x = context.Input<Tensor>("X");
    auto* in_y = context.Input<Tensor>("Y");
    auto* in_z = context.Input<Tensor>("Out");
    auto* in_x_norm = context.Input<Tensor>("XNorm");
    auto* in_y_norm = context.Input<Tensor>("YNorm");
    auto* out_grad_x = context.Output<Tensor>(framework::GradVarName("X"));
    auto* out_grad_y = context.Output<Tensor>(framework::GradVarName("Y"));
    auto* in_grad_z = context.Input<Tensor>(framework::GradVarName("Out"));
X
Xinghai Sun 已提交
210

211
    // compute gradident
212 213 214
    int rows_x = in_x->dims()[0];
    int rows_y = in_y->dims()[0];
    int cols = framework::product(in_x->dims()) / rows_x;
C
chengduoZH 已提交
215

C
chengduoZH 已提交
216 217 218 219 220 221
    if (rows_x == rows_y) {
      if (out_grad_x) {
        CosSimGradFunctor<T> functor(
            in_x_norm->data<T>(), in_y_norm->data<T>(), in_x->data<T>(),
            in_y->data<T>(), in_z->data<T>(), in_grad_z->data<T>(),
            out_grad_x->mutable_data<T>(context.GetPlace()), cols);
C
refine  
chengduoZH 已提交
222
        ForEachZip(rows_x, functor);
C
chengduoZH 已提交
223 224 225 226 227 228
      }
      if (out_grad_y) {
        CosSimGradFunctor<T> functor(
            in_y_norm->data<T>(), in_x_norm->data<T>(), in_y->data<T>(),
            in_x->data<T>(), in_z->data<T>(), in_grad_z->data<T>(),
            out_grad_y->mutable_data<T>(context.GetPlace()), cols);
C
refine  
chengduoZH 已提交
229
        ForEachZip(rows_x, functor);
C
chengduoZH 已提交
230 231 232
      }
    } else {
      if (out_grad_x) {
C
refine  
chengduoZH 已提交
233
        CosSimDxFunctor<T> functor(
C
chengduoZH 已提交
234 235
            in_x_norm->data<T>(), in_y_norm->data<T>(), in_x->data<T>(),
            in_y->data<T>(), in_z->data<T>(), in_grad_z->data<T>(),
C
refine  
chengduoZH 已提交
236 237
            out_grad_x->mutable_data<T>(context.GetPlace()), cols);
        ForEachZip(rows_x, functor);
C
chengduoZH 已提交
238 239
      }
      if (out_grad_y) {
C
refine  
chengduoZH 已提交
240 241 242 243 244 245
        out_grad_y->mutable_data<T>(context.GetPlace());
        math::SetConstant<DeviceContext, T> set_zero;
        auto& dev_ctx = context.template device_context<DeviceContext>();
        set_zero(dev_ctx, out_grad_y, static_cast<T>(0));

        CosSimDyFunctor<DeviceContext, T> functor(
C
chengduoZH 已提交
246
            in_x_norm->data<T>(), in_y_norm->data<T>(), in_x->data<T>(),
C
refine  
chengduoZH 已提交
247 248 249
            in_y->data<T>(), in_z->data<T>(), in_grad_z->data<T>(),
            out_grad_y->data<T>(), cols);
        ForEachZip(rows_x, functor);
C
chengduoZH 已提交
250
      }
251
    }
X
Xinghai Sun 已提交
252 253 254 255 256
  }
};

}  // namespace operators
}  // namespace paddle