concat_and_split.cc 11.6 KB
Newer Older
C
chengduoZH 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 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. */

C
chengduo 已提交
15
#include "paddle/fluid/operators/math/concat_and_split.h"
L
Leo Chen 已提交
16
#include "paddle/fluid/platform/device_context.h"
17

L
Leo Chen 已提交
18
#include "paddle/phi/kernels/funcs/concat_and_split_functor.h"
19
#ifdef PADDLE_WITH_ASCEND_CL
20
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
21
#endif
Z
zn 已提交
22 23 24
#ifdef PADDLE_WITH_MLU
#include "paddle/fluid/operators/mlu/mlu_baseop.h"
#endif
25 26
#include "paddle/phi/common/bfloat16.h"
#include "paddle/phi/common/float16.h"
W
wanghuancoder 已提交
27

28
namespace phi {
29
class DenseTensor;
30
}  // namespace phi
31

C
chengduoZH 已提交
32 33 34 35 36
namespace paddle {
namespace operators {
namespace math {

/*
C
chengduoZH 已提交
37
 * All tensors' dimension should be the same and the values of
38
 * each dimension must be the same, except the axis dimension.
C
chengduoZH 已提交
39 40 41 42 43
 */
template <typename T>
class ConcatFunctor<platform::CPUDeviceContext, T> {
 public:
  void operator()(const platform::CPUDeviceContext& context,
44 45
                  const std::vector<framework::Tensor>& input,
                  int axis,
C
chengduoZH 已提交
46
                  framework::Tensor* output) {
L
Leo Chen 已提交
47 48
    phi::funcs::ConcatFunctor<phi::CPUContext, T> functor;
    functor(context, input, axis, output);
C
chengduoZH 已提交
49 50 51
  }
};

C
chengduoZH 已提交
52 53
/*
 * All tensors' dimension should be the same and the values of
54
 * each dimension must be the same, except the axis dimension.
C
chengduoZH 已提交
55
 */
C
chengduoZH 已提交
56
template <typename T>
C
chengduo 已提交
57
class SplitFunctor<platform::CPUDeviceContext, T> {
C
chengduoZH 已提交
58 59
 public:
  void operator()(const platform::CPUDeviceContext& context,
Q
qiaolongfei 已提交
60
                  const framework::Tensor& input,
C
chengduoZH 已提交
61
                  const std::vector<const framework::Tensor*>& ref_inputs,
62 63
                  const int axis,
                  std::vector<framework::Tensor*>* outputs) {
L
Leo Chen 已提交
64 65
    phi::funcs::SplitFunctor<phi::CPUContext, T> functor;
    functor(context, input, ref_inputs, axis, outputs);
C
chengduoZH 已提交
66 67
  }
};
68 69 70 71 72 73 74 75 76 77

#ifdef PADDLE_WITH_XPU
/*
 * All tensors' dimension should be the same and the values of
 * each dimension must be the same, except the axis dimension.
 */
template <typename T>
class ConcatFunctor<platform::XPUDeviceContext, T> {
 public:
  void operator()(const platform::XPUDeviceContext& context,
78 79
                  const std::vector<framework::Tensor>& input,
                  int axis,
80
                  framework::Tensor* output) {
81
    int dev_id = context.GetPlace().GetDeviceId();
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    platform::XPUDeviceGuard guard(dev_id);

    int num = input.size();
    auto input_dims = input[0].dims();

    std::vector<std::vector<int>> xdims_list(num);
    for (int i = 0; i < num; ++i) {
      std::vector<int> tmp_dims(input_dims.size());
      for (int j = 0; j < input_dims.size(); ++j) {
        tmp_dims[j] = input[i].dims()[j];
      }
      xdims_list[i] = tmp_dims;
    }

    std::vector<const T*> ptrs;
    for (int i = 0; i < num; ++i) {
      ptrs.push_back(input[i].data<T>());
    }

101 102
    auto r = xpu::concat<T>(
        context.x_context(), ptrs, output->data<T>(), xdims_list, axis);
103
    PADDLE_ENFORCE_EQ(
104 105
        r,
        XPU_SUCCESS,
106 107 108
        platform::errors::External(
            "XPU API return wrong value[%d %s], please check whether "
            "Baidu Kunlun Card is properly installed.",
109 110
            r,
            XPUAPIErrorMsg[r]));
111 112 113 114 115 116 117 118 119
  }
};

template <typename T>
class SplitFunctor<platform::XPUDeviceContext, T> {
 public:
  void operator()(const platform::XPUDeviceContext& context,
                  const framework::Tensor& input,
                  const std::vector<const framework::Tensor*>& ref_inputs,
120 121
                  const int axis,
                  std::vector<framework::Tensor*>* outputs) {
122
    int dev_id = context.GetPlace().GetDeviceId();
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    platform::XPUDeviceGuard guard(dev_id);

    auto& ins = ref_inputs;

    int num = ins.size();
    auto input_dims = ins[0]->dims();
    std::vector<int> split_list(num);
    std::vector<int> xdims_list(input_dims.size());
    int total_length = 0;
    for (int i = 0; i < num; ++i) {
      split_list[i] = ins[i]->dims()[axis];
      total_length += ins[i]->dims()[axis];
    }

    for (int i = 0; i < input_dims.size(); ++i) {
      if (i == axis) continue;
      xdims_list[i] = input_dims[i];
    }
    xdims_list[axis] = total_length;

    std::vector<T*> ptrs(num);
    for (int i = 0; i < num; ++i) {
      ptrs[i] = outputs->at(i)->data<T>();
    }

148 149 150 151 152 153
    auto r = xpu::split<T>(context.x_context(),
                           input.data<T>(),
                           ptrs,
                           xdims_list,
                           split_list,
                           axis);
154
    PADDLE_ENFORCE_EQ(
155 156
        r,
        XPU_SUCCESS,
157 158 159
        platform::errors::External(
            "XPU API return wrong value[%d %s], please check whether "
            "Baidu Kunlun Card is properly installed.",
160 161
            r,
            XPUAPIErrorMsg[r]));
162 163 164 165
  }
};
#endif

166 167 168 169 170
#ifdef PADDLE_WITH_ASCEND_CL
template <typename T>
class ConcatFunctor<platform::NPUDeviceContext, T> {
 public:
  void operator()(const platform::NPUDeviceContext& context,
171 172
                  const std::vector<framework::Tensor>& input,
                  int axis,
173
                  framework::Tensor* output) {
174
    int dev_id = context.GetPlace().GetDeviceId();
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    platform::NPUDeviceGuard guard(dev_id);

    std::vector<std::string> names;
    for (size_t i = 0; i < input.size(); ++i) {
      names.push_back("x" + std::to_string(i));
    }
    NpuOpRunner runner{
        "ConcatD",
        {input},
        {*output},
        {{"concat_dim", axis}, {"N", static_cast<int>(input.size())}}};
    runner.AddInputNames(names);
    runner.Run(context.stream());
  }
};

template <typename T>
class SplitFunctor<platform::NPUDeviceContext, T> {
 public:
  void operator()(const platform::NPUDeviceContext& context,
                  const framework::Tensor& input,
                  const std::vector<const framework::Tensor*>& ref_inputs,
197 198
                  const int axis,
                  std::vector<framework::Tensor*>* outputs) {
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    if (input.numel() == 0) {
      return;
    }

    size_t num = outputs->size();

    int input_rows = 1;
    auto dim_0 = ref_inputs[0]->dims();
    for (int i = 0; i < axis; ++i) {
      input_rows *= dim_0[i];
    }

    int input_cols = 0;

    std::vector<int64_t> output_cols(outputs->size());
    for (size_t i = 0; i < num; ++i) {
      int t_cols = ref_inputs[i]->numel() / input_rows;
      input_cols += t_cols;
      output_cols[i] = t_cols;
    }
219
    auto npu_place = context.GetPlace();
220 221 222 223 224 225 226 227 228 229

    // computation
    for (int k = 0; k < input_rows; ++k) {
      const T* src_ptr = input.data<T>() + k * input_cols;
      int col_idx = 0;
      for (size_t j = 0; j < num; ++j) {
        int col_len = output_cols[j];
        auto* out_tensor = outputs->at(j);
        if (out_tensor != nullptr) {
          T* dst_ptr = out_tensor->data<T>() + k * col_len;
230 231 232 233 234 235
          memory::Copy(npu_place,
                       dst_ptr,
                       npu_place,
                       src_ptr + col_idx,
                       sizeof(T) * col_len,
                       context.stream());
236 237 238 239 240 241 242 243
        }
        col_idx += col_len;
      }
    }
  }
};
#endif

Z
zn 已提交
244 245 246 247 248
#ifdef PADDLE_WITH_MLU
template <typename T>
class ConcatFunctor<platform::MLUDeviceContext, T> {
 public:
  void operator()(const platform::MLUDeviceContext& context,
249 250
                  const std::vector<framework::Tensor>& input,
                  int axis,
Z
zn 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
                  framework::Tensor* output) {
    int dev_id = context.GetPlace().GetDeviceId();
    platform::MLUDeviceGuard guard(dev_id);

    auto ins_size = input.size();

    const int axis_t = axis;
    const int ins_size_t = ins_size;

    // mlu should do sth
    // init ins tensors
    std::vector<const void*> inputs;
    std::vector<MLUCnnlTensorDesc> input_descs;
    std::vector<cnnlTensorDescriptor_t> desc_vector;
    for (size_t i = 0; i < ins_size; i++) {
      input_descs.emplace_back(MLUCnnlTensorDesc(
          input[i], CNNL_LAYOUT_ARRAY, ToCnnlDataType(input[i].dtype())));
      desc_vector.push_back(input_descs.back().get());
      inputs.push_back(input[i].data());
    }
    // init out tensors
272 273
    MLUCnnlTensorDesc output_desc(
        *output, CNNL_LAYOUT_ARRAY, ToCnnlDataType(output->dtype()));
Z
zn 已提交
274 275

    // MLU should do sth
276 277 278 279 280 281 282
    MLUCnnl::Concat(context,
                    ins_size_t,
                    axis_t,
                    desc_vector.data(),
                    inputs.data(),
                    output_desc.get(),
                    GetBasePtr(output));
Z
zn 已提交
283 284 285 286 287 288 289 290 291
  }
};

template <typename T>
class SplitFunctor<platform::MLUDeviceContext, T> {
 public:
  void operator()(const platform::MLUDeviceContext& context,
                  const framework::Tensor& input,
                  const std::vector<const framework::Tensor*>& ref_inputs,
292 293
                  const int axis,
                  std::vector<framework::Tensor*>* outputs) {
Z
zn 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    if (input.numel() == 0) {
      return;
    }

    int dev_id = context.GetPlace().GetDeviceId();
    platform::MLUDeviceGuard guard(dev_id);

    auto in_dims = input.dims();
    auto out_size = outputs->size();

    std::vector<framework::DDim> outs_dims(out_size, in_dims);
    for (size_t i = 0; i < out_size; ++i) {
      outs_dims[i][axis] = ref_inputs[i]->dims()[axis];
    }

    // init out tensors
    std::vector<void*> vct_tensor;
    std::vector<MLUCnnlTensorDesc> output_descs;
    std::vector<cnnlTensorDescriptor_t> desc_vector;
    for (size_t i = 0; i < out_size; i++) {
      (*outputs)[i]->Resize(outs_dims[i]);
      output_descs.emplace_back(
316 317
          MLUCnnlTensorDesc(*(*outputs)[i],
                            CNNL_LAYOUT_ARRAY,
Z
zn 已提交
318 319 320 321 322
                            ToCnnlDataType((*outputs)[i]->dtype())));
      desc_vector.push_back(output_descs.back().get());
      vct_tensor.push_back(GetBasePtr((*outputs)[i]));
    }
    // init in tensors
323 324
    MLUCnnlTensorDesc input_desc(
        input, CNNL_LAYOUT_ARRAY, ToCnnlDataType(input.dtype()));
Z
zn 已提交
325 326

    // MLU should do sth
327 328 329 330 331 332 333
    MLUCnnl::Split(context,
                   out_size,
                   axis,
                   input_desc.get(),
                   input.data(),
                   desc_vector.data(),
                   vct_tensor.data());
Z
zn 已提交
334 335 336 337
  }
};
#endif

C
chengduoZH 已提交
338 339
#define DEFINE_FUNCTOR(type)                                      \
  template class ConcatFunctor<platform::CPUDeviceContext, type>; \
C
chengduo 已提交
340
  template class SplitFunctor<platform::CPUDeviceContext, type>;
C
chengduoZH 已提交
341

C
chengduoZH 已提交
342
FOR_ALL_TYPES(DEFINE_FUNCTOR);
C
chengduoZH 已提交
343

344 345 346 347 348 349 350 351
#ifdef PADDLE_WITH_XPU
#define DEFINE_XPU_FUNCTOR(type)                                  \
  template class ConcatFunctor<platform::XPUDeviceContext, type>; \
  template class SplitFunctor<platform::XPUDeviceContext, type>;

DEFINE_XPU_FUNCTOR(float)
#endif

352 353 354 355 356 357 358 359
#ifdef PADDLE_WITH_ASCEND_CL
#define DEFINE_NPU_FUNCTOR(type)                                  \
  template class ConcatFunctor<platform::NPUDeviceContext, type>; \
  template class SplitFunctor<platform::NPUDeviceContext, type>;

FOR_ALL_TYPES(DEFINE_NPU_FUNCTOR)
#endif

Z
zn 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372
#ifdef PADDLE_WITH_MLU
#define DEFINE_MLU_FUNCTOR(type)                                  \
  template class ConcatFunctor<platform::MLUDeviceContext, type>; \
  template class SplitFunctor<platform::MLUDeviceContext, type>;
DEFINE_MLU_FUNCTOR(float)
DEFINE_MLU_FUNCTOR(platform::float16)
DEFINE_MLU_FUNCTOR(int64_t)
DEFINE_MLU_FUNCTOR(bool)
DEFINE_MLU_FUNCTOR(int)
DEFINE_MLU_FUNCTOR(int8_t)
DEFINE_MLU_FUNCTOR(int16_t)
DEFINE_MLU_FUNCTOR(uint8_t)
#endif
C
chengduoZH 已提交
373 374 375
}  // namespace math
}  // namespace operators
}  // namespace paddle