index_sample_op.h 7.8 KB
Newer Older
C
Chengmo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* 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. */

#pragma once

#include <cmath>
#include <fstream>
#include <set>
#include <string>
#include <utility>
#include <vector>
23
#include "gflags/gflags.h"
24
#include "paddle/fluid/framework/convert_utils.h"
C
Chengmo 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#include "paddle/fluid/framework/op_registry.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
using DDim = framework::DDim;

template <typename T, typename IndexT = int>
void IndexSampleInner(const framework::ExecutionContext &context,
                      const LoDTensor &input, const LoDTensor &index,
                      LoDTensor *output) {
  auto input_dims = input.dims();
  auto index_dims = index.dims();

  int batch_size = input_dims[0];
  auto value_length = input_dims[1];
  auto index_length = index_dims[1];
  int index_ids_num = index.numel();

C
Chengmo 已提交
46 47
  std::vector<T> input_vec;
  std::vector<IndexT> index_vec;
48 49 50 51
  paddle::framework::TensorToVector(input, context.device_context(),
                                    &input_vec);
  paddle::framework::TensorToVector(index, context.device_context(),
                                    &index_vec);
C
Chengmo 已提交
52 53

  std::vector<T> res(index_ids_num);
C
Chengmo 已提交
54 55 56
  for (int i = 0; i < index_ids_num; i++) {
    int b = floor(i / index_length);
    PADDLE_ENFORCE_GE(
C
Chengmo 已提交
57
        index_vec[i], 0,
C
Chengmo 已提交
58 59 60 61
        platform::errors::InvalidArgument(
            "Variable value (index) of OP(index_sample) "
            "expected >= 0 and < %ld, but got %ld. Please check input "
            "value.",
C
Chengmo 已提交
62
            value_length, index_vec[i]));
C
Chengmo 已提交
63
    PADDLE_ENFORCE_LT(
C
Chengmo 已提交
64
        index_vec[i], value_length,
C
Chengmo 已提交
65 66 67 68
        platform::errors::InvalidArgument(
            "Variable value (index) of OP(index_sample) "
            "expected >= 0 and < %ld, but got %ld. Please check input "
            "value.",
C
Chengmo 已提交
69
            value_length, index_vec[i]));
C
Chengmo 已提交
70

C
Chengmo 已提交
71 72
    int v_i = b * value_length + static_cast<int>(index_vec[i]);
    T v = input_vec[v_i];
C
Chengmo 已提交
73 74
    VLOG(4) << "Index Sample: batch = " << b << " index = " << v_i
            << " value = " << v;
C
Chengmo 已提交
75
    res[i] = v;
C
Chengmo 已提交
76 77 78
  }

  auto ddim = framework::make_ddim({batch_size, index_length});
C
Chengmo 已提交
79 80
  output->mutable_data<T>(context.GetPlace());
  framework::TensorFromVector(res, context.device_context(), output);
C
Chengmo 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  output->Resize(ddim);
}

template <typename DeviceContext, typename T>
class IndexSampleKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    auto *input_var = ctx.InputVar("X");
    auto *index_var = ctx.InputVar("Index");

    auto &input_tensor = input_var->Get<LoDTensor>();
    auto &index_tensor = index_var->Get<LoDTensor>();

    auto *out_var = ctx.OutputVar("Out");
    auto *out_tensor = out_var->GetMutable<framework::LoDTensor>();

97 98
    const auto &index_type =
        framework::TransToProtoVarType(index_tensor.dtype());
C
Chengmo 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    bool index_type_match = index_type == framework::proto::VarType::INT32 ||
                            index_type == framework::proto::VarType::INT64;
    PADDLE_ENFORCE_EQ(index_type_match, true,
                      platform::errors::InvalidArgument(
                          "Input(Index) holds the wrong type, it holds %s, but "
                          "desires to be %s or %s",
                          paddle::framework::DataTypeToString(index_type),
                          paddle::framework::DataTypeToString(
                              framework::proto::VarType::INT32),
                          paddle::framework::DataTypeToString(
                              framework::proto::VarType::INT64)));
    if (index_type == framework::proto::VarType::INT32) {
      IndexSampleInner<T, int>(ctx, input_tensor, index_tensor, out_tensor);
    } else if (index_type == framework::proto::VarType::INT64) {
      IndexSampleInner<T, int64_t>(ctx, input_tensor, index_tensor, out_tensor);
    }
  }
};

template <typename T, typename IndexT = int>
void IndexSampleGradInner(const framework::ExecutionContext &context,
                          const LoDTensor &out_grad, const LoDTensor &index,
                          LoDTensor *x_grad) {
C
Chengmo 已提交
122 123
  std::vector<T> out_grad_vec;
  std::vector<IndexT> index_vec;
124 125 126 127
  paddle::framework::TensorToVector(out_grad, context.device_context(),
                                    &out_grad_vec);
  paddle::framework::TensorToVector(index, context.device_context(),
                                    &index_vec);
C
Chengmo 已提交
128

C
Chengmo 已提交
129 130 131 132 133 134 135
  auto index_dims = index.dims();
  auto x_grad_dims = x_grad->dims();

  auto value_length = x_grad_dims[1];
  auto index_length = index_dims[1];
  int index_ids_num = index.numel();

C
Chengmo 已提交
136
  std::vector<T> x_grad_vec(x_grad->numel(), 0);
C
Chengmo 已提交
137 138 139 140

  for (int i = 0; i < index_ids_num; i++) {
    int b = floor(i / index_length);
    PADDLE_ENFORCE_GE(
C
Chengmo 已提交
141
        index_vec[i], 0,
C
Chengmo 已提交
142 143 144 145
        platform::errors::InvalidArgument(
            "Variable value (index) of OP(index_sample_grad) "
            "expected >= 0 and < %ld, but got %ld. Please check input "
            "value.",
C
Chengmo 已提交
146
            value_length, index_vec[i]));
C
Chengmo 已提交
147
    PADDLE_ENFORCE_LT(
C
Chengmo 已提交
148
        index_vec[i], value_length,
C
Chengmo 已提交
149 150 151 152
        platform::errors::InvalidArgument(
            "Variable value (index) of OP(index_sample_grad) "
            "expected >= 0 and < %ld, but got %ld. Please check input "
            "value.",
C
Chengmo 已提交
153 154 155
            value_length, index_vec[i]));
    int v_i = b * value_length + static_cast<int>(index_vec[i]);
    x_grad_vec[v_i] += out_grad_vec[i];
C
Chengmo 已提交
156
  }
C
Chengmo 已提交
157 158 159
  x_grad->mutable_data<T>(context.GetPlace());
  framework::TensorFromVector(x_grad_vec, context.device_context(), x_grad);
  x_grad->Resize(x_grad_dims);
C
Chengmo 已提交
160 161 162 163 164 165 166 167 168 169 170 171 172 173
}

template <typename DeviceContext, typename T>
class IndexSampleGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &context) const override {
    auto *index_var = context.InputVar("Index");
    auto *x_grad_var = context.OutputVar(framework::GradVarName("X"));
    auto *out_grad_var = context.InputVar(framework::GradVarName("Out"));

    auto &index_tensor = index_var->Get<LoDTensor>();
    auto &out_grad_tensor = out_grad_var->Get<LoDTensor>();
    auto *x_grad_tensor = x_grad_var->GetMutable<framework::LoDTensor>();

174 175
    const auto &index_type =
        framework::TransToProtoVarType(index_tensor.dtype());
C
Chengmo 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    bool index_type_match = index_type == framework::proto::VarType::INT32 ||
                            index_type == framework::proto::VarType::INT64;
    PADDLE_ENFORCE_EQ(index_type_match, true,
                      platform::errors::InvalidArgument(
                          "Input(Index) holds the wrong type, it holds %s, but "
                          "desires to be %s or %s",
                          paddle::framework::DataTypeToString(index_type),
                          paddle::framework::DataTypeToString(
                              framework::proto::VarType::INT32),
                          paddle::framework::DataTypeToString(
                              framework::proto::VarType::INT64)));
    if (index_type == framework::proto::VarType::INT32) {
      IndexSampleGradInner<T, int>(context, out_grad_tensor, index_tensor,
                                   x_grad_tensor);
    } else if (index_type == framework::proto::VarType::INT64) {
      IndexSampleGradInner<T, int64_t>(context, out_grad_tensor, index_tensor,
                                       x_grad_tensor);
    }
  }
};

}  // namespace operators
}  // namespace paddle