set_value_op_npu.cc 16.4 KB
Newer Older
X
xiongkun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 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 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 183 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 221 222 223 224 225 226 227 228 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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
/* Copyright (c) 2021 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/set_value_op.h"
#include "paddle/fluid/operators/assign_value_op.h"
#include "paddle/fluid/operators/npu_op_runner.h"
#include "paddle/fluid/operators/slice_utils.h"
#include "paddle/fluid/operators/utils.h"
#include "paddle/fluid/platform/enforce.h"

namespace paddle {
namespace operators {
template <typename DeviceContext, typename T>
class SetValueNPUKernel : public framework::OpKernel<T> {
 private:
  using Vector_Int64 = std::vector<int64_t>;
  void GetNPUStartEndSteps(const Vector_Int64& start, const Vector_Int64& end,
                           const Vector_Int64& steps, const Vector_Int64& axes,
                           const framework::DDim& in_dim,
                           std::vector<std::vector<int64_t>>& output) const {
    int rank = in_dim.size();
    for (int i = 0; i < rank; ++i) {
      int axis_size = in_dim[i];
      auto iter = find(axes.begin(), axes.end(), i);
      if (iter != axes.end()) {
        int idx = iter - axes.begin();
        output[0].push_back(start[idx]);  // set as the same as raw input
        output[1].push_back(end[idx]);
        output[2].push_back(steps[idx]);
      } else {
        output[0].push_back(0);          // begin 0
        output[1].push_back(axis_size);  // end = last one
        output[2].push_back(1);          // step = 1
      }
    }
  }

  inline std::vector<int> MininumPadNumberMakeSureLastDimGT8(
      const std::vector<std::vector<int64_t>>& npu_slice) const {
    int rank = npu_slice[0].size();
    int last_dim_start = npu_slice[0][rank - 1];
    int last_dim_end = npu_slice[1][rank - 1];
    int last_dim_step = npu_slice[2][rank - 1];
    int min_end = last_dim_start + last_dim_step * min_last_dim_value_;
    int raw_last_dim_len = (last_dim_end - last_dim_start) / last_dim_step;
    return std::vector<int>({std::max(0, min_end - last_dim_end),
                             min_last_dim_value_ - raw_last_dim_len});
  }

  inline void TileTensor(const framework::ExecutionContext* ctx,
                         const Tensor* input, Tensor* output) const {
    VLOG(4) << "start to tile tensor function, which calls the npu operator "
               "TileWithAxis";
    // UNSQUEEZE last dim + TILE last dim * min_last_dim_value_
    Tensor reshape_tensor;
    auto reshape_dims = framework::vectorize<int>(input->dims());
    reshape_dims.push_back(1);
    reshape_tensor.ShareDataWith(*input);
    reshape_tensor.Resize(framework::make_ddim(reshape_dims));

    auto output_dims = framework::vectorize<int>(input->dims());
    output_dims.push_back(min_last_dim_value_);
    output->mutable_data<T>(framework::make_ddim(output_dims), ctx->GetPlace());

    framework::NPUAttributeMap attr;
    attr["axis"] = static_cast<int>(reshape_dims.size() - 1);
    attr["tiles"] = min_last_dim_value_;
    auto stream =
        ctx->template device_context<paddle::platform::NPUDeviceContext>()
            .stream();
    NpuOpRunner("TileWithAxis", {reshape_tensor}, {*output}, attr).Run(stream);
  }

  inline void BroadcastToD(const framework::ExecutionContext* ctx,
                           const Tensor* input,
                           const std::vector<int64_t>* shape,
                           Tensor* output) const {
    VLOG(4) << "Start BroadCast To";
    auto new_shape = std::vector<int32_t>(shape->begin(), shape->end());
    output->mutable_data<T>(framework::make_ddim(new_shape), ctx->GetPlace());
    framework::NPUAttributeMap attr;
    attr["shape"] = new_shape;
    auto stream =
        ctx->template device_context<paddle::platform::NPUDeviceContext>()
            .stream();
    NpuOpRunner("BroadcastToD", {*input}, {*output}, attr).Run(stream);
  }

  inline void CropTensor(const framework::ExecutionContext* ctx,
                         const Tensor* input, Tensor* output) const {
    auto out_dims = output->dims();
    auto in_dims = input->dims();
    int rank = in_dims.size();
    in_dims[rank - 1] = 1;
    output->Resize(in_dims);  // unsqueeze output -> [..., 1]
    framework::NPUAttributeMap attr;
    attr["axis"] = 0;
    attr["offsets"] = std::vector<int>(rank, 0);
    auto stream =
        ctx->template device_context<paddle::platform::NPUDeviceContext>()
            .stream();
    NpuOpRunner("Crop", {*input, *output}, {*output}, attr).Run(stream);
    output->Resize(out_dims);  // restore it
  }

  void SliceAssignNPU(const framework::ExecutionContext* ctx,
                      const Tensor* value_tensor, Vector_Int64& start,
                      Vector_Int64& end, Vector_Int64& steps,
                      Vector_Int64& axes, Tensor* assigned_tensor) const {
    // must ensure assigned_tensor and value_tensor have the same shape
    // not support steps < 0
    // output is also the assigned_tensor.
    VLOG(4) << "start function SliceAssignND";
    auto stream =
        ctx->template device_context<paddle::platform::NPUDeviceContext>()
            .stream();
    for (size_t i = 0; i < steps.size(); ++i) {
      PADDLE_ENFORCE_GT(steps[i], 0,
                        platform::errors::InvalidArgument(
                            "Currently NPU set_value operator doesn't support "
                            "negative steps, but got %d as step",
                            steps[i]));
    }
    std::vector<std::vector<int64_t>> npu_slice(3);
    GetNPUStartEndSteps(start, end, steps, axes, assigned_tensor->dims(),
                        npu_slice);
    auto tile_numbers = MininumPadNumberMakeSureLastDimGT8(npu_slice);
    int assigned_tensor_tile_number = tile_numbers[0];
    int value_tensor_tile_number = tile_numbers[1];

    VLOG(4) << "tile number is : " << assigned_tensor_tile_number << " "
            << value_tensor_tile_number;

    Tensor tiled_assigned_tns, tiled_value_tns;
    if (assigned_tensor_tile_number > 0) {
      TileTensor(ctx, assigned_tensor, &tiled_assigned_tns);
      TileTensor(ctx, value_tensor, &tiled_value_tns);
      // output have different shape, so use a tmp variable before_crop_output;
      // add last dim = min_last_dim_value_ in slice
      npu_slice[0].push_back(0);
      npu_slice[1].push_back(min_last_dim_value_);
      npu_slice[2].push_back(1);
    }

    framework::NPUAttributeMap attr_input;
    attr_input["begin"] =
        std::vector<int>(npu_slice[0].begin(), npu_slice[0].end());
    attr_input["end"] =
        std::vector<int>(npu_slice[1].begin(), npu_slice[1].end());
    attr_input["strides"] =
        std::vector<int>(npu_slice[2].begin(), npu_slice[2].end());
    attr_input["begin_mask"] = 0;
    attr_input["end_mask"] = 0;
    attr_input["ellipsis_mask"] = 0;
    attr_input["new_axis_mask"] = 0;
    attr_input["shrink_axis_mask"] = 0;
    if (assigned_tensor_tile_number > 0) {
      NpuOpRunner("StridedSliceAssignD", {tiled_assigned_tns, tiled_value_tns},
                  {tiled_assigned_tns}, attr_input)
          .Run(stream);  // Remember, set output = input, and this op will
                         // change the input value.
    } else {
      NpuOpRunner("StridedSliceAssignD", {*assigned_tensor, *value_tensor},
                  {*assigned_tensor}, attr_input)
          .Run(stream);
    }
    if (assigned_tensor_tile_number > 0) {
      CropTensor(ctx, &tiled_assigned_tns /*initialzied*/,
                 assigned_tensor /*initalized*/);
    }
  }

  void ModifyAxesAccordingNoneAxes(const Vector_Int64& none_axes,
                                   Vector_Int64& axes_to_modify) const {
    if (none_axes.empty()) return;
    auto none_axes_copy = none_axes;
    sort(none_axes_copy.begin(), none_axes_copy.end());
    for (size_t i = 0; i < axes_to_modify.size(); ++i) {
      int axis = axes_to_modify[i];
      auto upper =
          upper_bound(none_axes_copy.begin(), none_axes_copy.end(), axis);
      // Example: none_axes = [1,3,4,5,7]
      //          axis = 4
      //          find the element number less or equal than 4, which is
      //          3(1,3,4)
      //          axis becomes  4 + 3 = 7 ;
      axes_to_modify[i] = axis + (upper - none_axes_copy.begin());
    }
  }

  void UnsqueezeAccordingNoneAxes(const Vector_Int64& none_axes,
                                  Vector_Int64& slice_dims) const {
    // note : axes will change, because new axes inserted.
    // sum array to modify the axes. because more simply
    if (none_axes.empty()) return;
    Vector_Int64 slice_dims_with_none;
    size_t none_axes_cur = 0;
    for (size_t i = 0; i < slice_dims.size(); ++i) {
      while (none_axes_cur < none_axes.size() &&
             none_axes[none_axes_cur] <= static_cast<int>(i)) {
        slice_dims_with_none.push_back(1);
        none_axes_cur++;
      }
      slice_dims_with_none.push_back(slice_dims[i]);
    }
    // if the none_axes.size() > slice_dims.size(), append 1 after last dim
    while (none_axes_cur < none_axes.size()) {
      slice_dims_with_none.push_back(1);
      none_axes_cur++;
    }
    slice_dims = slice_dims_with_none;
  }

  void ModiftyDimsAccordingNoneAndDecrease(Vector_Int64& slice_dim,
                                           Vector_Int64& value_dim,
                                           Vector_Int64& axes,
                                           Vector_Int64& none_axes,
                                           Vector_Int64& dec_axes) const {
    // change the value of slice_dim, value_dim, start, end, steps, axes by none
    // and decrease axes
    // after change, this values can be passed to SliceAssignNPU() directly.

    // Modity Slice Dim
    UnsqueezeAccordingNoneAxes(none_axes, slice_dim);
    ModifyAxesAccordingNoneAxes(none_axes, dec_axes);
    ModifyAxesAccordingNoneAxes(none_axes, axes);
    // Modity Value Dim by new slice dim
    auto slice_dim_reverse = slice_dim;
    auto value_dim_reverse = value_dim;
    std::reverse(slice_dim_reverse.begin(), slice_dim_reverse.end());
    std::reverse(value_dim_reverse.begin(), value_dim_reverse.end());

    Vector_Int64 new_value_dim;
    PADDLE_ENFORCE_GE(
        slice_dim.size(), value_dim.size(),
        platform::errors::InvalidArgument("The size of expanded slice_dim(%d) "
                                          "must greater than the value_dim(%d)",
                                          slice_dim.size(), value_dim.size()));

    size_t value_cur = 0;
    size_t rank = slice_dim.size();
    for (size_t i = 0; i < rank; ++i) {
      auto& xsize = slice_dim_reverse[i];
      if (value_cur >= value_dim_reverse.size()) {
        new_value_dim.push_back(1);
        continue;
      }
      auto& vsize = value_dim_reverse[value_cur];
      auto it = find(dec_axes.begin(), dec_axes.end(), rank - 1 - i);
      if (it != dec_axes.end()) {
        // found, insert one dim ;
        PADDLE_ENFORCE_EQ(xsize, 1, platform::errors::InvalidArgument(
                                        "The dims refered by decrease axes is "
                                        "not equal to 1, some wrongs happen"));
        new_value_dim.push_back(1);
        continue;
      }
      if (xsize == vsize || vsize == 1) {
        new_value_dim.push_back(vsize);
        ++value_cur;
        continue;
      }
      PADDLE_THROW(platform::errors::InvalidArgument(
          "The shape of value_tensor can't be broadcast to value tensor, "
          "please check input"));
    }
    for (; value_cur < value_dim_reverse.size(); ++value_cur) {
      if (value_dim_reverse[value_cur] != 1) {
        PADDLE_THROW(platform::errors::InvalidArgument(
            "The shape of value_tensor can't be broadcast to value tensor, "
            "please check input"));
      }
    }
    std::reverse(new_value_dim.begin(), new_value_dim.end());
    value_dim = new_value_dim;
    return;
  }

 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    VLOG(2) << "Start Set Value Npu Kernel";
    auto* in = ctx.Input<framework::LoDTensor>("Input");
    auto* out = ctx.Output<framework::LoDTensor>("Out");
    auto* value_tensor = ctx.Input<framework::LoDTensor>("ValueTensor");
    auto starts_tensor_list =
        ctx.MultiInput<framework::Tensor>("StartsTensorList");
    auto ends_tensor_list = ctx.MultiInput<framework::Tensor>("EndsTensorList");
    auto steps_tensor_list =
        ctx.MultiInput<framework::Tensor>("StepsTensorList");
    auto axes = ctx.Attr<std::vector<int64_t>>("axes");
    auto starts = ctx.Attr<std::vector<int64_t>>("starts");
    auto ends = ctx.Attr<std::vector<int64_t>>("ends");
    auto steps = ctx.Attr<std::vector<int64_t>>("steps");
    auto shape = ctx.Attr<std::vector<int64_t>>("shape");
    auto decrease_axes = ctx.Attr<std::vector<int64_t>>("decrease_axes");
    auto none_axes = ctx.Attr<std::vector<int64_t>>("none_axes");
    auto dtype = in->type();

    if (dtype == framework::proto::VarType::FP64 ||
        dtype == framework::proto::VarType::INT64 ||
        dtype == framework::proto::VarType::BOOL) {
      auto value_type_name = GetValueName(dtype);
      PADDLE_THROW(platform::errors::InvalidArgument(
          "The NPU setvalue kernel currently only support FLOAT32 and INT32, "
          "but got type: %s",
          value_type_name.data()));
    }

    if (!starts_tensor_list.empty()) {
      starts = GetDataFromTensorList<int64_t>(starts_tensor_list);
    }
    if (!ends_tensor_list.empty()) {
      ends = GetDataFromTensorList<int64_t>(ends_tensor_list);
    }
    if (!steps_tensor_list.empty()) {
      steps = GetDataFromTensorList<int64_t>(steps_tensor_list);
    }

    auto in_dims = in->dims();
    CheckAndUpdateSliceAttrs(in_dims, axes, &starts, &ends, &steps);
    auto slice_dims = GetSliceDims(in_dims, axes, starts, ends, &steps);
    auto place = ctx.GetPlace();

    // aforementioned code is copyed directly from CPU kernel.
    // (@xiongkun03) the following is redesigned by xiongkun. because NPU can do
    // step slice assignment. so we deal with all none_axes and decrease_axes
    // here.
    // 1. we insert 1 into assigned_tensor_shape according to none_axes;
    // 2. we insert 1 into value_tensor_shape(value tensor) according to
    // decrease_axes;
    // 3. we reshape back the assigned_tensor. and return it.
    // note : we use a tmp_value_tensor as value_tns. it shares data with
    // value_tensor;
    // I believe the logic is more simple than cpu logic.

    TensorCopy(*in, place, out);
    Tensor value_t(dtype);

    if (value_tensor == nullptr) {
      auto value_dims = framework::make_ddim(shape);
      value_t.mutable_data<T>(value_dims, place);
      auto value_name = GetValueName(dtype);
      CopyVecotorToTensor<T>(value_name.c_str(), &value_t, ctx);
      value_t.Resize(value_dims);
    }

    const Tensor* value_tensor_ptr =
        (value_tensor == nullptr) ? &value_t : value_tensor;
    auto value_dims_vec = framework::vectorize(value_tensor_ptr->dims());
    auto slice_dims_vec = framework::vectorize(slice_dims);
    auto in_dims_vec = framework::vectorize(in_dims);

    UnsqueezeAccordingNoneAxes(none_axes, in_dims_vec);
    ModiftyDimsAccordingNoneAndDecrease(slice_dims_vec, value_dims_vec, axes,
                                        none_axes,
                                        decrease_axes);  // Modify and Check

    Tensor reshaped_value_tensor, broadcast_value_tensor;
    reshaped_value_tensor.ShareDataWith(*value_tensor_ptr);
    reshaped_value_tensor.Resize(framework::make_ddim(value_dims_vec));

    BroadcastToD(&ctx, &reshaped_value_tensor, &slice_dims_vec,
                 &broadcast_value_tensor /*inner function initialized*/);

    out->Resize(framework::make_ddim(in_dims_vec));
    SliceAssignNPU(&ctx, &broadcast_value_tensor, starts, ends, steps, axes,
                   out);
    out->Resize(in_dims);  // Reshape Back
  }

 private:
  const int min_last_dim_value_ =
      32 / sizeof(T);  // 16 for float16 , 8 for float32
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;
REGISTER_OP_NPU_KERNEL(
    set_value, ops::SetValueNPUKernel<paddle::platform::NPUDeviceContext, int>,
    ops::SetValueNPUKernel<paddle::platform::NPUDeviceContext, float>)