concat_and_split.cc 9.7 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"
16
#ifdef PADDLE_WITH_ASCEND_CL
17
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
18
#endif
19 20
#include "paddle/pten/common/bfloat16.h"
#include "paddle/pten/common/float16.h"
W
wanghuancoder 已提交
21

22 23 24 25
namespace pten {
class DenseTensor;
}  // namespace pten

W
wanghuancoder 已提交
26
namespace paddle {
27
namespace framework {}  // namespace framework
W
wanghuancoder 已提交
28 29 30 31
namespace platform {
class CPUDeviceContext;
}  // namespace platform
}  // namespace paddle
C
chengduoZH 已提交
32 33 34 35 36 37

namespace paddle {
namespace operators {
namespace math {

/*
C
chengduoZH 已提交
38
 * All tensors' dimension should be the same and the values of
39
 * each dimension must be the same, except the axis dimension.
C
chengduoZH 已提交
40 41 42 43 44
 */
template <typename T>
class ConcatFunctor<platform::CPUDeviceContext, T> {
 public:
  void operator()(const platform::CPUDeviceContext& context,
C
chengduoZH 已提交
45
                  const std::vector<framework::Tensor>& input, int axis,
C
chengduoZH 已提交
46
                  framework::Tensor* output) {
C
chengduoZH 已提交
47
    // TODO(zcd): Add input data validity checking
W
wuhuachaocoding 已提交
48
    size_t num = input.size();
C
chengduoZH 已提交
49

W
wuhuachaocoding 已提交
50
    int64_t rows = 1;
C
chengduoZH 已提交
51 52 53 54
    auto dim_0 = input[0].dims();
    for (int i = 0; i < axis; ++i) {
      rows *= dim_0[i];
    }
W
wuhuachaocoding 已提交
55
    int64_t out_rows = rows, out_cols = 0;
C
chengduoZH 已提交
56

C
chengduoZH 已提交
57
    std::vector<int64_t> input_cols(input.size());
W
wuhuachaocoding 已提交
58 59
    for (size_t i = 0; i < num; ++i) {
      int64_t t_cols = input[i].numel() / rows;
C
chengduoZH 已提交
60
      out_cols += t_cols;
C
chengduoZH 已提交
61
      input_cols[i] = t_cols;
C
chengduoZH 已提交
62
    }
63
    auto cpu_place = context.GetPlace();
C
chengduoZH 已提交
64

C
chengduoZH 已提交
65
    // computation
L
luotao1 已提交
66
    auto output_data = output->data<T>();
W
wuhuachaocoding 已提交
67 68 69
    int64_t col_idx = 0;
    for (size_t j = 0; j < num; ++j) {
      int64_t col_len = input_cols[j];
L
luotao1 已提交
70
      auto input_data = input[j].data<T>();
W
wuhuachaocoding 已提交
71
      for (int64_t k = 0; k < out_rows; ++k) {
L
luotao1 已提交
72 73
        memory::Copy(cpu_place, output_data + k * out_cols + col_idx, cpu_place,
                     input_data + k * col_len, sizeof(T) * col_len);
C
chengduoZH 已提交
74
      }
L
luotao1 已提交
75
      col_idx += col_len;
C
chengduoZH 已提交
76
    }
C
chengduoZH 已提交
77 78 79
  }
};

C
chengduoZH 已提交
80 81
/*
 * All tensors' dimension should be the same and the values of
82
 * each dimension must be the same, except the axis dimension.
C
chengduoZH 已提交
83
 */
C
chengduoZH 已提交
84
template <typename T>
C
chengduo 已提交
85
class SplitFunctor<platform::CPUDeviceContext, T> {
C
chengduoZH 已提交
86 87
 public:
  void operator()(const platform::CPUDeviceContext& context,
Q
qiaolongfei 已提交
88
                  const framework::Tensor& input,
C
chengduoZH 已提交
89
                  const std::vector<const framework::Tensor*>& ref_inputs,
Q
qiaolongfei 已提交
90
                  const int axis, std::vector<framework::Tensor*>* outputs) {
L
Leo Chen 已提交
91 92 93 94 95 96
    // NOTE(zhiqiu): split a tensor of shape [0,3,4] at axis=1, result in 3
    // tensors of shape [0,1,4]
    if (input.numel() == 0) {
      return;
    }

C
chengduoZH 已提交
97
    // TODO(zcd): Add input data validity checking
Q
qiaolongfei 已提交
98
    size_t num = outputs->size();
C
chengduoZH 已提交
99

C
chengduoZH 已提交
100
    int input_rows = 1;
Q
qiaolongfei 已提交
101
    auto dim_0 = ref_inputs[0]->dims();
C
chengduoZH 已提交
102 103 104
    for (int i = 0; i < axis; ++i) {
      input_rows *= dim_0[i];
    }
Q
qiaolongfei 已提交
105

C
chengduoZH 已提交
106 107
    int input_cols = 0;

108
    std::vector<int64_t> output_cols(outputs->size());
Q
qiaolongfei 已提交
109 110
    for (size_t i = 0; i < num; ++i) {
      int t_cols = ref_inputs[i]->numel() / input_rows;
C
chengduoZH 已提交
111 112 113
      input_cols += t_cols;
      output_cols[i] = t_cols;
    }
114
    auto cpu_place = context.GetPlace();
C
chengduoZH 已提交
115 116

    // computation
C
chengduoZH 已提交
117
    for (int k = 0; k < input_rows; ++k) {
C
chengduoZH 已提交
118 119
      const T* src_ptr = input.data<T>() + k * input_cols;
      int col_idx = 0;
C
chengduoZH 已提交
120
      for (size_t j = 0; j < num; ++j) {
C
chengduoZH 已提交
121
        int col_len = output_cols[j];
Q
qiaolongfei 已提交
122
        auto* out_tensor = outputs->at(j);
Q
qiaolongfei 已提交
123 124 125 126 127
        if (out_tensor != nullptr) {
          T* dst_ptr = out_tensor->data<T>() + k * col_len;
          memory::Copy(cpu_place, dst_ptr, cpu_place, src_ptr + col_idx,
                       sizeof(T) * col_len);
        }
C
chengduoZH 已提交
128 129 130
        col_idx += col_len;
      }
    }
C
chengduoZH 已提交
131 132
  }
};
133 134 135 136 137 138 139 140 141 142 143 144

#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,
                  const std::vector<framework::Tensor>& input, int axis,
                  framework::Tensor* output) {
145
    int dev_id = context.GetPlace().GetDeviceId();
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    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>());
    }

    auto r = xpu::concat<T>(context.x_context(), ptrs, output->data<T>(),
                            xdims_list, axis);
    PADDLE_ENFORCE_EQ(
        r, XPU_SUCCESS,
        platform::errors::External(
            "XPU API return wrong value[%d %s], please check whether "
            "Baidu Kunlun Card is properly installed.",
            r, XPUAPIErrorMsg[r]));
  }
};

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,
                  const int axis, std::vector<framework::Tensor*>* outputs) {
183
    int dev_id = context.GetPlace().GetDeviceId();
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    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>();
    }

    auto r = xpu::split<T>(context.x_context(), input.data<T>(), ptrs,
                           xdims_list, split_list, axis);
    PADDLE_ENFORCE_EQ(
        r, XPU_SUCCESS,
        platform::errors::External(
            "XPU API return wrong value[%d %s], please check whether "
            "Baidu Kunlun Card is properly installed.",
            r, XPUAPIErrorMsg[r]));
  }
};
#endif

221 222 223 224 225 226 227
#ifdef PADDLE_WITH_ASCEND_CL
template <typename T>
class ConcatFunctor<platform::NPUDeviceContext, T> {
 public:
  void operator()(const platform::NPUDeviceContext& context,
                  const std::vector<framework::Tensor>& input, int axis,
                  framework::Tensor* output) {
228
    int dev_id = context.GetPlace().GetDeviceId();
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    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,
                  const int axis, std::vector<framework::Tensor*>* outputs) {
    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;
    }
272
    auto npu_place = context.GetPlace();
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

    // 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;
          memory::Copy(npu_place, dst_ptr, npu_place, src_ptr + col_idx,
                       sizeof(T) * col_len, context.stream());
        }
        col_idx += col_len;
      }
    }
  }
};
#endif

C
chengduoZH 已提交
293 294
#define DEFINE_FUNCTOR(type)                                      \
  template class ConcatFunctor<platform::CPUDeviceContext, type>; \
C
chengduo 已提交
295
  template class SplitFunctor<platform::CPUDeviceContext, type>;
C
chengduoZH 已提交
296

C
chengduoZH 已提交
297
FOR_ALL_TYPES(DEFINE_FUNCTOR);
C
chengduoZH 已提交
298

299 300 301 302 303 304 305 306
#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

307 308 309 310 311 312 313 314
#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

C
chengduoZH 已提交
315 316 317
}  // namespace math
}  // namespace operators
}  // namespace paddle