common_infer_shape_functions.cc 7.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2020 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. */

#include "paddle/fluid/operators/common_infer_shape_functions.h"
L
Leo Chen 已提交
16

W
wanghuancoder 已提交
17 18 19 20 21 22
namespace paddle {
namespace framework {
class InferShapeContext;
}  // namespace framework
}  // namespace paddle

23 24 25 26 27 28
// This file almostly contains all the infershape functions that are used in
// operators.

namespace paddle {
namespace operators {
namespace details {
L
Leo Chen 已提交
29

30 31
inline void GetBroadcastDimsArrays(const framework::DDim &x_dims,
                                   const framework::DDim &y_dims,
32 33 34 35
                                   int *x_dims_array,
                                   int *y_dims_array,
                                   int *out_dims_array,
                                   const int max_dim,
36 37
                                   const int axis) {
  PADDLE_ENFORCE_GE(
38 39
      axis,
      0,
40 41 42
      platform::errors::InvalidArgument(
          "Axis should be great than or equal to 0, but received axis is %d.",
          axis));
43
  PADDLE_ENFORCE_LE(axis,
44
                    max_dim,
45 46
                    platform::errors::InvalidArgument(
                        "Axis should be less than %d, but received axis is %d.",
47 48
                        max_dim,
                        axis));
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  if (x_dims.size() > y_dims.size()) {
    std::fill(y_dims_array, y_dims_array + axis, 1);
    if (axis + y_dims.size() < max_dim) {
      std::fill(y_dims_array + axis + y_dims.size(), y_dims_array + max_dim, 1);
    }
    std::copy(x_dims.Get(), x_dims.Get() + x_dims.size(), x_dims_array);
    std::copy(y_dims.Get(), y_dims.Get() + y_dims.size(), y_dims_array + axis);
  } else {
    std::fill(x_dims_array, x_dims_array + axis, 1);
    if (axis + x_dims.size() < max_dim) {
      std::fill(x_dims_array + axis + x_dims.size(), x_dims_array + max_dim, 1);
    }
    std::copy(x_dims.Get(), x_dims.Get() + x_dims.size(), x_dims_array + axis);
    std::copy(y_dims.Get(), y_dims.Get() + y_dims.size(), y_dims_array);
  }

  for (int i = 0; i < max_dim; i++) {
    PADDLE_ENFORCE_EQ(
        x_dims_array[i] == y_dims_array[i] || x_dims_array[i] <= 1 ||
            y_dims_array[i] <= 1,
69 70 71 72 73 74
        true,
        platform::errors::InvalidArgument(
            "Broadcast dimension mismatch. Operands could "
            "not be broadcast together with the shape of X = [%s] and "
            "the shape of Y = [%s]. Received [%d] in X is not equal to "
            "[%d] in Y at i:%d.",
75 76 77 78 79
            x_dims,
            y_dims,
            x_dims_array[i],
            y_dims_array[i],
            i));
80 81 82 83 84 85 86 87
    if ((x_dims_array[i] > 1 || y_dims_array[i] > 1) ||
        (x_dims_array[i] == 1 && y_dims_array[i] == 1)) {
      out_dims_array[i] = std::max(x_dims_array[i], y_dims_array[i]);
    } else {
      out_dims_array[i] = -1;
    }
  }
}
L
Leo Chen 已提交
88 89

framework::DDim BroadcastTwoDims(const framework::DDim &x_dims,
90 91
                                 const framework::DDim &y_dims,
                                 int axis) {
L
Leo Chen 已提交
92 93 94 95 96
  int max_dim = std::max(x_dims.size(), y_dims.size());
  axis = (axis == -1 ? std::abs(x_dims.size() - y_dims.size()) : axis);
  std::vector<int> x_dims_array(max_dim);
  std::vector<int> y_dims_array(max_dim);
  std::vector<int> out_dims_array(max_dim);
97 98 99 100 101 102
  GetBroadcastDimsArrays(x_dims,
                         y_dims,
                         x_dims_array.data(),
                         y_dims_array.data(),
                         out_dims_array.data(),
                         max_dim,
L
Leo Chen 已提交
103
                         axis);
104
  return phi::make_ddim(out_dims_array);
L
Leo Chen 已提交
105 106
}

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
}  // namespace details

// shape input(0) -> output(0) without change.
void UnaryOpUnchangedInferShape(framework::InferShapeContext *ctx) {
  auto x_name = ctx->GetInputNameByIdx(0);
  auto out_name = ctx->GetOutputNameByIdx(0);
  ctx->ShareDim(x_name, /*->*/ out_name);
  ctx->ShareLoD(x_name, /*->*/ out_name);
}

// shape input(0) -> output(0) without change, check if axis in range [-Rank(x),
// Rank(x)-1]
void UnaryOpUnchangedInferShapeCheckAxis(framework::InferShapeContext *ctx) {
  auto x_name = ctx->GetInputNameByIdx(0);
  auto out_name = ctx->GetOutputNameByIdx(0);
  auto x_dim = ctx->GetInputDim(x_name);
  auto x_rank = x_dim.size();
  auto axis = ctx->Attrs().Get<int>("axis");
  PADDLE_ENFORCE_GE(
126 127
      axis,
      -x_rank,
128 129 130
      platform::errors::InvalidArgument(
          "Attr(axis) value should be in range [-R, R-1], "
          "R is the rank of Input(X). But received axis: %d, R: %d.",
131 132
          axis,
          x_rank));
133
  PADDLE_ENFORCE_LT(
134 135
      axis,
      x_rank,
136 137 138
      platform::errors::InvalidArgument(
          "Attr(axis) value should be in range [-R, R-1], "
          "R is the rank of Input(X). But received axis: %d, R: %d.",
139 140
          axis,
          x_rank));
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
  ctx->ShareDim(x_name, /*->*/ out_name);
  ctx->ShareLoD(x_name, /*->*/ out_name);
}

// broadcast input(0) and input(1) -> output(0)
void BinaryOpBroadcastInferShape(framework::InferShapeContext *ctx) {
  auto x_name = ctx->GetInputNameByIdx(0);
  auto y_name = ctx->GetInputNameByIdx(1);
  auto out_name = ctx->GetOutputNameByIdx(0);
  auto x_dims = ctx->GetInputDim(x_name);
  auto y_dims = ctx->GetInputDim(y_name);
  PADDLE_ENFORCE_EQ(
      ctx->GetInputsVarType(y_name).front(),
      framework::proto::VarType::LOD_TENSOR,
      platform::errors::InvalidArgument(
          "The var type of input %s should be LoDTensor, but got %s.",
157 158
          ctx->Inputs(y_name).front(),
          ctx->GetInputsVarType(y_name).front()));
159 160 161

  if (ctx->GetInputsVarType(x_name).front() ==
      framework::proto::VarType::SELECTED_ROWS) {
162 163
    PADDLE_ENFORCE_EQ(y_dims.size(),
                      1u,
164 165 166 167 168 169 170
                      platform::errors::InvalidArgument(
                          "For binary broadcastable operator, if X is "
                          "Sparse(VarType.SELECTED_ROWS"
                          "), Y must be scalar, and the size of Y should be 1. "
                          "But reveived the size of Y = %s.",
                          y_dims.size()));
    PADDLE_ENFORCE_EQ(
171 172
        y_dims[0],
        1,
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
        platform::errors::InvalidArgument(
            "For binary broadcastable operator, if X is "
            "Sparse(VarType.SELECTED_ROWS"
            "), Y must be scalar, the first dimension of Y should be 1. "
            "But reveived the first dimension of Y = %s.",
            y_dims[0]));
  } else if (ctx->GetInputsVarType(x_name).front() !=
             framework::proto::VarType::LOD_TENSOR) {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "For binary broadcastable operator, the var type of input X should "
        "be LOD_TENSOR, but got %s",
        ctx->GetInputsVarType(x_name).front()));
  }

  if (x_dims == y_dims) {
    ctx->ShareDim(x_name, /*->*/ out_name);
    ctx->ShareLoD(x_name, /*->*/ out_name);
  } else {
    int axis = ctx->Attrs().Get<int>("axis");
L
Leo Chen 已提交
192 193
    auto out_dims = details::BroadcastTwoDims(x_dims, y_dims, axis);
    ctx->SetOutputDim(out_name, out_dims);
194 195 196 197 198 199
    ctx->ShareLoD(x_name, /*->*/ out_name);
  }
}

}  // namespace operators
}  // namespace paddle