coalesce_tensor_op.cc 16.9 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 17
#include <vector>
#include "paddle/fluid/framework/op_registry.h"
18
#include "paddle/fluid/framework/op_version_registry.h"
19 20 21
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/var_type.h"
#include "paddle/fluid/operators/math/math_function.h"
22
#include "paddle/fluid/platform/device_memory_aligment.h"
23 24 25 26 27

namespace paddle {
namespace operators {

template <typename DeviceContext, typename T>
28
class CoalesceTensorOpKernel : public framework::OpKernel<T> {
29 30
 public:
  void Compute(const framework::ExecutionContext &context) const override {
H
hong 已提交
31 32
    auto in_var_names = context.InputNames("Input");
    auto out_var_names = context.OutputNames("Output");
33 34 35
    auto &in_vars = context.MultiInputVar("Input");
    auto out_vars = context.MultiOutputVar("Output");

36
    PADDLE_ENFORCE_GT(in_var_names.size(), static_cast<size_t>(0),
37 38 39 40 41 42 43 44
                      platform::errors::InvalidArgument(
                          "The CoalesceTensor operator has no input."));
    PADDLE_ENFORCE_EQ(in_var_names.size(), out_var_names.size(),
                      platform::errors::InvalidArgument(
                          "The number of CoalesceTensor operator's input and "
                          "output is not match, "
                          "input number is %u, output number is %u.",
                          in_var_names.size(), out_var_names.size()));
45

46
    // Input & Output check: only support LoDTensor
47
    for (size_t i = 0; i < in_var_names.size(); ++i) {
48 49
      PADDLE_ENFORCE_NOT_NULL(
          in_vars[i],
50 51 52
          platform::errors::NotFound("The input variable %s of CoalesceTensor "
                                     "operator does not exist.",
                                     in_var_names[i]));
53 54
      PADDLE_ENFORCE_NOT_NULL(
          out_vars[i],
55 56 57 58 59 60 61 62 63 64 65 66
          platform::errors::NotFound("The output variable %s of CoalesceTensor "
                                     "operator does not exist.",
                                     out_var_names[i]));
      PADDLE_ENFORCE_EQ(in_vars[i]->IsType<framework::LoDTensor>(), true,
                        platform::errors::InvalidArgument(
                            "The input variable %s of CoalesceTensor operator "
                            "is not LoDTensor.",
                            in_var_names[i]));
      PADDLE_ENFORCE_EQ(out_vars[i]->IsType<framework::LoDTensor>(), true,
                        platform::errors::InvalidArgument(
                            "The output variable %s of CoalesceTensor operator "
                            "is not LoDTensor.",
67
                            out_var_names[i]));
68 69 70
    }

    auto in_tensors = context.MultiInput<framework::LoDTensor>("Input");
71
    bool use_align = context.Attr<bool>("use_align");
72
    auto align_size = context.Attr<int>("align_size");
73 74 75

    if (context.Attr<bool>("check_name")) {
      for (size_t i = 0; i < in_var_names.size(); ++i) {
76 77
        PADDLE_ENFORCE_EQ(
            in_var_names[i], out_var_names[i],
78 79 80 81
            platform::errors::InvalidArgument(
                "The input and output variable of CoalesceTensor operator is "
                "different, %dth input is %s, %dth output is %s.",
                i, in_var_names[i], i, out_var_names[i]));
82 83 84 85 86 87 88 89 90 91 92 93 94
      }
    } else {
      // Init the output as input
      for (size_t i = 0; i < in_tensors.size(); ++i) {
        out_vars[i]->GetMutable<framework::LoDTensor>()->Resize(
            in_tensors[i]->dims());
      }
    }

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

    // Get numel and dtype
    size_t numel = 0;
95 96 97 98
    auto dtype = static_cast<framework::proto::VarType::Type>(
        context.Attr<int>("dtype"));
    size_t size_of_dtype = framework::SizeOfType(dtype);
    GetMemSizeAndDtype(in_tensors, in_var_names, &numel, size_of_dtype,
99
                       context.GetPlace(), use_align, align_size);
100 101 102 103 104 105 106 107

    // Alloc the continuous space
    auto fused_tensor = context.Output<framework::LoDTensor>("FusedOutput");
    fused_tensor->Resize(framework::make_ddim({static_cast<int64_t>(numel)}))
        .mutable_data(context.GetPlace(), dtype);

    // Init the continuous space
    auto out_tensors = context.MultiOutput<framework::LoDTensor>("Output");
C
chengduo 已提交
108
    size_t offset = 0;
109 110
    if (context.Attr<bool>("copy_data")) {
      for (size_t i = 0; i < in_var_names.size(); ++i) {
C
chengduo 已提交
111 112 113 114
        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));
        framework::TensorCopy(*in_tensors[i], context.GetPlace(), dev_ctx,
115
                              &sub_tensor);
C
chengduo 已提交
116

117 118 119 120 121
        offset += use_align
                      ? platform::Alignment(len * size_of_dtype,
                                            context.GetPlace(), align_size) /
                            size_of_dtype
                      : len;
122 123
      }
    } else if (context.Attr<bool>("set_constant")) {
124
      // TODO(Liu yuang) ADD NPU SET_CONSTANT FUNCTION.
125 126 127
      math::SetConstant<DeviceContext, T> set_constant;
      set_constant(dev_ctx, fused_tensor,
                   static_cast<T>(context.Attr<float>("constant")));
128 129 130 131 132 133 134 135 136 137
    } 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()) {
          framework::TensorCopy(*out_tensors[i], context.GetPlace(), dev_ctx,
                                &sub_tensor);
        }
138 139 140 141 142
        offset += use_align
                      ? platform::Alignment(len * size_of_dtype,
                                            context.GetPlace(), align_size) /
                            size_of_dtype
                      : len;
143
      }
144 145 146 147
    }

    // Make the outputs point to the continuous space.
    offset = 0;
148 149
    std::stringstream ss;
    ss << "alloc_space_for_vars: ";
150

151
    for (size_t i = 0; i < out_tensors.size(); ++i) {
C
chengduo 已提交
152
      size_t len = static_cast<size_t>(out_tensors[i]->numel());
153
      auto dim = out_tensors[i]->dims();
154
      VLOG(4) << len << " " << dim << " " << offset;
155
      out_tensors[i]
C
chengduo 已提交
156 157
          ->ShareDataWith(fused_tensor->Slice(
              static_cast<int64_t>(offset), static_cast<int64_t>(offset + len)))
158
          .Resize(dim);
159
      len = use_align
160 161
                ? platform::Alignment(len * size_of_dtype, context.GetPlace(),
                                      align_size) /
162 163
                      size_of_dtype
                : len;
164
      ss << "output(" << out_var_names[i] << ")  dim:(" << dim << ")"
165 166 167
         << " address: " << out_tensors[i]->data<void>() << " len: " << len
         << ", ";
      offset += len;
168
    }
169 170 171 172 173 174
    PADDLE_ENFORCE_EQ(
        (int64_t)offset, fused_tensor->numel(),
        platform::errors::InvalidArgument(
            "The alloc_space_for_vars's offset: %s is unequal with "
            "fused_tensor's numel: %s.",
            offset, fused_tensor->numel()));
175
    VLOG(10) << ss.str();
176 177
  }

C
chengduo 已提交
178
 private:
179 180 181
  void GetMemSizeAndDtype(
      const std::vector<const framework::LoDTensor *> &lod_tensors,
      const std::vector<std::string> var_names, size_t *numel,
182
      const size_t &size_of_dtype, const platform::Place &place,
183
      const bool use_align = true, const int align_size = -1) const {
184 185 186 187 188 189
    PADDLE_ENFORCE_EQ(
        lod_tensors.size(), var_names.size(),
        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.",
            lod_tensors.size(), var_names.size()));
190
    *numel = 0;
191 192
    std::stringstream ss;
    ss << "alloc_space_for_vars: ";
193
    for (size_t i = 0; i < var_names.size(); ++i) {
194
      PADDLE_ENFORCE_EQ(lod_tensors[i]->IsInitialized(), true,
195 196
                        platform::errors::InvalidArgument(
                            "Tensor `%s` is not initialized.", var_names[i]));
197 198

      auto size = lod_tensors[i]->numel();
199 200 201 202
      PADDLE_ENFORCE_GT(
          size, 0,
          platform::errors::InvalidArgument(
              "The number of tensor `%s`'s elements is 0.", var_names[i]));
203 204 205 206 207 208 209
      auto len =
          use_align
              ? platform::Alignment(static_cast<size_t>(size) * size_of_dtype,
                                    place, align_size) /
                    size_of_dtype
              : static_cast<size_t>(size);
      VLOG(4) << size << " " << len;
210
      ss << "input(" << var_names[i] << ") dim:(" << lod_tensors[i]->dims()
211
         << ") "
212 213 214
         << " addres:" << lod_tensors[i]->data<void>() << " len: " << len
         << ", ";
      *numel += len;
215
    }
216
    VLOG(10) << ss.str();
217 218 219
  }
};

220
class CoalesceTensorOp : public framework::OperatorWithKernel {
221 222 223
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
  void InferShape(framework::InferShapeContext *ctx) const override {
    if (ctx->IsRuntime()) {
      return;
    }
    auto use_align = ctx->Attrs().Get<bool>("use_align");
    auto align_size = ctx->Attrs().Get<int>("align_size");

    auto dtype = static_cast<framework::proto::VarType::Type>(
        ctx->Attrs().Get<int>("dtype"));
    size_t size_of_dtype = framework::SizeOfType(dtype);

    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 = framework::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", framework::make_ddim({numel}));
      VLOG(4) << "FusedOutput size:" << framework::make_ddim({numel});
    }
  }
260 261 262 263 264 265 266 267 268

 protected:
  framework::OpKernelType GetKernelTypeForVar(
      const std::string &var_name, const framework::Tensor &tensor,
      const framework::OpKernelType &expected_kernel_type) const override {
    return framework::OpKernelType(expected_kernel_type.data_type_,
                                   expected_kernel_type.place_,
                                   tensor.layout());
  }
269 270
};

271
class CoalesceTensorOpMaker : public framework::OpProtoAndCheckerMaker {
272 273 274 275
 public:
  void Make() override {
    AddInput("Input",
             "(vector<LoDTensor>) The input tensors of"
276
             " coalesce_tensor operator.")
277 278 279
        .AsDuplicable();
    AddOutput("Output",
              "(vector<LoDTensor>) The output "
280
              "tensors of coalesce_tensor operator. And the address "
281 282 283 284 285
              "of output tensors are continuous, they are sliced from the "
              "tensor of FusedOutput.")
        .AsDuplicable();
    AddOutput("FusedOutput",
              "(LoDTensor) The output tensor "
286
              "of coalesce_tensor operator. And the tensors of"
287
              " Output is sliced from the tensor of FusedOutput.");
288
    AddAttr<int>("dtype", "The output data type.");
289 290 291 292 293
    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);
294 295 296
    AddAttr<bool>("persist_output",
                  "Whether to persist the original Output value.")
        .SetDefault(false);
297 298 299 300 301 302 303 304
    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);
305 306 307 308
    AddAttr<bool>("use_align",
                  "Whether to consider memory chunk and take alignment into "
                  "account for inputs and outputs.")
        .SetDefault(true);
309 310
    AddAttr<int>("align_size", "The alignment size when use_align is True")
        .SetDefault(-1);
311
    AddComment(R"DOC(
312
CoalesceTensor Operator.
313

314
coalesce_tensor is used to make the address of Output
315 316 317 318 319 320 321 322
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
323
coalesce_tensor allows copying the value of Input to Output, or
324 325
setting the Output with a constant value, or persist the original Output
value.
326 327 328 329 330 331 332 333

)DOC");
  }
};

}  // namespace operators
}  // namespace paddle

334 335
REGISTER_OPERATOR(coalesce_tensor, paddle::operators::CoalesceTensorOp,
                  paddle::operators::CoalesceTensorOpMaker);
336
namespace ops = paddle::operators;
337
namespace plat = paddle::platform;
338
REGISTER_OP_CPU_KERNEL(
339
    coalesce_tensor,
340 341 342
    ops::CoalesceTensorOpKernel<paddle::platform::CPUDeviceContext, int>,
    ops::CoalesceTensorOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::CoalesceTensorOpKernel<paddle::platform::CPUDeviceContext, double>);
343

344
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
345
REGISTER_OP_CUDA_KERNEL(
346
    coalesce_tensor,
347 348 349 350 351
    ops::CoalesceTensorOpKernel<paddle::platform::CUDADeviceContext,
                                plat::float16>,
    ops::CoalesceTensorOpKernel<paddle::platform::CUDADeviceContext, int>,
    ops::CoalesceTensorOpKernel<paddle::platform::CUDADeviceContext, float>,
    ops::CoalesceTensorOpKernel<paddle::platform::CUDADeviceContext, double>);
352
#endif
353

354 355 356 357 358 359 360 361 362 363
#if defined(PADDLE_WITH_ASCEND_CL)
REGISTER_OP_CUDA_KERNEL(
    coalesce_tensor,
    ops::CoalesceTensorOpKernel<paddle::platform::NPUDeviceContext,
                                plat::float16>,
    ops::CoalesceTensorOpKernel<paddle::platform::NPUDeviceContext, int>,
    ops::CoalesceTensorOpKernel<paddle::platform::NPUDeviceContext, float>,
    ops::CoalesceTensorOpKernel<paddle::platform::NPUDeviceContext, double>);
#endif

W
WangXi 已提交
364 365 366 367 368 369 370 371 372 373
#ifdef PADDLE_WITH_XPU
REGISTER_OP_XPU_KERNEL(
    coalesce_tensor,
    ops::CoalesceTensorOpKernel<paddle::platform::XPUDeviceContext,
                                plat::float16>,
    ops::CoalesceTensorOpKernel<paddle::platform::XPUDeviceContext, int>,
    ops::CoalesceTensorOpKernel<paddle::platform::XPUDeviceContext, float>,
    ops::CoalesceTensorOpKernel<paddle::platform::XPUDeviceContext, double>);
#endif

374 375 376 377 378 379 380 381 382 383
#if defined(PADDLE_WITH_ASCEND_CL)
REGISTER_OP_NPU_KERNEL(
    coalesce_tensor,
    ops::CoalesceTensorOpKernel<paddle::platform::CPUDeviceContext, int>,
    ops::CoalesceTensorOpKernel<paddle::platform::CPUDeviceContext, float>,
    ops::CoalesceTensorOpKernel<paddle::platform::CPUDeviceContext,
                                plat::float16>,
    ops::CoalesceTensorOpKernel<paddle::platform::CPUDeviceContext, double>);
#endif

384 385 386 387 388 389 390 391 392
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.",
393 394 395 396 397 398 399 400 401 402 403
            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));