clip_by_norm_op.h 5.0 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 66
    } else {
      PADDLE_THROW("Unexpected branch, input variable type is %s",
S
sneaxiy 已提交
67
                   framework::ToTypeName(in_var->Type()));
68 69 70 71
    }

    PADDLE_ENFORCE_NOT_NULL(input);

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

    auto temp = (x_norm <= max_norm).template cast<T>().eval();
    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());
    out.device(place) = x * scaling.reshape(one_dim).broadcast(m_dsize);
  }
};

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
class ClipByNormOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of ClipByNormOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of ClipByNormOp should not be null.");
    auto max_norm = ctx->Attrs().Get<float>("max_norm");
    PADDLE_ENFORCE_GT(max_norm, 0, "max_norm should be greater than 0.");
    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",
             "(Tensor) The input of clip_by_norm op."
             "The number of dimensions must be between [1, 9].");
    AddOutput("Out",
              "(Tensor) The output of clip_by_norm op with shape as input(X)");
    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$.

Examples:
        .. code-block:: python

            data = fluid.layer.data(
                name='data', shape=[2, 4, 6], dtype='float32')
            reshaped = fluid.layers.clip_by_norm(
                x=data, max_norm=0.5)

)DOC");
  }
};

W
wwhu 已提交
140 141
}  // namespace operators
}  // namespace paddle