lars_momentum_op.cc 8.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2018 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. */

W
Wu Yi 已提交
15
#include "paddle/fluid/operators/optimizers/lars_momentum_op.h"
16 17 18 19

namespace paddle {
namespace operators {

L
limingshu 已提交
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
class LarsMomentumOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
    OP_INOUT_CHECK(ctx->HasInputs("Param"), "Input", "Param", "LarsMomentum");
    OP_INOUT_CHECK(ctx->HasInputs("Grad"), "Input", "Grad", "LarsMomentum");
    OP_INOUT_CHECK(ctx->HasInputs("Velocity"), "Input", "Velocity",
                   "LarsMomentum");
    OP_INOUT_CHECK(ctx->HasInputs("LearningRate"), "Input", "LearningRate",
                   "LarsMomentum");
    OP_INOUT_CHECK(ctx->HasOutputs("ParamOut"), "Output", "ParamOut",
                   "LarsMomentum");
    OP_INOUT_CHECK(ctx->HasOutputs("VelocityOut"), "Output", "VelocityOut",
                   "LarsMomentum");
    PADDLE_ENFORCE_EQ(
        ctx->GetInputsVarType("Param").front(),
        framework::proto::VarType::LOD_TENSOR,
        platform::errors::InvalidArgument(
            "The input var's type should be LoDTensor, but the received is %s",
            ctx->GetInputsVarType("Param").front()));

    auto lr_dims = ctx->GetInputsDim("LearningRate");
    auto grad_dim = ctx->GetInputsDim("Grad");
    auto param_dim = ctx->GetInputsDim("Param");
    auto velocity_dim = ctx->GetInputsDim("Velocity");
    auto lars_weight_decays =
        ctx->Attrs().Get<std::vector<float>>("lars_weight_decay");
    auto multi_precision = ctx->Attrs().Get<bool>("multi_precision");

    PADDLE_ENFORCE_EQ(
        param_dim.size(), grad_dim.size(),
        platform::errors::InvalidArgument(
            "Input(Param) and Input(Grad) of LarsMomentumOp should have "
            "same quantity. But number of Param is [%d] and Grad is [%d].",
            param_dim.size(), grad_dim.size()));
    PADDLE_ENFORCE_EQ(
        param_dim.size(), velocity_dim.size(),
        platform::errors::InvalidArgument(
            "Input(Param) and Input(Velocity) of LarsMomentumOp should "
            "have same quantity. But number of Param is [%d] and Velocity "
            "is [%d].",
            param_dim.size(), velocity_dim.size()));
    PADDLE_ENFORCE_EQ(
        lars_weight_decays.size(), grad_dim.size(),
        platform::errors::InvalidArgument(
            "Attr(Lars_weight_decay) and "
            "Input(Grad) of LarsMomentumOp should have same quantity. "
            "But number of Lars_weight_decay is [%d] and Grad is [%d].",
            lars_weight_decays.size(), grad_dim.size()));

    if (multi_precision) {
      OP_INOUT_CHECK(ctx->HasInputs("MasterParam"), "Input", "MasterParam",
                     "LarsMomentumMultiPrecision");
      OP_INOUT_CHECK(ctx->HasOutputs("MasterParamOut"), "Output",
                     "MasterParamOut", "LarsMomentumMultiPrecision");
    }
    for (size_t i = 0; i < lr_dims.size(); ++i) {
      PADDLE_ENFORCE_EQ(framework::product(lr_dims[i]), 1,
                        platform::errors::InvalidArgument(
                            "Learning_rate should be a scalar. But Received "
                            "LearningRate's dim [%s]",
                            framework::product(lr_dims[i])));
    }

    for (size_t i = 0; i < param_dim.size(); ++i) {
      PADDLE_ENFORCE_EQ(ctx->GetInputsVarType("Grad")[i],
                        framework::proto::VarType::LOD_TENSOR,
                        platform::errors::InvalidArgument(
                            "The Var(%s)'s type should be LoDTensor, "
                            "but the received is %s",
                            ctx->Inputs("Grad")[i].front(),
                            ctx->GetInputsVarType("Grad")[i]));
      PADDLE_ENFORCE_EQ(
          param_dim[i], grad_dim[i],
          platform::errors::InvalidArgument(
              "Input(Param) and Input(Grad) input of LarsMomentumOp shall "
              "have same dimension. But Param`s dim is [%s] and Grad's dim "
              "is [%s].",
              param_dim[i], grad_dim[i]));
      PADDLE_ENFORCE_EQ(
          param_dim[i], velocity_dim[i],
          platform::errors::InvalidArgument(
              "Input(Param) and Input(Velocity) of LarsMomentumOp shall have "
              "same dimension. But Param dim [%s] differs with Velocity dim "
              "[%s].",
              param_dim[i], velocity_dim[i]));
    }
    ctx->SetOutputsDim("ParamOut", param_dim);
    ctx->SetOutputsDim("VelocityOut", param_dim);
    if (ctx->HasOutputs("MasterParamOut")) {
      ctx->SetOutputsDim("MasterParamOut", param_dim);
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    auto input_data_type =
        OperatorWithKernel::IndicateVarDataType(ctx, "Param");
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
  }
};

125 126 127 128 129
class LarsMomentumOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("Param",
             "(LoDTensor, default LoDTensor<float>) "
L
limingshu 已提交
130 131
             "Input parameter that has to be updated")
        .AsDuplicable();
132 133
    AddInput("Grad",
             "(LoDTensor, default LoDTensor<float>) "
L
limingshu 已提交
134 135
             "Input gradient of the parameter")
        .AsDuplicable();
136 137 138
    AddInput("Velocity",
             "(LoDTensor, default LoDTensor<float>) "
             "Input velocity (corresponding to the parameter) "
L
limingshu 已提交
139 140
             "that has to be updated")
        .AsDuplicable();
141 142
    AddInput("LearningRate",
             "(LoDTensor, default LoDTensor<float>) "
L
limingshu 已提交
143 144 145 146 147
             "Input learning rate")
        .AsDuplicable();
    AddInput("MasterParam", "FP32 master weight for AMP.")
        .AsDuplicable()
        .AsDispensable();
148 149
    AddOutput("ParamOut",
              "(LoDTensor) This output is updated parameter. "
L
limingshu 已提交
150 151
              "It shared memory with Input(Param).")
        .AsDuplicable();
152 153
    AddOutput("VelocityOut",
              "(LoDTensor) This output is updated velocity. "
L
limingshu 已提交
154 155
              "It shared memory with Input(Velocity).")
        .AsDuplicable();
156 157 158
    AddOutput("MasterParamOut",
              "The updated FP32 master weight for AMP. "
              "It shared memory with Input(MasterParam).")
L
limingshu 已提交
159
        .AsDuplicable()
160
        .AsDispensable();
161 162 163
    AddAttr<float>("mu", "(float) Momentum coefficient");
    AddAttr<float>("lars_coeff", "(float, default 0.001) LARS coefficient.")
        .SetDefault(0.001);
L
limingshu 已提交
164 165 166 167
    AddAttr<std::vector<float>>(
        "lars_weight_decay",
        "(std::vector<float>, default 0.0005) LARS weight decay params")
        .SetDefault({0.0005});
168 169 170
    AddAttr<float>("epsilon",
                   "(float, default 0.0) epsilon to avoid Division by Zero.")
        .SetDefault(0.0);
171 172 173 174 175 176 177 178 179
    AddAttr<bool>("multi_precision",
                  "(bool, default false) "
                  "Whether to use multi-precision during weight updating.")
        .SetDefault(false);
    AddAttr<float>(
        "rescale_grad",
        "(float, default 1.0) Multiply the gradient with `rescale_grad`"
        "before updating. Often choose to be `1.0/batch_size`.")
        .SetDefault(1.0f);
180 181 182 183 184 185 186 187

    AddComment(R"DOC(
Lars Momentum Optimizer.

This optimizer use LARS (https://arxiv.org/abs/1708.03888) to optimize each
weight using a local learning rate:

$$
M
minqiyang 已提交
188
local\_lr = \eta  *
189
    \frac{\left \| param \right \|}{\left \| grad \right \| + \beta *\left \| param \right \|} \\
M
minqiyang 已提交
190
velocity = mu * velocity +
191 192 193 194 195 196 197 198 199 200 201 202 203
    local\_lr * (grad + \beta * param) \\
param = param - velocity. \\
$$

Note that we use lars_weight_decay here to decay weights, you may need not to
use L2 regularizers in case of using LARS.

)DOC");
  }
};

class LarsMomentumOpVarTypeInference : public framework::VarTypeInference {
 public:
M
minqiyang 已提交
204
  void operator()(framework::InferVarTypeContext* ctx) const override {}
205 206 207 208 209
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
H
hong 已提交
210
REGISTER_OPERATOR(
L
limingshu 已提交
211
    lars_momentum, ops::LarsMomentumOp, ops::LarsMomentumOpMaker,
H
hong 已提交
212 213 214
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>,
    ops::LarsMomentumOpVarTypeInference);
215 216
REGISTER_OP_CPU_KERNEL(lars_momentum, ops::LarsMomentumOpKernel<float>,
                       ops::LarsMomentumOpKernel<double>);