eager_layout_transformer.h 17.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// Copyright (c) 2022 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.

#pragma once

#include "paddle/fluid/eager/api/generated/eager_generated/forwards/dygraph_functions.h"
#include "paddle/fluid/imperative/layout_autotune.h"
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/core/tensor_utils.h"
namespace egr {
inline paddle::experimental::Tensor EagerTraceTransposeOp(
    const paddle::experimental::DataLayout layout,
    const paddle::experimental::Tensor& in) {
25 26
  VLOG(4) << "AutoTune Transpose from " << in.layout() << " to " << layout
          << ", tensor's shape is " << in.shape().size();
27 28 29 30 31 32 33 34 35 36 37
  if (in.shape().size() != 4) {
    return in;
  }
  std::vector<int> axis;
  if (layout == paddle::experimental::DataLayout::NHWC) {
    axis = {0, 2, 3, 1};
  } else if (layout == paddle::experimental::DataLayout::NCHW) {
    axis = {0, 3, 1, 2};
  } else {
    axis = {0, 1, 2, 3};
  }
J
Jiabin Yang 已提交
38
  auto out_tensor = transpose_ad_func(in, axis);
39 40 41 42 43 44 45 46
  VLOG(4) << "AutoTune Transpose from "
          << paddle::framework::DataLayoutToString(in.layout()) << " to "
          << paddle::framework::DataLayoutToString(layout);
  return out_tensor;
}

// agnostic op
class EagerLayoutTransformer {
47 48
  using Layout = paddle::experimental::DataLayout;

49
 public:
50
  EagerLayoutTransformer() : op_name_(""), final_layout_(Layout::UNDEFINED) {}
51 52 53 54 55

  EagerLayoutTransformer(const EagerLayoutTransformer&) = delete;

  EagerLayoutTransformer& operator=(const EagerLayoutTransformer&) = delete;

56 57 58 59 60 61 62 63 64 65
  explicit EagerLayoutTransformer(
      const std::string& op_name,
      const paddle::small_vector<std::vector<paddle::experimental::Tensor>,
                                 kSlotSmallVectorSize>& tensors_vector,
      const Layout final_layout = Layout::UNDEFINED)
      : op_name_(op_name), final_layout_(final_layout) {
    VLOG(4) << "Agnostic op : " << op_name_ << " final_layout_ is "
            << final_layout_;
  }

66 67
  virtual ~EagerLayoutTransformer() {}

68 69 70 71 72 73 74 75 76 77 78 79 80 81
  virtual paddle::experimental::Tensor TransInTensor(
      const std::string& in_name, const paddle::experimental::Tensor& in) {
    if (final_layout_ == Layout::UNDEFINED || final_layout_ == in.layout()) {
      VLOG(4) << "EagerLayoutTransformer with no trans";
      return in;
    } else {  // from NCHW to NHWC
      VLOG(4) << "EagerLayoutTransformer with trans from " << in.layout()
              << " to " << final_layout_;
      auto out_tensor = EagerTraceTransposeOp(final_layout_, in);
      phi::DenseTensorUtils::GetMutableMeta(
          static_cast<phi::DenseTensor*>(out_tensor.impl().get()))
          ->layout = final_layout_;
      return out_tensor;
    }
82 83
  }

84
  virtual paddle::optional<paddle::experimental::Tensor> TransInTensor(
85
      const std::string& in_name,
86 87
      const paddle::optional<paddle::experimental::Tensor>& in) {
    return in ? TransInTensor(in_name, *in) : in;
88 89
  }

90
  virtual std::vector<paddle::experimental::Tensor> TransInTensors(
91 92
      const std::string& in_name,
      const std::vector<paddle::experimental::Tensor>& in) {
93
    VLOG(4) << " TransInTensor";
94 95 96
    return in;
  }

97 98 99 100 101 102 103 104
  virtual paddle::optional<std::vector<paddle::experimental::Tensor>>
  TransInTensors(
      const std::string& in_name,
      const paddle::optional<std::vector<paddle::experimental::Tensor>>& in) {
    VLOG(4) << " TransInTensor";
    if (in) {
      return TransInTensors(in_name, *in);
    }
105 106 107
    return in;
  }

108 109 110
  virtual void SetOutTensorLayout(
      paddle::optional<paddle::experimental::Tensor>* out_tensor) {
    VLOG(4) << "optional out_tensor";
111 112 113 114
  }

  virtual void SetOutTensorLayout(
      std::vector<paddle::experimental::Tensor>* out_tensor) {
115
    bool use_default = (final_layout_ == Layout::UNDEFINED);
116 117 118 119 120 121 122 123 124 125 126
    if (!use_default) {
      for (size_t i = 0; i < out_tensor->size(); i++) {
        phi::DenseTensorUtils::GetMutableMeta(
            static_cast<phi::DenseTensor*>((*out_tensor)[i].impl().get()))
            ->layout =
            paddle::imperative::LayoutAutoTune::Instance().GetDesiredLayout();
      }
    }
    VLOG(4) << op_name_ << "is is agnostic, use_default " << use_default;
  }

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
  virtual void SetOutTensorLayout(
      paddle::optional<std::vector<paddle::experimental::Tensor>>* out_tensor) {
    VLOG(4) << "optional out_tensor";
  }

  virtual void SetOutTensorLayout(paddle::experimental::Tensor* out_tensor) {
    bool use_default = final_layout_ == Layout::UNDEFINED;
    if (!use_default) {
      phi::DenseTensorUtils::GetMutableMeta(
          static_cast<phi::DenseTensor*>(out_tensor->impl().get()))
          ->layout = final_layout_;
    }
    VLOG(4) << op_name_ << "is is agnostic, use_default " << use_default;
  }

142 143
 protected:
  std::string op_name_;
144
  const Layout final_layout_;
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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
};

class EagerHeavilyLayoutSensitiveOpTransformer : public EagerLayoutTransformer {
 public:
  explicit EagerHeavilyLayoutSensitiveOpTransformer(const std::string& op_name,
                                                    std::string* layout)
      : op_name_(op_name),
        desired_layout_(
            paddle::imperative::LayoutAutoTune::Instance().GetDesiredLayout()) {
    VLOG(3) << "Optimze Layout heavily op: " << op_name;
    final_layout_ = paddle::framework::DataLayoutToString(desired_layout_);
    if ((*layout) != final_layout_) {
      *layout = final_layout_;
    }
  }

  paddle::experimental::Tensor TransInTensor(
      const std::string& in_name, const paddle::experimental::Tensor& in) {
    if (heavily_input_.count(in_name) != 0 && in.layout() != desired_layout_) {
      VLOG(4) << op_name_ << "'s " << in_name << " need transpose from "
              << paddle::framework::DataLayoutToString(in.layout()) << " to "
              << final_layout_;
      auto out_tensor = EagerTraceTransposeOp(desired_layout_, in);
      return out_tensor;
    }
    return in;
  }

  void SetOutTensorLayout(paddle::experimental::Tensor* out_tensor) {
    if (out_tensor->layout() != desired_layout_) {
      VLOG(4) << " Set Out_tensor's layout from "
              << paddle::framework::DataLayoutToString(out_tensor->layout())
              << " to " << final_layout_;
      phi::DenseTensorUtils::GetMutableMeta(
          static_cast<phi::DenseTensor*>(out_tensor->impl().get()))
          ->layout = desired_layout_;
    }
  }

  void SetOutTensorLayout(
      std::vector<paddle::experimental::Tensor*>* out_tensor) {
    for (size_t i = 0; i < out_tensor->size(); i++) {
      SetOutTensorLayout((*out_tensor)[i]);
    }
  }

  void SetOutTensorLayout(
      std::vector<paddle::experimental::Tensor>* out_tensor) {
    for (size_t i = 0; i < out_tensor->size(); i++) {
      if ((*out_tensor)[i].layout() != desired_layout_) {
        VLOG(4) << " Set Out_tensor's layout from "
                << paddle::framework::DataLayoutToString(
                       (*out_tensor)[i].layout())
                << " to " << final_layout_;
        phi::DenseTensorUtils::GetMutableMeta(
            static_cast<phi::DenseTensor*>((*out_tensor)[i].impl().get()))
            ->layout = desired_layout_;
      }
    }
  }

 protected:
  std::string op_name_;
  std::string final_layout_;
  const paddle::experimental::DataLayout desired_layout_;
  std::unordered_set<std::string> heavily_input_{"x", "y", "input"};
};

class EagerLightlyLayoutSensitiveOpTransformer : public EagerLayoutTransformer {
 public:
  EagerLightlyLayoutSensitiveOpTransformer() {}
  explicit EagerLightlyLayoutSensitiveOpTransformer(const std::string& op_name)
      : op_name_(op_name) {
    VLOG(3) << "Optimze Layout lightly " << op_name;
    auto desired_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDesiredLayout();
    final_layout_ = paddle::framework::DataLayoutToString(desired_layout);
  }

  // transpose from desired to default
  paddle::experimental::Tensor TransInTensor(
      const std::string& in_name, const paddle::experimental::Tensor& in) {
    std::string input_layout =
        paddle::framework::DataLayoutToString(in.layout());
    auto default_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDefaultLayout();
    if (final_layout_ == input_layout && in.shape().size() == 4) {
      VLOG(4) << op_name_ << "'s " << in_name << " need transpose from "
              << input_layout << " to default_layout";
      auto out_tensor = EagerTraceTransposeOp(
          paddle::experimental::DataLayout::UNDEFINED, in);
      phi::DenseTensorUtils::GetMutableMeta(
          static_cast<phi::DenseTensor*>(out_tensor.impl().get()))
          ->layout = default_layout;
      return out_tensor;
    }
    VLOG(4) << in_name << "'s layout is " << input_layout;
    return in;
  }

245
  virtual std::vector<paddle::experimental::Tensor> TransInTensors(
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 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
      const std::string& in_name,
      const std::vector<paddle::experimental::Tensor>& in) {
    std::vector<paddle::experimental::Tensor> result;
    auto desired_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDesiredLayout();
    auto default_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDefaultLayout();
    for (size_t i = 0; i < in.size(); i++) {
      auto in_tensor = in[i];
      if (in_tensor.layout() == desired_layout) {
        VLOG(4) << op_name_ << "'s " << in_name << " need transpose from "
                << final_layout_ << " to default_layout";
        auto out_tensor = EagerTraceTransposeOp(
            paddle::experimental::DataLayout::UNDEFINED, in_tensor);
        phi::DenseTensorUtils::GetMutableMeta(
            static_cast<phi::DenseTensor*>(out_tensor.impl().get()))
            ->layout = default_layout;
        result.emplace_back(out_tensor);
      } else {
        result.emplace_back(in_tensor);
      }
    }
    return result;
  }

  void SetOutTensorLayout(paddle::experimental::Tensor* out_tensor) {
    auto out_layout = out_tensor->layout();
    auto default_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDefaultLayout();
    if (out_layout != default_layout) {
      VLOG(4) << op_name_ << "'s out need transpose to default_layout";
      phi::DenseTensorUtils::GetMutableMeta(
          static_cast<phi::DenseTensor*>(out_tensor->impl().get()))
          ->layout = default_layout;
    }
  }

  void SetOutTensorLayout(
      std::vector<paddle::experimental::Tensor*>* out_tensor) {
    for (size_t i = 0; i < out_tensor->size(); i++) {
      VLOG(4) << "out layout is"
              << paddle::framework::DataLayoutToString(
                     (*out_tensor)[i]->layout());
      SetOutTensorLayout((*out_tensor)[i]);
    }
  }

  void SetOutTensorLayout(
      std::vector<paddle::experimental::Tensor>* out_tensor) {
    auto default_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDefaultLayout();
    for (size_t i = 0; i < out_tensor->size(); i++) {
      VLOG(4) << " out_tensor layout trans to default ";
      phi::DenseTensorUtils::GetMutableMeta(
          static_cast<phi::DenseTensor*>((*out_tensor)[i].impl().get()))
          ->layout = default_layout;
    }
  }

 protected:
  std::string op_name_;
  std::string final_layout_;
  std::unordered_set<std::string> heavily_input_{"x", "y", "input"};
};

class EagerTransposeOpTransformer
    : public EagerLightlyLayoutSensitiveOpTransformer {
 public:
  EagerTransposeOpTransformer() {}
  explicit EagerTransposeOpTransformer(const std::string& op_name)
      : op_name_(op_name) {
    VLOG(3) << "Optimze Layout TransposeOpTransformer " << op_name;
    auto desired_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDesiredLayout();
    std::string desired_layout_str =
        paddle::framework::DataLayoutToString(desired_layout);
    final_layout_ = desired_layout_str;
  }

  void SetAttr(std::vector<int>* axis, bool is_nhwc) {
    // input's layout is nhwc and input's layout === desired_layout
    std::vector<int> perm_nchw = {0, 2, 3, 1};
    std::vector<int> perm_nhwc = {0, 3, 1, 2};
    auto perm = is_nhwc ? perm_nhwc : perm_nchw;
    (*axis)[0] = perm[(*axis)[0]];
    (*axis)[1] = perm[(*axis)[1]];
    (*axis)[2] = perm[(*axis)[2]];
    (*axis)[3] = perm[(*axis)[3]];
    VLOG(4) << " EagerTransposeOpTransformer " << op_name_
            << "'s layout is equal to desire: " << is_nhwc;
  }

  paddle::experimental::Tensor TransInTensor(
      const std::string& in_name, const paddle::experimental::Tensor& in) {
    return in;
  }

  void SetOutTensorLayout(paddle::experimental::Tensor* out_tensor) {
344 345 346
    auto default_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDefaultLayout();
    if (out_tensor->layout() != default_layout) {
347 348
      VLOG(4) << " Set Out_tensor's layout from "
              << paddle::framework::DataLayoutToString(out_tensor->layout())
349
              << " to " << default_layout;
350 351
      phi::DenseTensorUtils::GetMutableMeta(
          static_cast<phi::DenseTensor*>(out_tensor->impl().get()))
352
          ->layout = default_layout;
353 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
    }
  }

 protected:
  std::string op_name_;
  std::string final_layout_;
  std::unordered_set<std::string> heavily_input_{"x", "y", "input"};
};

class EagerArgmaxOpTransformer
    : public EagerLightlyLayoutSensitiveOpTransformer {
 public:
  EagerArgmaxOpTransformer() {}
  explicit EagerArgmaxOpTransformer(const std::string& op_name)
      : op_name_(op_name) {
    VLOG(3) << "Optimze Layout lightly " << op_name;
  }

  void SetAttr(paddle::experimental::Scalar* axis, bool is_nhwc) {
    std::vector<int> perm_nhwc = {0, 3, 1, 2};
    std::vector<int> perm_nchw = {0, 2, 3, 1};
    auto perm = is_nhwc ? perm_nhwc : perm_nchw;
    int axes = axis->to<int>();
    (*axis) = static_cast<paddle::experimental::Scalar>(perm[axes]);
  }

  void SetOutTensorLayout(paddle::experimental::Tensor* out_tensor) {
    VLOG(4) << "EagerArgmaxOpTransformer's out layout is"
            << paddle::framework::DataLayoutToString(out_tensor->layout());
382 383 384
    auto default_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDefaultLayout();
    if (default_layout != out_tensor->layout()) {
385 386
      VLOG(4) << "Change layout from "
              << paddle::framework::DataLayoutToString(out_tensor->layout())
387
              << " to " << default_layout;
388 389
      phi::DenseTensorUtils::GetMutableMeta(
          static_cast<phi::DenseTensor*>(out_tensor->impl().get()))
390
          ->layout = default_layout;
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    }
  }

 protected:
  std::string op_name_;
  std::string final_layout_;
  std::unordered_set<std::string> heavily_input_{"x", "y", "input"};
};

class EagerFlattenOpTransformer
    : public EagerLightlyLayoutSensitiveOpTransformer {
 public:
  EagerFlattenOpTransformer() {}
  explicit EagerFlattenOpTransformer(const std::string& op_name)
      : op_name_(op_name) {
    VLOG(3) << "Optimze Layout lightly " << op_name;
407 408 409 410 411
    auto default_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDefaultLayout();
    std::string default_layout_str =
        paddle::framework::DataLayoutToString(default_layout);
    final_layout_ = default_layout_str;
412 413 414 415 416 417 418 419 420
  }

  // transpose from NHWC to NCHW
  paddle::experimental::Tensor TransInTensor(
      const std::string& in_name, const paddle::experimental::Tensor& in) {
    return in;
  }

  void SetOutTensorLayout(paddle::experimental::Tensor* out_tensor) {
421
    VLOG(4) << "EagerFlattenOpTransformer's out layout is"
422
            << paddle::framework::DataLayoutToString(out_tensor->layout());
423 424 425
    auto desired_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDesiredLayout();
    if (desired_layout != out_tensor->layout()) {
426 427
      VLOG(4) << "Change layout from "
              << paddle::framework::DataLayoutToString(out_tensor->layout())
428
              << " to " << desired_layout;
429 430
      phi::DenseTensorUtils::GetMutableMeta(
          static_cast<phi::DenseTensor*>(out_tensor->impl().get()))
431
          ->layout = desired_layout;
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
    }
  }

 protected:
  std::string op_name_;
  std::string final_layout_;
  std::unordered_set<std::string> heavily_input_{"x", "y", "input"};
};

class EagerConcatOpTransformer
    : public EagerLightlyLayoutSensitiveOpTransformer {
 public:
  EagerConcatOpTransformer() {}
  explicit EagerConcatOpTransformer(const std::string& op_name)
      : op_name_(op_name) {
    VLOG(3) << "Optimze Layout lightly " << op_name;
448 449 450 451 452
    auto default_layout =
        paddle::imperative::LayoutAutoTune::Instance().GetDefaultLayout();
    std::string default_layout_str =
        paddle::framework::DataLayoutToString(default_layout);
    final_layout_ = default_layout_str;
453 454 455 456 457 458 459 460 461 462 463 464
  }

  void SetAttr(paddle::experimental::Scalar* axis,
               paddle::framework::DataLayout layout) {
    std::vector<int> perm_nhwc = {0, 3, 1, 2};
    std::vector<int> perm_nchw = {0, 2, 3, 1};
    int axes = axis->to<int>();
    auto perm =
        (paddle::framework::DataLayout::NHWC == layout) ? perm_nhwc : perm_nchw;
    (*axis) = static_cast<paddle::experimental::Scalar>(perm[axes]);
  }

465
  virtual std::vector<paddle::experimental::Tensor> TransInTensors(
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
      const std::string& in_name,
      const std::vector<paddle::experimental::Tensor>& in) {
    return in;
  }

  void SetOutTensorLayout(paddle::experimental::Tensor* out_tensor) {
    auto layout = paddle::framework::StringToDataLayout(final_layout_);
    if (layout != out_tensor->layout()) {
      VLOG(4) << "Change layout from "
              << paddle::framework::DataLayoutToString(out_tensor->layout())
              << " to " << final_layout_;
      phi::DenseTensorUtils::GetMutableMeta(
          static_cast<phi::DenseTensor*>(out_tensor->impl().get()))
          ->layout = layout;
    }
  }

 protected:
  std::string op_name_;
  std::string final_layout_;
  std::unordered_set<std::string> heavily_input_{"x", "y", "input"};
};
}  // namespace egr