math_function.cc 11.7 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. */

15
#include "paddle/phi/kernels/funcs/math_function.h"
16 17

#ifdef PADDLE_WITH_MKLML
18
#include "paddle/phi/backends/dynload/mklml.h"
19 20 21 22 23 24 25 26 27
#endif

#ifdef PADDLE_USE_OPENBLAS
#include <cblas.h>
#endif

#include <memory>
#include <utility>
#include <vector>
28

29
#include "paddle/phi/backends/cpu/cpu_context.h"
30
#include "paddle/phi/common/bfloat16.h"
31
#include "paddle/phi/common/data_type.h"
32
#include "paddle/phi/common/float16.h"
33 34
#include "paddle/phi/kernels/funcs/eigen/common.h"
#include "paddle/phi/kernels/funcs/math_function_impl.h"
35 36
#include "unsupported/Eigen/CXX11/Tensor"

37
namespace phi {
38 39
namespace funcs {

40
using float16 = phi::dtype::float16;
41

42 43 44 45 46 47 48 49 50 51 52
template struct SetConstant<phi::CPUContext, phi::dtype::float16>;
template struct SetConstant<phi::CPUContext, phi::dtype::bfloat16>;
template struct SetConstant<phi::CPUContext, float>;
template struct SetConstant<phi::CPUContext, double>;
template struct SetConstant<phi::CPUContext, int16_t>;
template struct SetConstant<phi::CPUContext, int>;
template struct SetConstant<phi::CPUContext, int64_t>;
template struct SetConstant<phi::CPUContext, bool>;
template struct SetConstant<phi::CPUContext, uint8_t>;
template struct SetConstant<phi::CPUContext, phi::dtype::complex<float>>;
template struct SetConstant<phi::CPUContext, phi::dtype::complex<double>>;
53 54 55

#ifdef PADDLE_WITH_XPU
template struct SetConstant<paddle::platform::XPUDeviceContext,
56
                            phi::dtype::float16>;
57
template struct SetConstant<paddle::platform::XPUDeviceContext,
58
                            phi::dtype::bfloat16>;
59 60 61 62 63 64 65 66
template struct SetConstant<paddle::platform::XPUDeviceContext, float>;
template struct SetConstant<paddle::platform::XPUDeviceContext, double>;
template struct SetConstant<paddle::platform::XPUDeviceContext, uint8_t>;
template struct SetConstant<paddle::platform::XPUDeviceContext, int16_t>;
template struct SetConstant<paddle::platform::XPUDeviceContext, int>;
template struct SetConstant<paddle::platform::XPUDeviceContext, int64_t>;
template struct SetConstant<paddle::platform::XPUDeviceContext, bool>;
template struct SetConstant<paddle::platform::XPUDeviceContext,
67
                            phi::dtype::complex<float>>;
68
template struct SetConstant<paddle::platform::XPUDeviceContext,
69
                            phi::dtype::complex<double>>;
H
houj04 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82

template struct SetConstant<phi::XPUContext, phi::dtype::float16>;
template struct SetConstant<phi::XPUContext, phi::dtype::bfloat16>;
template struct SetConstant<phi::XPUContext, float>;
template struct SetConstant<phi::XPUContext, double>;
template struct SetConstant<phi::XPUContext, uint8_t>;
template struct SetConstant<phi::XPUContext, int16_t>;
template struct SetConstant<phi::XPUContext, int>;
template struct SetConstant<phi::XPUContext, int64_t>;
template struct SetConstant<phi::XPUContext, bool>;
template struct SetConstant<phi::XPUContext, phi::dtype::complex<float>>;
template struct SetConstant<phi::XPUContext, phi::dtype::complex<double>>;

83 84
#endif

L
Leo Chen 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98
#define DEFINE_CPU_TRANS(RANK)                                            \
  template struct Transpose<phi::CPUContext, phi::dtype::float16, RANK>;  \
  template struct Transpose<phi::CPUContext, phi::dtype::bfloat16, RANK>; \
  template struct Transpose<phi::CPUContext, float, RANK>;                \
  template struct Transpose<phi::CPUContext, double, RANK>;               \
  template struct Transpose<phi::CPUContext, int, RANK>;                  \
  template struct Transpose<phi::CPUContext, int64_t, RANK>;              \
  template struct Transpose<phi::CPUContext, bool, RANK>;                 \
  template struct Transpose<phi::CPUContext, int16_t, RANK>;              \
  template struct Transpose<phi::CPUContext, uint8_t, RANK>;              \
  template struct Transpose<phi::CPUContext, int8_t, RANK>;               \
  template struct Transpose<phi::CPUContext,                              \
                            phi::dtype::complex<float>,                   \
                            RANK>;                                        \
99
  template struct Transpose<phi::CPUContext, phi::dtype::complex<double>, RANK>;
100 101 102 103 104 105 106 107

DEFINE_CPU_TRANS(1);
DEFINE_CPU_TRANS(2);
DEFINE_CPU_TRANS(3);
DEFINE_CPU_TRANS(4);
DEFINE_CPU_TRANS(5);
DEFINE_CPU_TRANS(6);

108 109 110
template <typename DeviceContext, typename T>
void TransposeNormal<DeviceContext, T>::operator()(
    const DeviceContext& context,
111 112
    const phi::DenseTensor& in,
    phi::DenseTensor* out,
113 114
    const std::vector<int>& axis) {
  const int rank = axis.size();
115 116
  auto in_stride = phi::stride(in.dims());
  auto out_stride = phi::stride(out->dims());
117 118 119 120 121 122 123 124 125 126 127 128
  const T* in_ptr = in.data<T>();
  T* out_ptr = out->data<T>();

  auto transpose_helper = [&](int64_t beg, int64_t end) {
    for (int64_t out_idx = beg; out_idx < end; ++out_idx) {
      int64_t in_idx = 0;
      int64_t tmp_idx = out_idx;
      // calculate the input index
      for (int i = 0; i < rank; ++i) {
        const int64_t coordinate = tmp_idx / out_stride[i];
        tmp_idx -= coordinate * out_stride[i];
        in_idx += coordinate * in_stride[axis[i]];
129
      }
130 131 132 133 134
      out_ptr[out_idx] = in_ptr[in_idx];
    }
  };
  transpose_helper(0, out->numel());
}
135 136

// define transpose normal
L
Leo Chen 已提交
137
#define DEFINE_CPU_TRANS_NORMAL(TYPE) \
138
  template struct TransposeNormal<phi::CPUContext, TYPE>
139

140 141
DEFINE_CPU_TRANS_NORMAL(phi::dtype::float16);
DEFINE_CPU_TRANS_NORMAL(phi::dtype::bfloat16);
142 143 144 145 146 147 148 149
DEFINE_CPU_TRANS_NORMAL(float);
DEFINE_CPU_TRANS_NORMAL(double);
DEFINE_CPU_TRANS_NORMAL(int);
DEFINE_CPU_TRANS_NORMAL(int64_t);
DEFINE_CPU_TRANS_NORMAL(bool);
DEFINE_CPU_TRANS_NORMAL(int16_t);
DEFINE_CPU_TRANS_NORMAL(uint8_t);
DEFINE_CPU_TRANS_NORMAL(int8_t);
150 151
DEFINE_CPU_TRANS_NORMAL(phi::dtype::complex<float>);
DEFINE_CPU_TRANS_NORMAL(phi::dtype::complex<double>);
152 153

struct TensorSetConstantCPU {
154
  TensorSetConstantCPU(phi::DenseTensor* tensor, float value)
155 156 157
      : tensor_(tensor), value_(value) {}
  template <typename T>
  void apply() const {
158
    auto cpu = phi::CPUPlace();
159 160 161
    auto* begin = tensor_->mutable_data<T>(cpu);
    std::fill(begin, begin + tensor_->numel(), static_cast<T>(value_));
  }
162
  phi::DenseTensor* tensor_;
163 164 165 166 167 168
  float value_;
};

template <>
void set_constant_with_place<paddle::platform::XPUPlace>(
    const paddle::platform::DeviceContext& context,
169
    phi::DenseTensor* tensor,
170
    float value) {
J
james 已提交
171 172 173 174 175 176 177
#ifdef PADDLE_WITH_XPU
  phi::VisitDataType(
      tensor->dtype(),
      TensorSetConstantXPU<float>(tensor, value, tensor->place()));
#else
  PADDLE_THROW(phi::errors::PreconditionNotMet("Not compiled with XPU!"));
#endif
178 179 180 181 182
}

template <>
void set_constant_with_place<paddle::platform::NPUPlace>(
    const paddle::platform::DeviceContext& context,
183
    phi::DenseTensor* tensor,
184
    float value) {
185
  PADDLE_THROW(phi::errors::Unimplemented("NPUPlace is not supported"));
186 187 188 189 190
}

template <>
void set_constant_with_place<paddle::platform::NPUPinnedPlace>(
    const paddle::platform::DeviceContext& context,
191
    phi::DenseTensor* tensor,
192
    float value) {
193
  PADDLE_THROW(phi::errors::Unimplemented("NPUPinnedPlace is not supported"));
194 195 196 197 198
}

template <>
void set_constant_with_place<paddle::platform::IPUPlace>(
    const paddle::platform::DeviceContext& context,
199
    phi::DenseTensor* tensor,
200
    float value) {
201
  PADDLE_THROW(phi::errors::Unimplemented("IPUPlace is not supported"));
202 203
}

204 205 206
template <>
void set_constant_with_place<paddle::platform::CustomPlace>(
    const paddle::platform::DeviceContext& context,
207
    phi::DenseTensor* tensor,
208
    float value) {
209
  PADDLE_THROW(phi::errors::Unimplemented("CustomPlace is not supported"));
210 211
}

212
template <>
213
void set_constant_with_place<phi::CPUPlace>(
214
    const paddle::platform::DeviceContext& context,
215
    phi::DenseTensor* tensor,
216
    float value) {
217
  phi::VisitDataType(tensor->dtype(), TensorSetConstantCPU(tensor, value));
218 219 220 221 222
}

template <>
void set_constant_with_place<paddle::platform::MLUPlace>(
    const paddle::platform::DeviceContext& context,
223
    phi::DenseTensor* tensor,
224
    float value) {
225
  PADDLE_THROW(phi::errors::Unimplemented("MLUPlace is not supported"));
226 227 228 229 230
}

template <>
void set_constant_with_place<paddle::platform::CUDAPinnedPlace>(
    const paddle::platform::DeviceContext& context,
231
    phi::DenseTensor* tensor,
232
    float value) {
233
  phi::VisitDataType(tensor->dtype(), TensorSetConstantCPU(tensor, value));
234 235
}

236 237
struct TensorSetConstantWithPlace
    : public std::unary_function<paddle::platform::Place, void> {
238
  TensorSetConstantWithPlace(const paddle::platform::DeviceContext& context,
239
                             phi::DenseTensor* tensor,
240 241 242 243 244 245 246 247 248
                             float value)
      : context_(context), tensor_(tensor), value_(value) {}

  template <typename Place>
  void operator()(Place place) const {
    set_constant_with_place<Place>(context_, tensor_, value_);
  }

  const paddle::platform::DeviceContext& context_;
249
  phi::DenseTensor* tensor_;
250 251 252 253
  float value_;
};

void set_constant(const paddle::platform::DeviceContext& context,
254
                  phi::DenseTensor* tensor,
255 256
                  float value) {
  TensorSetConstantWithPlace func(context, tensor, value);
257 258 259 260 261 262
#ifdef PADDLE_WITH_CUSTOM_DEVICE
  if (paddle::platform::is_custom_place(context.GetPlace())) {
    func(phi::CPUPlace());
    return;
  }
#endif
263 264 265
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  // tensor->place().apply_visitor(func);
  paddle::platform::VisitPlace(tensor->place(), func);
J
james 已提交
266 267
#elif defined(PADDLE_WITH_XPU)
  func(phi::XPUPlace());
268
#else
269
  func(phi::CPUPlace());
270 271 272
#endif
}

L
Leo Chen 已提交
273 274 275 276 277 278 279 280
template struct ColwiseSum<phi::CPUContext, float>;
template struct ColwiseSum<phi::CPUContext, double>;
template struct ColwiseSum<phi::CPUContext, int>;
template struct ColwiseSum<phi::CPUContext, int64_t>;

template struct RowwiseMean<phi::CPUContext, float>;
template struct RowwiseMean<phi::CPUContext, double>;

281
template <typename T>
L
Leo Chen 已提交
282 283
struct RowwiseAdd<phi::CPUContext, T> {
  void operator()(const phi::CPUContext& context,
284 285 286
                  const phi::DenseTensor& input,
                  const phi::DenseTensor& vector,
                  phi::DenseTensor* output) {
287 288 289 290 291 292
    auto in_dims = input.dims();
    auto out_dims = output->dims();
    auto size = input.numel() / in_dims[0];
    PADDLE_ENFORCE_EQ(
        vector.numel(),
        size,
293
        phi::errors::InvalidArgument(
294 295 296 297 298 299 300 301 302
            "The input vector size"
            " should be equal to the size of each row of input tensor."
            " Expected vector size=%d, but received %d",
            size,
            vector.numel()));
    const char* in_dims_cstr = in_dims.to_str().c_str();
    const char* out_dims_cstr = out_dims.to_str().c_str();
    PADDLE_ENFORCE_EQ(out_dims,
                      in_dims,
303
                      phi::errors::InvalidArgument(
304 305 306 307 308 309
                          "The output tensor shape should be same as the input"
                          " tensor shape. Expected output tensor shape: %s,"
                          " but received %s",
                          in_dims_cstr,
                          out_dims_cstr));

310 311 312
    auto in = phi::EigenMatrix<T>::From(input);
    auto vec = phi::EigenVector<T>::Flatten(vector);
    auto out = phi::EigenMatrix<T>::From(*output);
313 314 315 316 317 318 319

    for (int64_t i = 0; i < in_dims[0]; ++i) {
      out.chip(i, 0) = in.chip(i, 0) + vec;
    }
  }
};

L
Leo Chen 已提交
320 321
template struct RowwiseAdd<phi::CPUContext, float>;
template struct RowwiseAdd<phi::CPUContext, double>;
322 323

}  // namespace funcs
324
}  // namespace phi