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

15
#include <sstream>
16
#include <vector>
17

18
#include "paddle/fluid/framework/op_registry.h"
19
#include "paddle/fluid/framework/op_version_registry.h"
20 21
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/var_type.h"
22
#include "paddle/phi/backends/device_memory_aligment.h"
23
#include "paddle/phi/kernels/funcs/math_function.h"
24

25
#include "paddle/fluid/framework/convert_utils.h"
26 27
#include "paddle/fluid/framework/infershape_utils.h"
#include "paddle/phi/infermeta/multiary.h"
28 29 30 31

namespace paddle {
namespace operators {

32 33 34
template <typename DeviceContext>
struct FillConstantVisitor {
  FillConstantVisitor(const DeviceContext &dev_ctx,
35
                      phi::DenseTensor *tensor,
36
                      const float value,
37 38 39 40 41 42 43
                      framework::proto::VarType::Type dtype,
                      const framework::ExecutionContext &context)
      : dev_ctx_(dev_ctx),
        tensor_(tensor),
        value_(value),
        dtype_(dtype),
        context_(context) {}
44 45 46 47 48 49 50 51 52 53 54 55 56

  template <typename T>
  void apply(typename std::enable_if<std::is_same<T, int8_t>::value ||
                                     std::is_same<T, int16_t>::value>::type * =
                 nullptr) const {
    PADDLE_THROW(platform::errors::InvalidArgument(
        "Not support data type for set_constant attr"));
  }

  template <typename T>
  void apply(typename std::enable_if<!(std::is_same<T, int8_t>::value ||
                                       std::is_same<T, int16_t>::value)>::type
                 * = nullptr) const {
57
    phi::funcs::SetConstant<DeviceContext, T> set_constant;
58 59 60 61
    set_constant(dev_ctx_, tensor_, static_cast<T>(value_));
  }

  const DeviceContext &dev_ctx_;
62
  phi::DenseTensor *tensor_;
63
  float value_;
64 65
  framework::proto::VarType::Type dtype_;
  const framework::ExecutionContext &context_;
66 67
};

68
template <typename DeviceContext, typename T>
69
class CoalesceTensorOpKernel : public framework::OpKernel<T> {
70 71
 public:
  void Compute(const framework::ExecutionContext &context) const override {
H
hong 已提交
72 73
    auto in_var_names = context.InputNames("Input");
    auto out_var_names = context.OutputNames("Output");
74 75
    const auto &in_tensors = context.MultiInput<phi::DenseTensor>("Input");
    auto out_tensors = context.MultiOutput<phi::DenseTensor>("Output");
76

77 78
    PADDLE_ENFORCE_GT(in_var_names.size(),
                      static_cast<size_t>(0),
79 80
                      platform::errors::InvalidArgument(
                          "The CoalesceTensor operator has no input."));
81 82
    PADDLE_ENFORCE_EQ(in_var_names.size(),
                      out_var_names.size(),
83 84 85 86
                      platform::errors::InvalidArgument(
                          "The number of CoalesceTensor operator's input and "
                          "output is not match, "
                          "input number is %u, output number is %u.",
87 88
                          in_var_names.size(),
                          out_var_names.size()));
89

90
    // Input & Output check: only support phi::DenseTensor
91 92
    bool has_not_init_in_vars = false;
    for (size_t i = 0; i < in_tensors.size(); ++i) {
93
      PADDLE_ENFORCE_NOT_NULL(
94 95 96
          in_tensors[i],
          platform::errors::InvalidArgument(
              "The %d-th input tensor cannot be nullptr.", i));
97
      PADDLE_ENFORCE_NOT_NULL(
98 99 100
          out_tensors[i],
          platform::errors::InvalidArgument(
              "The %d-th output tensor cannot be nullptr.", i));
101 102 103 104 105 106 107 108 109 110
      if (!in_tensors[i]->IsInitialized()) {
        has_not_init_in_vars = true;
      }
    }

    if (has_not_init_in_vars) {
      const auto &concated_shapes =
          context.Attr<std::vector<int64_t>>("concated_shapes");
      const auto &concated_ranks =
          context.Attr<std::vector<int64_t>>("concated_ranks");
111 112
      PADDLE_ENFORCE_EQ(concated_ranks.size(),
                        out_tensors.size(),
113
                        platform::errors::InvalidArgument(
114 115 116 117 118 119 120 121
                            "The attribute(concated_ranks) length must be "
                            "equal to the output tensor number."));
      int64_t accumulated_ranks = 0;
      for (size_t i = 0; i < in_tensors.size(); ++i) {
        framework::DDim dims(concated_shapes.data() + accumulated_ranks,
                             concated_ranks[i]);
        if (!in_tensors[i]->IsInitialized()) {
          PADDLE_ENFORCE_EQ(
122 123
              in_tensors[i],
              out_tensors[i],
124 125 126
              platform::errors::InvalidArgument(
                  "The %d-th output tensor and %d-th input tensor when the "
                  "%d-th input tensor is not initialized.",
127 128 129
                  i,
                  i,
                  i));
130 131 132
          out_tensors[i]->Resize(dims);
        } else {
          PADDLE_ENFORCE_EQ(
133 134
              in_tensors[i]->dims(),
              dims,
135 136 137 138 139 140 141
              platform::errors::InvalidArgument(
                  "The %d-th input tensor shape does not match the "
                  "attribute(concated_shapes) and "
                  "attribute(concated_ranks).",
                  i));
        }
        accumulated_ranks += concated_ranks[i];
142 143
        PADDLE_ENFORCE_LE(accumulated_ranks,
                          concated_shapes.size(),
144 145 146 147
                          platform::errors::InvalidArgument(
                              "The attribute(concated_shapes) and "
                              "attribute(concated_ranks) do not match."));
      }
148 149
      PADDLE_ENFORCE_EQ(accumulated_ranks,
                        concated_shapes.size(),
150
                        platform::errors::InvalidArgument(
151 152
                            "The attribute(concated_shapes) and "
                            "attribute(concated_ranks) do not match."));
153 154
    }

155
    bool use_align = context.Attr<bool>("use_align");
156
    auto align_size = context.Attr<int>("align_size");
157
    auto size_of_dtype = context.Attr<int>("user_defined_size_of_dtype");
158 159 160

    if (context.Attr<bool>("check_name")) {
      for (size_t i = 0; i < in_var_names.size(); ++i) {
161
        PADDLE_ENFORCE_EQ(
162 163
            in_var_names[i],
            out_var_names[i],
164 165 166
            platform::errors::InvalidArgument(
                "The input and output variable of CoalesceTensor operator is "
                "different, %dth input is %s, %dth output is %s.",
167 168 169 170
                i,
                in_var_names[i],
                i,
                out_var_names[i]));
171 172 173 174
      }
    } else {
      // Init the output as input
      for (size_t i = 0; i < in_tensors.size(); ++i) {
175
        out_tensors[i]->Resize(in_tensors[i]->dims());
176 177 178 179 180 181 182
      }
    }

    auto &dev_ctx = context.template device_context<DeviceContext>();

    // Get numel and dtype
    size_t numel = 0;
183 184
    auto dtype = static_cast<framework::proto::VarType::Type>(
        context.Attr<int>("dtype"));
185 186 187
    if (size_of_dtype == -1) {
      size_of_dtype = framework::SizeOfType(dtype);
    }
188 189 190 191 192 193 194
    GetMemSizeAndDtype(in_tensors,
                       in_var_names,
                       &numel,
                       size_of_dtype,
                       context.GetPlace(),
                       use_align,
                       align_size);
195 196

    // Alloc the continuous space
197
    auto fused_tensor = context.Output<phi::DenseTensor>("FusedOutput");
198
    void *fused_tensor_ptr =
199
        fused_tensor->Resize(phi::make_ddim({static_cast<int64_t>(numel)}))
200
            .mutable_data(context.GetPlace(),
201
                          framework::TransToPhiDataType(dtype));
202
    VLOG(10) << "Fused tensor addr " << fused_tensor_ptr;
203 204

    // Init the continuous space
C
chengduo 已提交
205
    size_t offset = 0;
206 207
    if (context.Attr<bool>("copy_data")) {
      for (size_t i = 0; i < in_var_names.size(); ++i) {
C
chengduo 已提交
208 209 210
        size_t len = static_cast<size_t>(in_tensors[i]->numel());
        auto sub_tensor = fused_tensor->Slice(
            static_cast<int64_t>(offset), static_cast<int64_t>(offset + len));
211 212 213
        framework::TensorCopy(
            *in_tensors[i], context.GetPlace(), dev_ctx, &sub_tensor);

214 215 216
        offset += use_align ? phi::Alignment(len * size_of_dtype,
                                             context.GetPlace(),
                                             align_size) /
217 218
                                  size_of_dtype
                            : len;
219 220
      }
    } else if (context.Attr<bool>("set_constant")) {
221
      framework::VisitDataType(
222 223 224 225 226 227
          dtype,
          FillConstantVisitor<DeviceContext>(dev_ctx,
                                             fused_tensor,
                                             context.Attr<float>("constant"),
                                             dtype,
                                             context));
228 229 230 231 232 233 234
    } else if (context.Attr<bool>("persist_output")) {
      for (size_t i = 0; i < out_var_names.size(); ++i) {
        size_t len = static_cast<size_t>(out_tensors[i]->numel());
        auto sub_tensor = fused_tensor->Slice(
            static_cast<int64_t>(offset), static_cast<int64_t>(offset + len));
        // some var may not persistable, or persistable var may not init
        if (out_tensors[i]->IsInitialized()) {
235 236
          framework::TensorCopy(
              *out_tensors[i], context.GetPlace(), dev_ctx, &sub_tensor);
237
        }
238 239 240
        offset += use_align ? phi::Alignment(len * size_of_dtype,
                                             context.GetPlace(),
                                             align_size) /
241 242
                                  size_of_dtype
                            : len;
243
      }
244 245 246 247
    }

    // Make the outputs point to the continuous space.
    offset = 0;
248 249
    std::stringstream ss;
    ss << "alloc_space_for_vars: ";
250

251
    for (size_t i = 0; i < out_tensors.size(); ++i) {
C
chengduo 已提交
252
      size_t len = static_cast<size_t>(out_tensors[i]->numel());
253
      auto dim = out_tensors[i]->dims();
254
      VLOG(4) << len << " " << dim << " " << offset;
255
      out_tensors[i]
C
chengduo 已提交
256 257
          ->ShareDataWith(fused_tensor->Slice(
              static_cast<int64_t>(offset), static_cast<int64_t>(offset + len)))
258
          .Resize(dim);
259
      len = use_align
260
                ? phi::Alignment(
261 262 263
                      len * size_of_dtype, context.GetPlace(), align_size) /
                      size_of_dtype
                : len;
264
      ss << "output(" << out_var_names[i] << ")  dim:(" << dim << ")"
265
         << " address: " << out_tensors[i]->data() << " len: " << len << ", ";
266
      offset += len;
267
    }
268
    PADDLE_ENFORCE_EQ(
269 270
        (int64_t)offset,
        fused_tensor->numel(),
271 272 273
        platform::errors::InvalidArgument(
            "The alloc_space_for_vars's offset: %s is unequal with "
            "fused_tensor's numel: %s.",
274 275
            offset,
            fused_tensor->numel()));
276
    VLOG(10) << ss.str();
277 278
  }

C
chengduo 已提交
279
 private:
280
  void GetMemSizeAndDtype(
281
      const std::vector<const phi::DenseTensor *> &lod_tensors,
282 283 284 285 286 287
      const std::vector<std::string> var_names,
      size_t *numel,
      const size_t &size_of_dtype,
      const platform::Place &place,
      const bool use_align = true,
      const int align_size = -1) const {
288
    PADDLE_ENFORCE_EQ(
289 290
        lod_tensors.size(),
        var_names.size(),
291 292 293
        platform::errors::InvalidArgument(
            "The number of input tensor and variable does not match, the "
            "number of input tensor is %u, the number of input variable is %u.",
294 295
            lod_tensors.size(),
            var_names.size()));
296
    *numel = 0;
297 298
    std::stringstream ss;
    ss << "alloc_space_for_vars: ";
299 300
    for (size_t i = 0; i < var_names.size(); ++i) {
      auto size = lod_tensors[i]->numel();
301
      PADDLE_ENFORCE_GT(
302 303
          size,
          0,
304 305
          platform::errors::InvalidArgument(
              "The number of tensor `%s`'s elements is 0.", var_names[i]));
306 307 308 309 310 311
      auto len = use_align
                     ? phi::Alignment(static_cast<size_t>(size) * size_of_dtype,
                                      place,
                                      align_size) /
                           size_of_dtype
                     : static_cast<size_t>(size);
312 313
      const void *ptr =
          lod_tensors[i]->IsInitialized() ? lod_tensors[i]->data() : nullptr;
314
      VLOG(4) << size << " " << len;
315
      ss << "input(" << var_names[i] << ") dim:(" << lod_tensors[i]->dims()
316
         << ") "
317
         << " addres:" << ptr << " len: " << len << ", ";
318
      *numel += len;
319
    }
320
    VLOG(10) << ss.str();
321 322 323
  }
};

324
class CoalesceTensorOp : public framework::OperatorWithKernel {
325 326 327
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

328 329 330
  void InferShape(framework::InferShapeContext *ctx) const override {
    auto use_align = ctx->Attrs().Get<bool>("use_align");
    auto align_size = ctx->Attrs().Get<int>("align_size");
331
    auto size_of_dtype = ctx->Attrs().Get<int>("user_defined_size_of_dtype");
332 333 334

    auto dtype = static_cast<framework::proto::VarType::Type>(
        ctx->Attrs().Get<int>("dtype"));
335 336 337
    if (size_of_dtype == -1) {
      size_of_dtype = framework::SizeOfType(dtype);
    }
P
pangengzheng 已提交
338 339
    if (ctx->IsRuntime()) {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
340 341 342
      int64_t numel = 0;
      auto dims = ctx->GetInputsDim("Input");
      for (const auto &dim : dims) {
343
        auto size = phi::product(dim);
P
pangengzheng 已提交
344 345 346
        auto len = use_align ? phi::Alignment(
                                   static_cast<size_t>(size) * size_of_dtype,
                                   phi::GPUPlace(),
347
                                   align_size) /
P
pangengzheng 已提交
348 349
                                   size_of_dtype
                             : static_cast<size_t>(size);
350 351
        numel += len;
      }
352 353
      ctx->SetOutputDim("FusedOutput", phi::make_ddim({numel}));
      VLOG(4) << "FusedOutput size:" << phi::make_ddim({numel});
P
pangengzheng 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
#else
      return;
#endif
    } else {
      auto alignment = [](size_t size, size_t align_size) {
        size_t remaining = size % align_size;
        auto aligned_size =
            remaining == 0 ? size : size + (align_size - remaining);
        VLOG(4) << remaining << " " << size << " " << align_size << " "
                << aligned_size;
        return aligned_size;
      };
      VLOG(4) << "align_size: " << align_size;
      if (use_align && align_size > 0) {
        int64_t numel = 0;
        auto dims = ctx->GetInputsDim("Input");
        for (const auto &dim : dims) {
          auto size = phi::product(dim);
          auto len = use_align
                         ? alignment(static_cast<size_t>(size) * size_of_dtype,
                                     align_size) /
                               size_of_dtype
                         : static_cast<size_t>(size);
          numel += len;
        }
        ctx->SetOutputDim("FusedOutput", phi::make_ddim({numel}));
        VLOG(4) << "FusedOutput size:" << phi::make_ddim({numel});
      }
382 383
    }
  }
384 385

 protected:
386
  phi::KernelKey GetExpectedKernelType(
387 388 389
      const framework::ExecutionContext &context) const override {
    auto dtype = static_cast<framework::proto::VarType::Type>(
        context.Attr<int>("dtype"));
390
    return phi::KernelKey(dtype, context.GetPlace());
391 392
  }

393
  phi::KernelKey GetKernelTypeForVar(
394
      const std::string &var_name,
395
      const phi::DenseTensor &tensor,
396 397 398 399
      const phi::KernelKey &expected_kernel_type) const override {
    return phi::KernelKey(phi::Backend::ALL_BACKEND,
                          tensor.layout(),
                          expected_kernel_type.dtype());
400
  }
401 402
};

403
class CoalesceTensorOpMaker : public framework::OpProtoAndCheckerMaker {
404 405 406
 public:
  void Make() override {
    AddInput("Input",
407
             "(vector<phi::DenseTensor>) The input tensors of"
408
             " coalesce_tensor operator.")
409 410
        .AsDuplicable();
    AddOutput("Output",
411
              "(vector<phi::DenseTensor>) The output "
412
              "tensors of coalesce_tensor operator. And the address "
413 414 415 416
              "of output tensors are continuous, they are sliced from the "
              "tensor of FusedOutput.")
        .AsDuplicable();
    AddOutput("FusedOutput",
417
              "(phi::DenseTensor) The output tensor "
418
              "of coalesce_tensor operator. And the tensors of"
419
              " Output is sliced from the tensor of FusedOutput.");
420
    AddAttr<int>("dtype", "The output data type.");
421 422 423 424 425
    AddAttr<bool>("copy_data", "Whether to copy the Input value to Output.")
        .SetDefault(false);
    AddAttr<bool>("set_constant",
                  "Whether to set the Output with a constant value.")
        .SetDefault(false);
426 427 428
    AddAttr<bool>("persist_output",
                  "Whether to persist the original Output value.")
        .SetDefault(false);
429 430 431 432 433 434 435 436
    AddAttr<float>("constant",
                   "If set_constant is true, the constant value will be used "
                   "to set the Output.")
        .SetDefault(0.0);
    AddAttr<bool>("check_name",
                  "Whether to check the name of Input and Output to ensure "
                  "they are the same separately.")
        .SetDefault(false);
437 438 439 440
    AddAttr<bool>("use_align",
                  "Whether to consider memory chunk and take alignment into "
                  "account for inputs and outputs.")
        .SetDefault(true);
441 442
    AddAttr<int>("align_size", "The alignment size when use_align is True")
        .SetDefault(-1);
443 444 445 446 447 448 449 450 451
    AddAttr<int>("user_defined_size_of_dtype",
                 "The user defined size of dtype. This is used to coalesce "
                 "grad vars and merged_grad vars at the same time. For some "
                 "strategy, the dtype of fused_grad_vars and the dtype of "
                 "fused_grad_merged_vars are not identical, which will cause "
                 "the shape of these two coalesced vars are different. To "
                 "make sure the shape of these two vars are identical with "
                 "each other, this attr is added.")
        .SetDefault(-1);
452 453 454 455 456 457 458 459 460 461 462 463 464 465
    AddAttr<std::vector<int64_t>>(
        "concated_shapes",
        "The concated shapes of each shape of the input tensors. "
        "If any of the input tensors are not inited, this is used to "
        "init the output tensor shape, together with "
        "attribute(concated_ranks).")
        .SetDefault({});
    AddAttr<std::vector<int64_t>>(
        "concated_ranks",
        "The concated ranks of each rank of the input tensors. "
        "If any of the input tensors are not inited, this is used to "
        "init the output tensor shape, together with "
        "attribute(concated_shapes).")
        .SetDefault({});
466
    AddComment(R"DOC(
467
CoalesceTensor Operator.
468

469
coalesce_tensor is used to make the address of Output
470 471 472 473 474 475 476 477
continuous according to the Input. This Op will alloc a big tensor
according to the tensors of Input, the dtype is the same with those input tensors,
the size is the sum of those input tensors' numel, and the dim of the big
tensor is {sum(numel)}. And the big tensor is stored in FusedOutput.
The tensors of Output are sliced from the tensor of FusedOutput.
Note that, the dtype of Input should be the same, and the dim of Input
and Output should equal.
The tensors of Input and Output could be the same or different. And
478
coalesce_tensor allows copying the value of Input to Output, or
479 480
setting the Output with a constant value, or persist the original Output
value.
481 482 483 484 485 486 487 488

)DOC");
  }
};

}  // namespace operators
}  // namespace paddle

489 490 491 492
DECLARE_INFER_SHAPE_FUNCTOR(coalesce_tensor,
                            CoalesceTensorInferShapeFunctor,
                            PD_INFER_META(phi::CoalesceTensorInferMeta));

493 494
REGISTER_OPERATOR(coalesce_tensor,
                  paddle::operators::CoalesceTensorOp,
495 496
                  paddle::operators::CoalesceTensorOpMaker,
                  CoalesceTensorInferShapeFunctor);
497
namespace ops = paddle::operators;
498
namespace plat = paddle::platform;
499 500 501 502 503 504 505 506 507 508

REGISTER_OP_VERSION(coalesce_tensor)
    .AddCheckpoint(
        R"ROC(
              Upgrade coalesce_tensor: add a new attribute [use_align].)ROC",
        paddle::framework::compatible::OpVersionDesc().NewAttr(
            "use_align",
            "In order to optionally take memory alignment into account when "
            "coalescing tensors. The default value is true to be compatible "
            "with before.",
509 510 511 512 513 514 515 516 517 518 519
            true))
    .AddCheckpoint(
        R"ROC(
                Upgrade coalesce_tensor: add a new attribute [align_size].)ROC",
        paddle::framework::compatible::OpVersionDesc().NewAttr(
            "align_size",
            "In order to optionally take memory alignment into account when "
            "coalescing tensors. The default value is -1 and use the default "
            "align_size "
            "of each place to be compatible with before.",
            -1));