sparse_weight_embedding_grad_kernel.cc 8.0 KB
Newer Older
P
phlrain 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2022 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.

P
phlrain 已提交
15
#include "paddle/phi/kernels/sparse_weight_embedding_grad_kernel.h"
P
phlrain 已提交
16 17 18
#include "paddle/phi/kernels/funcs/embedding_util.h"

#include "paddle/phi/backends/cpu/cpu_context.h"
P
phlrain 已提交
19
#include "paddle/phi/common/data_type.h"
P
phlrain 已提交
20
#include "paddle/phi/core/kernel_registry.h"
P
phlrain 已提交
21
#include "paddle/phi/core/utils/data_type.h"
P
phlrain 已提交
22 23 24 25

namespace phi {

template <typename T, typename Context>
P
phlrain 已提交
26 27 28 29 30 31 32
struct SparseWeightEmbeddingGradCPUFunctor {
  SparseWeightEmbeddingGradCPUFunctor(const Context& dev_ctx,
                                      const DenseTensor& input,
                                      const SelectedRows& weight,
                                      const DenseTensor& out_grad,
                                      int64_t padding_idx,
                                      DenseTensor* weight_grad)
P
phlrain 已提交
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
      : dev_ctx_(dev_ctx),
        input_(input),
        weight_(weight),
        out_grad_(out_grad),
        weight_grad_(weight_grad),
        padding_idx_(padding_idx) {}

  template <typename IdT>
  void apply() {
    DDim table_dim = weight_.dims();

    auto ids = CopyIdsToVector<IdT, int64_t>(input_);
    auto ids_num = static_cast<int64_t>(ids.size());

    // Since paddings are not trainable and fixed in forward, the gradient of
    // paddings makes no sense and we don't deal with it in backward.
    {
      auto* d_output = &out_grad_;
      // auto d_table = weight_grad_;
      auto* ids_data = ids.data();

      int64_t N = table_dim[0];
      int64_t D = table_dim[1];

      auto* d_output_data = d_output->template data<T>();

      dev_ctx_.template Alloc<T>(weight_grad_);
      auto* d_table_data = weight_grad_->data<T>();

      memset(d_table_data, 0, weight_grad_->numel() * sizeof(T));

      for (int64_t i = 0; i < ids_num; ++i) {
        if (padding_idx_ != kNoPadding && ids_data[i] == padding_idx_) {
          // the gradient of padding_idx should be 0, already done by memset, so
          // do nothing.
        } else {
          PADDLE_ENFORCE_LT(
              ids_data[i],
              N,
              phi::errors::InvalidArgument(
P
phlrain 已提交
73 74
                  "Variable value (input) of "
                  "OP(paddle.nn.functional.embedding) "
P
phlrain 已提交
75 76 77 78 79 80 81 82
                  "expected >= 0 and < %ld, but got %ld. Please check input "
                  "value.",
                  N,
                  ids_data[i]));
          PADDLE_ENFORCE_GE(
              ids_data[i],
              0,
              phi::errors::InvalidArgument(
P
phlrain 已提交
83 84
                  "Variable value (input) of "
                  "OP(paddle.nn.functional.embedding) "
P
phlrain 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
                  "expected >= 0 and < %ld, but got %ld. Please check input "
                  "value.",
                  N,
                  ids_data[i]));
          for (int j = 0; j < D; ++j) {
            d_table_data[ids_data[i] * D + j] += d_output_data[i * D + j];
          }
        }
      }
    }
  }

 private:
  const Context& dev_ctx_;
  const DenseTensor& input_;
  const SelectedRows& weight_;
  const DenseTensor& out_grad_;
  DenseTensor* weight_grad_;
  int64_t padding_idx_;
};

P
phlrain 已提交
106
template <typename T, typename Context>
P
phlrain 已提交
107 108 109 110 111 112 113
struct SparseWeightEmbeddingSparseGradCPUFunctor {
  SparseWeightEmbeddingSparseGradCPUFunctor(const Context& dev_ctx,
                                            const DenseTensor& input,
                                            const SelectedRows& weight,
                                            const DenseTensor& out_grad,
                                            int64_t padding_idx,
                                            SelectedRows* weight_grad)
P
phlrain 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
      : dev_ctx_(dev_ctx),
        input_(input),
        weight_(weight),
        out_grad_(out_grad),
        weight_grad_(weight_grad),
        padding_idx_(padding_idx) {}

  template <typename IdT>
  void apply() {
    DDim table_dim = weight_.dims();

    auto ids = CopyIdsToVector<IdT, int64_t>(input_);
    auto ids_num = static_cast<int64_t>(ids.size());

    // Since paddings are not trainable and fixed in forward, the gradient of
    // paddings makes no sense and we don't deal with it in backward.
    auto* d_table = weight_grad_;
    auto* d_output = &out_grad_;
    d_table->set_rows(ids);

    auto* d_table_value = d_table->mutable_value();
    d_table_value->Resize({ids_num, table_dim[1]});

P
phlrain 已提交
137
    dev_ctx_.template Alloc<T>(d_table_value);
P
phlrain 已提交
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

    d_table->set_height(table_dim[0]);

    auto* d_output_data = d_output->template data<T>();
    auto* d_table_data = d_table_value->template data<T>();

    auto d_output_dims = d_output->dims();
    auto d_output_dims_2d =
        phi::flatten_to_2d(d_output_dims, d_output_dims.size() - 1);
    PADDLE_ENFORCE_EQ(d_table_value->dims(),
                      d_output_dims_2d,
                      phi::errors::InvalidArgument(
                          "ShapeError: The shape of lookup_table@Grad and "
                          "output@Grad should be same. "
                          "But received lookup_table@Grad's shape = [%s], "
                          "output@Grad's shape = [%s].",
                          d_table_value->dims(),
                          d_output_dims_2d));
    memcpy(d_table_data, d_output_data, sizeof(T) * d_output->numel());
  }

 private:
  const Context& dev_ctx_;
  const DenseTensor& input_;
  const SelectedRows& weight_;
  const DenseTensor& out_grad_;
  SelectedRows* weight_grad_;
  int64_t padding_idx_;
};

P
phlrain 已提交
168 169 170 171 172 173 174
template <typename T, typename Context>
void SparseWeightEmbeddingGradKernel(const Context& ctx,
                                     const DenseTensor& input,
                                     const SelectedRows& weight,
                                     const DenseTensor& out_grad,
                                     int64_t padding_idx,
                                     DenseTensor* weight_grad) {
P
phlrain 已提交
175
  SparseWeightEmbeddingGradCPUFunctor<T, Context> functor(
P
phlrain 已提交
176
      ctx, input, weight, out_grad, padding_idx, weight_grad);
P
phlrain 已提交
177 178 179 180 181 182 183 184

  if (input.dtype() == phi::DataType::INT32) {
    functor.template apply<int>();
  } else if (input.dtype() == phi::DataType::INT64) {
    functor.template apply<int64_t>();
  } else {
    PADDLE_THROW("emebdding input only support int32 and int64");
  }
P
phlrain 已提交
185 186 187 188 189 190 191 192 193
}

template <typename T, typename Context>
void SparseWeightEmbeddingSparseGradKernel(const Context& ctx,
                                           const DenseTensor& input,
                                           const SelectedRows& weight,
                                           const DenseTensor& out_grad,
                                           int64_t padding_idx,
                                           SelectedRows* weight_grad) {
P
phlrain 已提交
194
  SparseWeightEmbeddingSparseGradCPUFunctor<T, Context> functor(
P
phlrain 已提交
195
      ctx, input, weight, out_grad, padding_idx, weight_grad);
P
phlrain 已提交
196 197 198 199 200 201 202 203

  if (input.dtype() == phi::DataType::INT32) {
    functor.template apply<int>();
  } else if (input.dtype() == phi::DataType::INT64) {
    functor.template apply<int64_t>();
  } else {
    PADDLE_THROW("emebdding input only support int32 and int64");
  }
P
phlrain 已提交
204 205 206 207
}

}  // namespace phi

P
phlrain 已提交
208
PD_REGISTER_KERNEL(sparse_weight_embedding_grad,
P
phlrain 已提交
209 210 211 212 213
                   CPU,
                   ALL_LAYOUT,
                   phi::SparseWeightEmbeddingGradKernel,
                   float,
                   double,
P
phlrain 已提交
214
                   phi::dtype::bfloat16) {}
P
phlrain 已提交
215 216 217 218 219 220 221

PD_REGISTER_KERNEL(sparse_weight_embedding_sparse_grad,
                   CPU,
                   ALL_LAYOUT,
                   phi::SparseWeightEmbeddingSparseGradKernel,
                   float,
                   double,
P
phlrain 已提交
222
                   phi::dtype::bfloat16) {}