fused_feedforward_op.cc 17.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Copyright (c) 2021 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. */

#include <algorithm>
#include <utility>
#include <vector>
18

19 20 21
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/fluid/operators/matmul_v2_op.h"
22
#include "paddle/phi/kernels/funcs/blas/blas.h"
23 24 25 26 27 28 29 30 31 32 33 34

namespace paddle {
namespace operators {
using Tensor = framework::Tensor;

class FusedFeedForwardOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext *context) const override {
    OP_INOUT_CHECK(context->HasInput("X"), "Input", "X", "fused_feedforward");
35 36 37
    OP_INOUT_CHECK(context->HasInput("Linear1Weight"),
                   "Input",
                   "Linear1Weight",
38
                   "fused_feedforward");
39 40 41
    OP_INOUT_CHECK(context->HasInput("Linear2Weight"),
                   "Input",
                   "Linear2Weight",
42
                   "fused_feedforward");
43 44 45 46 47
    OP_INOUT_CHECK(
        context->HasOutput("Out"), "Output", "Out", "fused_feedforward");
    OP_INOUT_CHECK(context->HasOutput("Dropout1Mask"),
                   "Output",
                   "Dropout1Mask",
48
                   "fused_feedforward");
49 50 51
    OP_INOUT_CHECK(context->HasOutput("Dropout2Mask"),
                   "Output",
                   "Dropout2Mask",
52
                   "fused_feedforward");
53 54 55
    OP_INOUT_CHECK(context->HasOutput("Linear1Out"),
                   "Output",
                   "Linear1Out",
56
                   "fused_feedforward");
57 58 59
    OP_INOUT_CHECK(context->HasOutput("Dropout1Out"),
                   "Output",
                   "Dropout1Out",
60
                   "fused_feedforward");
61 62 63
    OP_INOUT_CHECK(context->HasOutput("Dropout2Out"),
                   "Output",
                   "Dropout2Out",
64 65 66
                   "fused_feedforward");

    auto dim_x = context->GetInputDim("X");
67
    auto mat_dim_x = phi::funcs::CreateMatrixDescriptor(
68
        RowMatrixFromVector(dim_x), 0, false);
69 70
    // verify for the pre layer_norm, the feature size must be larger than 1
    PADDLE_ENFORCE_GT(
71 72
        mat_dim_x.width_,
        static_cast<size_t>(1),
73 74 75 76 77 78 79
        platform::errors::InvalidArgument("Product from the X shape[1] to "
                                          "shape[n-1] must be larger than 1!"));
    auto dim_Linear1Weight = context->GetInputDim("Linear1Weight");
    auto tmp_dim_x = dim_x;
    tmp_dim_x[dim_x.size() - 1] =
        dim_Linear1Weight[dim_Linear1Weight.size() - 1];
    context->SetOutputDim("Out", dim_x);
L
Li Min 已提交
80
    if (context->Attrs().Get<bool>("is_test") == false) {
81 82 83 84 85 86
      context->SetOutputDim("Dropout1Mask", tmp_dim_x);
    }
    context->SetOutputDim("Dropout1Out", tmp_dim_x);
    context->SetOutputDim("Linear1Out", tmp_dim_x);
    context->SetOutputDim("Dropout2Out", dim_x);

L
Li Min 已提交
87
    if (context->Attrs().Get<bool>("is_test") == false) {
88 89 90
      context->SetOutputDim("Dropout2Mask", dim_x);
    }
    framework::DDim mean_dim =
91
        phi::make_ddim({mat_dim_x.batch_size_ * mat_dim_x.height_});
92 93
    bool pre_layer_norm = context->Attrs().Get<bool>("pre_layer_norm");
    if (pre_layer_norm) {
94 95 96
      OP_INOUT_CHECK(context->HasOutput("Ln1Mean"),
                     "Output",
                     "Ln1Mean",
97
                     "fused_feedforward");
98 99 100
      OP_INOUT_CHECK(context->HasOutput("Ln1Variance"),
                     "Output",
                     "Ln1Variance",
101
                     "fused_feedforward");
102 103 104
      OP_INOUT_CHECK(context->HasOutput("Ln1Out"),
                     "Output",
                     "Ln1Out",
105 106 107 108 109
                     "fused_feedforward");
      context->SetOutputDim("Ln1Out", dim_x);
      context->SetOutputDim("Ln1Mean", mean_dim);
      context->SetOutputDim("Ln1Variance", mean_dim);
    } else {
110 111 112
      OP_INOUT_CHECK(context->HasOutput("Ln2Mean"),
                     "Output",
                     "Ln2Mean",
113
                     "fused_feedforward");
114 115 116
      OP_INOUT_CHECK(context->HasOutput("Ln2Variance"),
                     "Output",
                     "Ln2Variance",
117 118 119 120
                     "fused_feedforward");
      context->SetOutputDim("Ln2Mean", mean_dim);
      context->SetOutputDim("Ln2Variance", mean_dim);
    }
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 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 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    context->ShareLoD("X", "Out");
  }

  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "X"), ctx.GetPlace());
  }
};

class FusedFeedForwardOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X", "The input of FusedFeedForward op");
    AddInput(
        "Dropout1Seed",
        "The seed of first dropout op, it has higher priority than the attr "
        "fix_seed and seed")
        .AsDispensable();
    AddInput(
        "Dropout2Seed",
        "The seed of second dropout op, it has higher priority than the attr "
        "fix_seed and seed")
        .AsDispensable();

    AddInput("Linear1Weight", "The linear1 weight of FusedFeedForward op");
    AddInput("Linear1Bias", "The linear1 bias of FusedFeedForward op")
        .AsDispensable();
    AddInput("Linear2Weight", "The linear2 weight of FusedFeedForward op");
    AddInput("Linear2Bias", "The linear2 bias input of FusedFeedForward op")
        .AsDispensable();
    AddInput("Ln1Scale", "The layer_norm1 scale of FusedFeedForward op")
        .AsDispensable();
    AddInput("Ln1Bias", "The layer_norm1 bias of FusedFeedForward op")
        .AsDispensable();
    AddInput("Ln2Scale", "The layer_norm2 scale of FusedFeedForward op")
        .AsDispensable();
    AddInput("Ln2Bias", "The layer_norm2 bias of FusedFeedForward op")
        .AsDispensable();
    AddOutput("Out", "The output of FusedFeedForward op");
    AddOutput("Dropout1Mask", "The mask of dropout1").AsIntermediate();
    AddOutput("Dropout2Mask", "The mask of dropout2").AsIntermediate();
    AddOutput("Ln1Mean", "The mean of layer_norm1").AsIntermediate();
    AddOutput("Ln1Variance", "The variance of layer_norm1").AsIntermediate();
    AddOutput("Ln2Mean", "The mean of layer_nomr2").AsIntermediate();
    AddOutput("Ln2Variance", "The variance of layer_norm2").AsIntermediate();
    AddOutput("Linear1Out", "The output of linear1").AsIntermediate();
    AddOutput("Ln1Out", "The output of layer_norm1").AsIntermediate();
    AddOutput("Dropout1Out", "The output of dropout1").AsIntermediate();
    AddOutput("Dropout2Out", "The output of dropout2").AsIntermediate();

    AddAttr<bool>("pre_layer_norm", "true is pre layernorm").SetDefault(false);
    AddAttr<float>("ln1_epsilon", "epsilon of pre layer_norm")
        .SetDefault(1e-5f);
    AddAttr<float>("ln2_epsilon", "epsilon of post layer_norm")
        .SetDefault(1e-5f);
    AddAttr<std::string>("act_method", "act_method").SetDefault("gelu");
    AddAttr<float>("dropout1_rate", "the dropout rate of first dropout")
        .SetDefault(.5f)
        .AddCustomChecker([](const float &drop_p) {
          PADDLE_ENFORCE_EQ(
182 183
              drop_p >= 0.0f && drop_p <= 1.0f,
              true,
184 185 186 187 188 189 190
              platform::errors::InvalidArgument(
                  "'dropout1_rate' must be between 0.0 and 1.0."));
        });
    AddAttr<float>("dropout2_rate", "the dropout rate of second dropout")
        .SetDefault(.5f)
        .AddCustomChecker([](const float &drop_p) {
          PADDLE_ENFORCE_EQ(
191 192
              drop_p >= 0.0f && drop_p <= 1.0f,
              true,
193 194 195 196 197 198 199 200
              platform::errors::InvalidArgument(
                  "'dropout2_rate' must be between 0.0 and 1.0."));
        });
    AddAttr<std::string>("dropout1_implementation",
                         "the dropout implementation of first dropout")
        .SetDefault("downgrade_in_infer")
        .AddCustomChecker([](const std::string &type) {
          PADDLE_ENFORCE_EQ(
201 202
              type == "downgrade_in_infer" || type == "upscale_in_train",
              true,
203 204 205 206 207 208 209 210 211
              platform::errors::InvalidArgument(
                  "dropout1_implementation can only be downgrade_in_infer or "
                  "upscale_in_train"));
        });
    AddAttr<std::string>("dropout2_implementation",
                         "the dropout implementation of second dropout")
        .SetDefault("downgrade_in_infer")
        .AddCustomChecker([](const std::string &type) {
          PADDLE_ENFORCE_EQ(
212 213
              type == "downgrade_in_infer" || type == "upscale_in_train",
              true,
214 215 216 217
              platform::errors::InvalidArgument(
                  "dropout2_implementation can only be downgrade_in_infer or "
                  "upscale_in_train"));
        });
L
Li Min 已提交
218
    AddAttr<bool>("is_test", "the is_test attribute of dropout")
219 220 221 222 223 224 225
        .SetDefault(false);
    AddAttr<bool>("dropout1_fix_seed", "the is_test of first dropout")
        .SetDefault(false);
    AddAttr<bool>("dropout2_fix_seed", "the is_test of second dropout")
        .SetDefault(false);
    AddAttr<int>("dropout1_seed", "Dropout1 random seed.").SetDefault(0);
    AddAttr<int>("dropout2_seed", "Dropout2 random seed.").SetDefault(0);
226
    AddAttr<bool>("add_residual", "Whether to add residual.").SetDefault(true);
227 228
    AddAttr<int>("ring_id", "ring id for tensor model parallel.")
        .SetDefault(-1);
229
    AddComment(R"DOC(
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
  The fused_feedforward operator is the same as the following pseudo codes:

  residual = src;
  if (pre_layer_norm)
    ln1_out = layer_norm(src);
  else
    ln1_out = src;
  // linear 1
  out = linear(ln1_out);
  out = dropout(activation(out));
  // linear 2
  out = linear(out);
  if (add_residual)
    out = residual + dropout(out);
  else
    out = dropout(out);
  if (!pre_layer_norm)
    out = layer_norm(out);
  )DOC");
249 250 251
  }
};

252 253 254 255 256 257
class FusedFeedForwardOpGrad : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext *ctx) const override {
258 259
    PADDLE_ENFORCE_EQ(ctx->Attrs().Get<bool>("is_test"),
                      false,
260 261
                      platform::errors::InvalidArgument(
                          "GradOp is only callable when is_test is false"));
262
    bool pre_layer_norm = ctx->Attrs().Get<bool>("pre_layer_norm");
263 264 265
    OP_INOUT_CHECK(ctx->HasInput("Dropout1Mask"),
                   "Input",
                   "Dropout1Mask",
266
                   "FusedFeedForwardGrad");
267 268 269
    OP_INOUT_CHECK(ctx->HasInput("Dropout2Mask"),
                   "Input",
                   "Dropout1Mask",
270
                   "FusedFeedForwardGrad");
271 272 273
    OP_INOUT_CHECK(ctx->HasInput("Linear1Out"),
                   "Input",
                   "Linear1Out",
274
                   "FusedFeedForwardGrad");
275 276 277
    OP_INOUT_CHECK(ctx->HasInput("Dropout1Out"),
                   "Input",
                   "Dropout1Out",
278
                   "FusedFeedForwardGrad");
279 280 281 282 283 284
    if (!pre_layer_norm) {
      OP_INOUT_CHECK(ctx->HasInput("Dropout2Out"),
                     "Input",
                     "Dropout2Out",
                     "FusedFeedForwardGrad");
    }
285 286 287
    OP_INOUT_CHECK(ctx->HasInput("Linear1Weight"),
                   "Input",
                   "Linear1Weight",
288
                   "FusedFeedForwardGrad");
289 290 291
    OP_INOUT_CHECK(ctx->HasInput("Linear2Weight"),
                   "Input",
                   "Linear2Weight",
292
                   "FusedFeedForwardGrad");
293
    if (pre_layer_norm) {
294 295 296 297 298
      OP_INOUT_CHECK(
          ctx->HasInput("Ln1Mean"), "Input", "Ln1Mean", "FusedFeedForwardGrad");
      OP_INOUT_CHECK(ctx->HasInput("Ln1Variance"),
                     "Input",
                     "Ln1Variance",
299
                     "FusedFeedForwardGrad");
300 301
      OP_INOUT_CHECK(
          ctx->HasInput("Ln1Out"), "Input", "Ln1Out", "FusedFeedForwardGrad");
302
    } else {
303 304 305 306 307
      OP_INOUT_CHECK(
          ctx->HasInput("Ln2Mean"), "Input", "Ln2Mean", "FusedFeedForwardGrad");
      OP_INOUT_CHECK(ctx->HasInput("Ln2Variance"),
                     "Input",
                     "Ln2Variance",
308 309
                     "FusedFeedForwardGrad");
    }
310

311 312 313 314
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Out")),
                   "Input",
                   framework::GradVarName("Out"),
                   "FusedFeedForwardGrad");
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350

    auto d_out_dim = ctx->GetInputDim(framework::GradVarName("Out"));
    ctx->SetOutputDim(framework::GradVarName("X"), d_out_dim);
    if (ctx->HasOutput(framework::GradVarName("Ln1Scale"))) {
      ctx->SetOutputDim(framework::GradVarName("Ln1Scale"),
                        ctx->GetInputDim("Ln1Scale"));
    }
    if (ctx->HasOutput(framework::GradVarName("Ln1Bias"))) {
      ctx->SetOutputDim(framework::GradVarName("Ln1Bias"),
                        ctx->GetInputDim("Ln1Bias"));
    }
    if (ctx->HasOutput(framework::GradVarName("Ln2Scale"))) {
      ctx->SetOutputDim(framework::GradVarName("Ln2Scale"),
                        ctx->GetInputDim("Ln2Scale"));
    }
    if (ctx->HasOutput(framework::GradVarName("Ln2Bias"))) {
      ctx->SetOutputDim(framework::GradVarName("Ln2Bias"),
                        ctx->GetInputDim("Ln2Bias"));
    }
    ctx->SetOutputDim(framework::GradVarName("Linear1Weight"),
                      ctx->GetInputDim("Linear1Weight"));
    if (ctx->HasOutput(framework::GradVarName("Linear1Bias"))) {
      ctx->SetOutputDim(framework::GradVarName("Linear1Bias"),
                        ctx->GetInputDim("Linear1Bias"));
    }
    ctx->SetOutputDim(framework::GradVarName("Linear2Weight"),
                      ctx->GetInputDim("Linear2Weight"));
    if (ctx->HasOutput(framework::GradVarName("Linear2Bias"))) {
      ctx->SetOutputDim(framework::GradVarName("Linear2Bias"),
                        ctx->GetInputDim("Linear2Bias"));
    }
  }

  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext &ctx) const override {
    auto input = ctx.Input<Tensor>("X");
351
    auto input_data_type = framework::TransToProtoVarType(input->dtype());
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
  }
};

template <typename T>
class FusedFeedForwardOpGradMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> op) const override {
    op->SetType("fused_feedforward_grad");
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
    op->SetInput("X", this->Input("X"));
    op->SetInput("Linear1Weight", this->Input("Linear1Weight"));
    op->SetInput("Linear1Bias", this->Input("Linear1Bias"));
    op->SetInput("Linear2Weight", this->Input("Linear2Weight"));
    op->SetInput("Dropout1Mask", this->Output("Dropout1Mask"));
    op->SetInput("Dropout2Mask", this->Output("Dropout2Mask"));
    op->SetInput("Linear1Out", this->Output("Linear1Out"));
    op->SetInput("Dropout1Out", this->Output("Dropout1Out"));

374
    op->SetAttrMap(this->Attrs());
R
Ruibiao Chen 已提交
375
    bool pre_layer_norm = PADDLE_GET_CONST(bool, op->GetAttr("pre_layer_norm"));
376 377 378
    if (!pre_layer_norm) {
      op->SetInput("Dropout2Out", this->Output("Dropout2Out"));
    }
379

380
    op->SetOutput(framework::GradVarName("X"), this->InputGrad("X"));
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    if (pre_layer_norm) {
      op->SetInput("Ln1Scale", this->Input("Ln1Scale"));
      op->SetInput("Ln1Bias", this->Input("Ln1Bias"));
      op->SetInput("Ln1Out", this->Output("Ln1Out"));
      op->SetInput("Ln1Mean", this->Output("Ln1Mean"));
      op->SetInput("Ln1Variance", this->Output("Ln1Variance"));
      op->SetOutput(framework::GradVarName("Ln1Scale"),
                    this->InputGrad("Ln1Scale"));
      op->SetOutput(framework::GradVarName("Ln1Bias"),
                    this->InputGrad("Ln1Bias"));
    } else {
      op->SetInput("Ln2Scale", this->Input("Ln2Scale"));
      op->SetInput("Ln2Bias", this->Input("Ln2Bias"));
      op->SetInput("Ln2Mean", this->Output("Ln2Mean"));
      op->SetInput("Ln2Variance", this->Output("Ln2Variance"));
      op->SetOutput(framework::GradVarName("Ln2Scale"),
                    this->InputGrad("Ln2Scale"));
      op->SetOutput(framework::GradVarName("Ln2Bias"),
                    this->InputGrad("Ln2Bias"));
    }
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    op->SetOutput(framework::GradVarName("Linear1Weight"),
                  this->InputGrad("Linear1Weight"));
    op->SetOutput(framework::GradVarName("Linear1Bias"),
                  this->InputGrad("Linear1Bias"));
    op->SetOutput(framework::GradVarName("Linear2Weight"),
                  this->InputGrad("Linear2Weight"));
    if (this->HasInput("Linear2Bias")) {
      op->SetInput("Linear2Bias", this->Input("Linear2Bias"));
      op->SetOutput(framework::GradVarName("Linear2Bias"),
                    this->InputGrad("Linear2Bias"));
    }
  }
};

template <typename T>
class FusedFeedForwardOpDoubleGradMaker
    : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
  void Apply(GradOpPtr<T> grad_op) const override {}
};
424 425 426 427
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
428 429
REGISTER_OPERATOR(fused_feedforward,
                  ops::FusedFeedForwardOp,
430 431 432 433
                  ops::FusedFeedForwardOpMaker,
                  ops::FusedFeedForwardOpGradMaker<paddle::framework::OpDesc>,
                  ops::FusedFeedForwardOpGradMaker<paddle::imperative::OpBase>);
REGISTER_OPERATOR(fused_feedforward_grad, ops::FusedFeedForwardOpGrad);
434 435 436 437 438 439

REGISTER_OP_VERSION(fused_feedforward)
    .AddCheckpoint(
        R"ROC(
              Add a new attribute [add_residual] )ROC",
        paddle::framework::compatible::OpVersionDesc().NewAttr(
440 441
            "add_residual",
            "A flag to indicate whether to add residual.",
442
            true));