clip_by_norm_op.h 5.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
W
wwhu 已提交
2

L
Luo Tao 已提交
3 4 5
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
W
wwhu 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
W
wwhu 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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. */
W
wwhu 已提交
14 15 16

#pragma once

Y
Yi Wang 已提交
17 18
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
M
minqiyang 已提交
19
#include "paddle/fluid/framework/selected_rows.h"
20
#include "paddle/fluid/operators/math/selected_rows_functor.h"
Y
Yi Wang 已提交
21
#include "paddle/fluid/platform/transform.h"
W
wwhu 已提交
22 23 24 25 26

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
M
minqiyang 已提交
27
using SelectedRows = framework::SelectedRows;
W
wwhu 已提交
28 29 30 31
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenVector = framework::EigenVector<T, MajorType, IndexType>;

Q
QI JUN 已提交
32
template <typename DeviceContext, typename T>
W
wwhu 已提交
33 34 35 36
class ClipByNormKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    auto max_norm = context.Attr<T>("max_norm");
37
    auto in_var = context.InputVar("X");
W
wwhu 已提交
38

M
minqiyang 已提交
39
    Tensor* output = nullptr;
40 41 42
    const Tensor* input = nullptr;
    if (in_var->IsType<framework::LoDTensor>()) {
      input = context.Input<Tensor>("X");
M
minqiyang 已提交
43 44 45

      output = context.Output<Tensor>("Out");
      output->mutable_data<T>(context.GetPlace());
M
minqiyang 已提交
46 47
    } else if (in_var->IsType<SelectedRows>()) {
      auto* x = context.Input<SelectedRows>("X");
48 49 50

      // merge ids in selected rows first
      math::scatter::MergeAdd<DeviceContext, T> merge_func;
M
minqiyang 已提交
51 52 53 54
      SelectedRows* merged_input =
          const_cast<framework::Scope&>(context.scope())
              .Var()
              ->GetMutable<SelectedRows>();
55 56 57
      merge_func(context.template device_context<DeviceContext>(), *x,
                 merged_input);
      input = &(merged_input->value());
M
minqiyang 已提交
58

M
minqiyang 已提交
59 60 61 62 63
      SelectedRows* output_selected_rows = context.Output<SelectedRows>("Out");
      output_selected_rows->set_rows(merged_input->rows());
      output_selected_rows->set_height(merged_input->height());
      output = output_selected_rows->mutable_value();
      output->Resize(merged_input->value().dims());
64
      output->mutable_data<T>(context.GetPlace());
65
    } else {
开心的小妮's avatar
开心的小妮 已提交
66 67
      PADDLE_THROW(platform::errors::InvalidArgument(
          "Invalid input variable type, only support LodTensor and "
开心的小妮's avatar
开心的小妮 已提交
68 69
          "SelectedRows types, but got type is %s.",
          framework::ToTypeName(in_var->Type())));
70 71
    }

72 73 74 75
    PADDLE_ENFORCE_NOT_NULL(input,
                            platform::errors::InvalidArgument(
                                "Input(X) of ClipByNormOp should not be null. "
                                "Please check if it is created correctly."));
76

W
wwhu 已提交
77 78 79
    auto x = EigenVector<T>::Flatten(*input);
    auto out = EigenVector<T>::Flatten(*output);
    auto x_norm = x.square().sum().sqrt();
Q
QI JUN 已提交
80 81
    auto& place =
        *context.template device_context<DeviceContext>().eigen_device();
W
wwhu 已提交
82

83
    auto temp = (x_norm <= max_norm).template cast<T>();
W
wwhu 已提交
84 85 86
    auto scaling = temp + (static_cast<T>(1) - temp) * max_norm / x_norm;
    Eigen::array<int, 1> one_dim{{1}};
    Eigen::DSizes<int, 1> m_dsize(input->numel());
87 88 89 90 91 92
    if (context.GetPlace() == platform::CPUPlace()) {
      out.device(place) =
          x * scaling.reshape(one_dim).eval().broadcast(m_dsize);
    } else {
      out.device(place) = x * scaling.reshape(one_dim).broadcast(m_dsize);
    }
W
wwhu 已提交
93 94 95
  }
};

96 97 98 99 100 101
class ClipByNormOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
102 103 104 105 106 107 108 109
    PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true,
                      platform::errors::InvalidArgument(
                          "Input(X) of ClipByNormOp should not be null. Please "
                          "check if it is created correctly."));
    PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
                      platform::errors::InvalidArgument(
                          "Output(Out) of ClipByNormOp should not be null. "
                          "Please check if it is created correctly."));
110
    auto max_norm = ctx->Attrs().Get<float>("max_norm");
111 112 113 114
    PADDLE_ENFORCE_GT(max_norm, 0, platform::errors::InvalidArgument(
                                       "max_norm should be greater than 0. "
                                       "Received max_norm is %f.",
                                       max_norm));
115 116 117 118 119 120 121 122 123 124
    auto x_dims = ctx->GetInputDim("X");
    ctx->SetOutputDim("Out", x_dims);
    ctx->ShareLoD("X", /*->*/ "Out");
  }
};

class ClipByNormOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
W
wangguanzhong 已提交
125
             "(Tensor) The input of clip_by_norm op and data type is float32."
126 127
             "The number of dimensions must be between [1, 9].");
    AddOutput("Out",
W
wangguanzhong 已提交
128 129
              "(Tensor) The output of clip_by_norm op with shape as input(X)"
              "The data type is float32.");
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
    AddAttr<float>("max_norm", "(float) The maximum norm value.");
    AddComment(R"DOC(
ClipByNorm Operator.

This operator limits the L2 norm of the input $X$ within $max\_norm$.
If the L2 norm of $X$ is less than or equal to $max\_norm$, $Out$ will be
the same as $X$. If the L2 norm of $X$ is greater than $max\_norm$, $X$ will
be linearly scaled to make the L2 norm of $Out$ equal to $max\_norm$, as
shown in the following formula:

$$
Out = \\frac{max\\_norm * X}{norm(X)},
$$

where $norm(X)$ represents the L2 norm of $X$.

)DOC");
  }
};

W
wwhu 已提交
150 151
}  // namespace operators
}  // namespace paddle