scatter.h 10.1 KB
Newer Older
1
/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
Z
zchen0211 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

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 <cstring>
17
#include <string>
18
#include <unordered_set>
Z
zchen0211 已提交
19

20
#include "paddle/phi/common/place.h"
21
#include "paddle/phi/core/ddim.h"
22
#include "paddle/phi/core/dense_tensor.h"
23
#include "paddle/phi/kernels/funcs/blas/blas.h"
24
#include "paddle/phi/kernels/funcs/eigen/common.h"
Z
zchen0211 已提交
25

26 27
namespace phi {
namespace funcs {
Z
zchen0211 已提交
28 29

/**
30
 * Return the updated array pointer, use blas or eigen lib to optimize time
31 32 33 34
 * cost
 */
template <typename T, typename IndexT = int>
typename std::enable_if<std::is_floating_point<T>::value>::type
35 36 37 38 39 40 41 42 43
elementwise_inner_add(const phi::CPUContext& ctx,
                      const T* src_pointer,
                      T* dst_pointer,
                      size_t src_index,
                      IndexT dst_index,
                      size_t slice_size) {
  auto blas = phi::funcs::GetBlas<phi::CPUContext, T>(ctx);
  blas.VADD(slice_size,
            src_pointer + src_index * slice_size,
44 45
            dst_pointer + dst_index * slice_size,
            dst_pointer + dst_index * slice_size);
46 47 48 49
}

template <typename T, typename IndexT = int>
typename std::enable_if<!std::is_floating_point<T>::value>::type
50 51 52 53 54 55 56 57 58 59
elementwise_inner_add(const phi::CPUContext& ctx,
                      const T* src_pointer,
                      T* dst_pointer,
                      size_t src_index,
                      IndexT dst_index,
                      size_t slice_size) {
  using EigenVector = typename phi::EigenTensor<T, 1>::Type;
  using ConstEigenVector = typename phi::EigenTensor<T, 1>::ConstType;

  phi::EigenDim<1>::Type dim;
60 61 62 63 64
  dim[0] = slice_size;

  ConstEigenVector eigen_src(src_pointer + src_index * slice_size, dim);
  EigenVector eigen_dst(dst_pointer + dst_index * slice_size, dim);
  eigen_dst += eigen_src;
65
}
66

67 68
/**
 * Return an updated tensor from source tensor, scattered according to index:
Z
zchen0211 已提交
69
 * dst[i] = src[index[i]]
Z
zchen0211 已提交
70
 * input[src]: type-T source Tensor
71
 * input[index]: type-IndexT index Tensor (1-D)
Z
zchen0211 已提交
72 73
 * return: output tensor
 */
74
template <typename T, typename IndexT = int>
75 76 77 78
void ScatterAssign(const phi::CPUContext& ctx,
                   const DenseTensor& src,
                   const DenseTensor& index,
                   DenseTensor* output) {
Z
zchen0211 已提交
79
  // check index of shape 1-D
80
  if (index.dims().size() == 2) {
81 82 83 84 85 86 87
    PADDLE_ENFORCE_EQ(
        index.dims()[1],
        1,
        phi::errors::InvalidArgument("index.dims()[1] should be 1 when "
                                     "index.dims().size() =2 in scatter_op."
                                     "But received value is [%d]",
                                     index.dims()[1]));
88
  } else {
89 90 91
    PADDLE_ENFORCE_EQ(index.dims().size(),
                      1,
                      phi::errors::InvalidArgument(
92 93 94
                          "index.dims().size() should be 1 or 2 in scatter_op."
                          "But received value is [%d]",
                          index.dims().size()));
95
  }
96
  int64_t index_size = index.dims()[0];
Z
zchen0211 已提交
97

98
  auto src_dims = src.dims();
Z
zchen0211 已提交
99 100
  auto dst_dims = output->dims();

101
  const T* p_src = src.data<T>();
102
  const IndexT* p_index = index.data<IndexT>();
Z
zchen0211 已提交
103 104
  T* p_output = output->data<T>();

Z
zchen0211 已提交
105
  // check src shape and dst shape should match
Z
zchen0211 已提交
106
  for (int i = 1; i < src_dims.size(); i++)
K
Kqnonrime 已提交
107
    PADDLE_ENFORCE_EQ(
108 109 110
        src_dims[i],
        dst_dims[i],
        phi::errors::InvalidArgument(
K
Kqnonrime 已提交
111 112 113
            "The dimensions of the source tensor and target tensor should"
            " match, but received source tensor's %d-th dimension is %d,"
            "target tensor's %d-th dimension is %d.",
114 115 116 117
            i,
            src_dims[i],
            i,
            dst_dims[i]));
Z
zchen0211 已提交
118 119 120

  // slice size
  size_t slice_size = 1;
Z
zchen0211 已提交
121
  for (int i = 1; i < src_dims.size(); ++i) slice_size *= src_dims[i];
Z
zchen0211 已提交
122

Z
1 api  
zchen0211 已提交
123 124
  const size_t slice_bytes = slice_size * sizeof(T);

Z
Zeng Jinle 已提交
125
  for (int64_t i = 0; i < index_size; ++i) {
126
    IndexT index_ = p_index[i];
127

128 129 130
    PADDLE_ENFORCE_GE(index_,
                      0,
                      phi::errors::OutOfRange(
131 132 133 134 135 136
                          "The index is out of bounds, "
                          "please check whether the dimensions of index and "
                          "input meet the requirements. It should "
                          "be greater than or equal to 0, but received [%d]",
                          index_));

Z
1 api  
zchen0211 已提交
137 138
    memcpy(p_output + index_ * slice_size, p_src + i * slice_size, slice_bytes);
  }
Z
zchen0211 已提交
139 140
}

141
template <typename T, typename IndexT = int>
142 143 144 145
void ScatterAssignAdd(const phi::CPUContext& ctx,
                      const DenseTensor& src,
                      const DenseTensor& index,
                      DenseTensor* output) {
146
  // check index of shape 1-D
147 148 149
  PADDLE_ENFORCE_EQ(
      index.dims().size() == 1 ||
          (index.dims().size() == 2 && index.dims()[1] == 1),
150 151 152 153 154 155
      true,
      phi::errors::InvalidArgument(
          "index's shape is error, "
          "expect index'dims shape is 1 or 2 and index.dims[1] is 1"
          "but got index'dims shape is %d",
          index.dims().size()));
156
  int64_t index_size = index.dims()[0];
157 158 159 160 161 162 163

  auto src_dims = src.dims();
  auto dst_dims = output->dims();

  const T* p_src = src.data<T>();
  const IndexT* p_index = index.data<IndexT>();

164
  T* p_output = output->data<T>();
165 166 167

  // check src shape and dst shape should match
  for (int i = 1; i < src_dims.size(); i++)
K
Kqnonrime 已提交
168
    PADDLE_ENFORCE_EQ(
169 170 171
        src_dims[i],
        dst_dims[i],
        phi::errors::InvalidArgument(
K
Kqnonrime 已提交
172 173 174
            "The dimensions of the source tensor and target tensor should"
            " match, but received source tensor's %d-th dimension is %d,"
            "target tensor's %d-th dimension is %d.",
175 176 177 178
            i,
            src_dims[i],
            i,
            dst_dims[i]));
179 180 181 182 183 184 185 186

  // slice size
  size_t slice_size = 1;
  for (int i = 1; i < src_dims.size(); ++i) slice_size *= src_dims[i];

  const size_t& slice_bytes = slice_size * sizeof(T);

  // if not in overwrite mode, need to init output data
187
  auto max_index = dst_dims[0];
188 189
  for (int64_t i = 0; i < index_size; ++i) {
    const IndexT& index_val = p_index[i];
190 191 192
    PADDLE_ENFORCE_GE(index_val,
                      0,
                      phi::errors::OutOfRange(
193 194 195 196
                          "The index is out of bounds, "
                          "please check whether the dimensions of index and "
                          "input meet the requirements. It should "
                          "be greater than or equal to 0, but received [%d]",
197
                          index_val));
198 199 200
    PADDLE_ENFORCE_LT(index_val,
                      max_index,
                      phi::errors::OutOfRange(
201 202 203 204
                          "The index is out of bounds, "
                          "please check whether the dimensions of index and "
                          "input meet the requirements. It should "
                          "be less than %d, but received %d",
205 206
                          max_index,
                          index_val));
207 208
    memset(p_output + slice_size * index_val, 0, slice_bytes);
  }
209

210 211 212
  // if not in overwrite mode, need to init output data
  for (int64_t i = 0; i < index_size; ++i) {
    const IndexT& index_val = p_index[i];
213 214
    elementwise_inner_add<T, IndexT>(
        ctx, p_src, p_output, i, index_val, slice_size);
215 216 217
  }
}

S
ShenLiang 已提交
218 219 220
// The function is only for scatter grad x,
// however update grad use gather
template <typename T, typename IndexT = int>
221 222 223
void CPUScatterGradForX(const phi::CPUContext& ctx,
                        const DenseTensor& index,
                        DenseTensor* output) {
224
  int64_t index_size = index.dims()[0];
S
ShenLiang 已提交
225 226 227 228 229 230
  auto dst_dims = output->dims();
  const IndexT* p_index = index.data<IndexT>();
  T* p_output = output->data<T>();
  size_t slice_size = 1;
  for (int i = 1; i < dst_dims.size(); ++i) slice_size *= dst_dims[i];
  const size_t slice_bytes = slice_size * sizeof(T);
231
  for (int64_t i = 0; i < index_size; ++i) {
S
ShenLiang 已提交
232 233 234 235 236
    const IndexT& index_ = p_index[i];
    memset(p_output + slice_size * index_, 0, slice_bytes);
  }
}

237
template <typename T, typename IndexT = int>
238 239 240 241
void ScatterNdAdd(const phi::CPUContext& ctx,
                  const DenseTensor& update,
                  const DenseTensor& index,
                  DenseTensor* output) {
242 243 244 245 246 247 248 249 250
  // update.shape = index.shape[:-1] + output.shape[index.shape[-1]:]
  auto index_dims = index.dims();
  auto index_dims_size = index_dims.size();

  auto output_dims = output->dims();
  auto output_dims_size = output_dims.size();

  const T* p_update = update.data<T>();
  const IndexT* p_index = index.data<IndexT>();
251
  T* p_output = output->data<T>();
252 253 254 255

  // final dim
  int64_t end_size = index_dims[index_dims_size - 1];
  // remain dim
256 257
  auto remain_ddim = phi::slice_ddim(index_dims, 0, index_dims_size - 1);
  int64_t remain_numel = phi::product(remain_ddim);
258 259 260 261 262 263 264
  // slice size
  int64_t slice_size = 1;
  for (int64_t i = end_size; i < output_dims_size; ++i) {
    slice_size *= output_dims[i];
  }

  for (int64_t i = 0; i < remain_numel; ++i) {
265
    IndexT index_val = 0;
266 267 268
    IndexT temp = 1;
    for (int64_t j = end_size - 1; j >= 0; --j) {
      IndexT index_value = p_index[i * end_size + j];
269
      PADDLE_ENFORCE_EQ(
270 271 272
          (index_value >= 0 && index_value < output_dims[j]),
          true,
          phi::errors::OutOfRange(
273 274 275 276
              "The index is out of bounds, "
              "please check whether the dimensions of index and "
              "input meet the requirements. It should "
              "be less than [%d] and greater or equal to 0, but received [%d]",
277 278
              output_dims[j],
              index_value));
279

280
      index_val += (index_value * temp);
281 282
      temp *= output_dims[j];
    }
283 284
    elementwise_inner_add<T, IndexT>(
        ctx, p_update, p_output, i, index_val, slice_size);
285 286 287
  }
}

288 289
}  // namespace funcs
}  // namespace phi