layout_transformer.h 18.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// 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
16
#include "paddle/fluid/framework/framework.pb.h"
17 18 19 20 21
#include "paddle/fluid/imperative/layout_autotune.h"
#include "paddle/fluid/imperative/tracer.h"
#include "paddle/fluid/imperative/var_helper.h"
#include "paddle/phi/core/enforce.h"
#include "paddle/phi/core/errors.h"
22
#include "paddle/phi/core/tensor_utils.h"
23 24
namespace paddle {
namespace imperative {
25 26 27
template <typename VarType>
void SetOutDataLayout(std::shared_ptr<VarType> var,
                      const paddle::experimental::DataLayout layout) {
28
  if (var != nullptr && var->Var().IsInitialized()) {
29 30 31 32
    paddle::imperative::SetDataLayout(var, layout);
    // set out_tensor's layout
    if (var->MutableVar()->IsInitialized()) {
      paddle::framework::Variable* tmp_var = var->MutableVar();
33 34
      auto* out = tmp_var->GetMutable<phi::DenseTensor>();
      phi::DenseTensorUtils::GetMutableMeta(static_cast<phi::DenseTensor*>(out))
35 36 37 38
          ->layout = layout;
    }
  }
}
39 40 41

template <typename VarType>
std::shared_ptr<VarType> TraceTransposeOp(
42 43
    const std::shared_ptr<VarType>& var,
    const DataLayout layout,
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
    const std::shared_ptr<paddle::imperative::Tracer>& tracer) {
  std::vector<int> axis;
  if (layout == DataLayout::NHWC) {
    axis = {0, 2, 3, 1};
  } else if (layout == DataLayout::NCHW) {
    axis = {0, 3, 1, 2};
  } else {
    axis = {0, 1, 2, 3};
  }
  paddle::imperative::NameVarMap<VarType> ins = {{"X", {var}}};
  auto out =
      std::shared_ptr<VarType>(new VarType(tracer->GenerateUniqueName()));
  auto x_shape =
      std::shared_ptr<VarType>(new VarType(tracer->GenerateUniqueName()));
  paddle::imperative::NameVarMap<VarType> outs = {{"Out", {out}},
                                                  {"XShape", {x_shape}}};
  paddle::framework::AttributeMap attrs = {{"axis", axis}};
  tracer->TraceOp("transpose2", ins, outs, std::move(attrs));
  paddle::imperative::SetDataLayout(out, layout);
  VLOG(4) << "Transpose " << paddle::imperative::GetNameFromVar(var) << "["
          << paddle::framework::DataLayoutToString(
                 paddle::imperative::GetDataLayout(var))
          << "]"
          << " to " << paddle::imperative::GetNameFromVar(out) << "["
          << paddle::framework::DataLayoutToString(
                 paddle::imperative::GetDataLayout(out))
          << "]";
  return out;
}

template <typename VarType>
class LayoutTransformer {
 public:
  explicit LayoutTransformer(const std::string& type) : type_(type) {}

  virtual ~LayoutTransformer() {}

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

  virtual paddle::imperative::NameVarMap<VarType> Apply(
      const paddle::imperative::NameVarMap<VarType>& ins,
      const paddle::imperative::NameVarMap<VarType>& outs,
      paddle::framework::AttributeMap* attrs,
      const std::shared_ptr<paddle::imperative::Tracer>& tracer) {
    VLOG(3) << "Optimze Layout agnostic op: " << type_;
    auto in_layout = DataLayout::UNDEFINED;
    for (auto& pair : ins) {
      for (auto& var : pair.second) {
        // Once the any input is desired layout, we set in_layout is desired
        // layout.
95 96 97
        if (in_layout == DataLayout::UNDEFINED) {
          in_layout = paddle::imperative::GetDataLayout(var);
        }
98 99
        if (var != nullptr && (paddle::imperative::GetDataLayout(var) ==
                               LayoutAutoTune::Instance().GetDesiredLayout())) {
100 101 102 103 104
          in_layout = LayoutAutoTune::Instance().GetDesiredLayout();
          break;
        }
      }
    }
105 106 107 108 109
    VLOG(3) << "Optimze Layout agnostic op: " << type_ << " "
            << paddle::framework::DataLayoutToString(in_layout);
    if (in_layout != DataLayout::UNDEFINED) {
      SetVarsLayout(outs, in_layout);
    }
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    return ins;
  }

  // Set inputs, outputs and attributes to be optimized for the transposer.
  // Those may respectively be a subset of the corresponding original argument
  // of the operator.
  void SetArguments(const std::vector<std::string>& ins,
                    const std::vector<std::string>& outs,
                    const std::vector<std::string>& attrs) {
    ins_ = ins;
    outs_ = outs;
    attrs_ = attrs;
  }

  // Set the variables's layout to the specified layout.
  // If outs_ is not specified, it means all outputs of the operator
  // will be considered. Otherwise, it only set layout for the specified output.
  void SetVarsLayout(const paddle::imperative::NameVarMap<VarType>& outs,
                     DataLayout layout) const {
129 130 131 132 133 134 135
    bool not_in_out = true;
    if (!outs_.empty()) {
      for (auto& name : outs_) {
        if (outs.find(name) != outs.end()) {
          auto out_vars = outs.at(name);
          for (auto& var : out_vars) {
            if (var != nullptr) {
136
              paddle::imperative::SetOutDataLayout(var, layout);
137 138 139
            }
          }
          not_in_out = false;
140 141
        }
      }
142 143 144 145 146 147
    }

    if (not_in_out) {
      for (auto& pair : outs) {
        for (auto& var : pair.second) {
          if (var != nullptr) {
148
            paddle::imperative::SetOutDataLayout(var, layout);
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
        }
      }
    }
  }

  const std::vector<std::string>& Inputs() const { return ins_; }
  const std::vector<std::string>& Outputs() const { return outs_; }
  const std::vector<std::string>& Attributes() const { return attrs_; }

  const std::string& Type() { return type_; }

 protected:
  std::string type_{};
  std::vector<std::string> ins_{};
  std::vector<std::string> outs_{};
  std::vector<std::string> attrs_{};
};

/*
 * Both functionality and performance are affected by data layout.
 * Such as operators with data_format attribute.
 */
template <typename VarType>
class HeavilyLayoutSensitiveOpTransformer : public LayoutTransformer<VarType> {
 public:
  explicit HeavilyLayoutSensitiveOpTransformer(const std::string& type)
      : LayoutTransformer<VarType>(type) {}

  paddle::imperative::NameVarMap<VarType> Apply(
      const paddle::imperative::NameVarMap<VarType>& ins,
      const paddle::imperative::NameVarMap<VarType>& outs,
      paddle::framework::AttributeMap* attrs,
      const std::shared_ptr<paddle::imperative::Tracer>& tracer) {
    VLOG(3) << "Optimze heavily layout sensitive op " << this->Type();
    paddle::imperative::NameVarMap<VarType> new_ins(ins);

    // Step 1: Adjust the data_layout attr to the desired layout
    auto desired_layout = LayoutAutoTune::Instance().GetDesiredLayout();
    std::string desired_layout_str = paddle::framework::DataLayoutToString(
        LayoutAutoTune::Instance().GetDesiredLayout());
    if (attrs->find("data_format") != attrs->end() &&
R
Ruibiao Chen 已提交
191
        PADDLE_GET_CONST(std::string, (*attrs)["data_format"]) !=
192 193
            desired_layout_str) {
      VLOG(4) << "Origin layout attr: "
R
Ruibiao Chen 已提交
194
              << PADDLE_GET_CONST(std::string, (*attrs)["data_format"])
195 196 197
              << ", Desired layout attr: " << desired_layout_str;
      (*attrs)["data_format"] = desired_layout_str;
    } else if (attrs->find("data_layout") != attrs->end() &&
R
Ruibiao Chen 已提交
198
               PADDLE_GET_CONST(std::string, (*attrs)["data_layout"]) !=
199 200
                   desired_layout_str) {
      VLOG(4) << "Origin layout attr: "
R
Ruibiao Chen 已提交
201
              << PADDLE_GET_CONST(std::string, (*attrs)["data_layout"])
202 203 204 205 206 207 208
              << ", Desired layout attr: " << desired_layout_str;
      (*attrs)["data_layout"] = desired_layout_str;
    }

    // Step 2: Transpose the specified input for Op and set the transposed var's
    // layout.
    for (auto& name : this->Inputs()) {
209 210 211 212 213 214 215
      if (new_ins.find(name) != new_ins.end()) {
        auto& in_vars = new_ins[name];
        for (auto& var : in_vars) {
          if (var != nullptr &&
              paddle::imperative::GetDataLayout(var) != desired_layout) {
            var = TraceTransposeOp(var, desired_layout, tracer);
          }
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 245 246 247 248 249
        }
      }
    }

    // Step 3: Set the Op's layout sensitive outs var.
    this->SetVarsLayout(outs, desired_layout);

    return new_ins;
  }
};

/*
 * The functionality may be affected layout transformation before them.
 * Such as operators with axis attribute.
 */
template <typename VarType>
class LightlyLayoutSensitiveOpTransformer : public LayoutTransformer<VarType> {
 public:
  explicit LightlyLayoutSensitiveOpTransformer(const std::string& type)
      : LayoutTransformer<VarType>(type) {}

  paddle::imperative::NameVarMap<VarType> Apply(
      const paddle::imperative::NameVarMap<VarType>& ins,
      const paddle::imperative::NameVarMap<VarType>& outs,
      paddle::framework::AttributeMap* attrs,
      const std::shared_ptr<paddle::imperative::Tracer>& tracer) {
    VLOG(3) << "Optimze lightly layout sensitive op " << this->Type();
    paddle::imperative::NameVarMap<VarType> new_ins(ins);
    // If input's layout is not tuned, transformation is unnecessary.
    // If input's layout is already tuned, it will be transformed back to NCHW.
    // TODO(zhangting): The op of this type should be adapted to the previous
    // operator output data layout. Currently only a few operators are
    // supported, and transposers need to be carefully designed to ensure that
    // they do not cause exceptions.
250
    auto desired_layout = LayoutAutoTune::Instance().GetDesiredLayout();
251 252
    for (auto& pair : new_ins) {
      for (auto& var : pair.second) {
253 254 255 256 257 258 259 260 261 262 263
        if (var != nullptr) {
          VLOG(3) << "Tune the layout from "
                  << paddle::framework::DataLayoutToString(
                         paddle::imperative::GetDataLayout(var))
                  << " to "
                  << paddle::framework::DataLayoutToString(
                         LayoutAutoTune::Instance().GetDesiredLayout());
        }
        if (var != nullptr &&
            paddle::imperative::GetDataLayout(var) == desired_layout &&
            desired_layout == DataLayout::NHWC) {
264 265 266 267 268 269 270 271 272 273
          // Set layout to UNDEFINED so that TransposeOpTransformer do
          // NHWC->NCHW transformation.
          var = TraceTransposeOp(var, DataLayout::UNDEFINED, tracer);
        }
      }
    }
    return new_ins;
  }
};

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
template <typename VarType>
class ElementwiseOpTransformer
    : public LightlyLayoutSensitiveOpTransformer<VarType> {
 public:
  explicit ElementwiseOpTransformer(const std::string& type)
      : LightlyLayoutSensitiveOpTransformer<VarType>(type) {}

  paddle::imperative::NameVarMap<VarType> Apply(
      const paddle::imperative::NameVarMap<VarType>& ins,
      const paddle::imperative::NameVarMap<VarType>& outs,
      paddle::framework::AttributeMap* attrs,
      const std::shared_ptr<paddle::imperative::Tracer>& tracer) {
    // [Why we need the this?]
    // The Elementwise Ops has a axis attr, it is to support broadcast.
    // When bias_attr of Conv is not false, the elementwise_add will be
    // appended, and the axis will be set to the channel dimension.
    // If the axis is set to the channel dimension, the attr transformation
    // is necessary. Otherwise, it will fall back to the
    // LayoutTransformer::Apply.
    auto& in1_vars = ins.at("X")[0];
    auto& in2_vars = ins.at("Y")[0];
    auto in_layout = paddle::imperative::GetDataLayout(in1_vars);
    // for conv's bias
    if (attrs->find("axis") != attrs->end() &&
R
Ruibiao Chen 已提交
298
        PADDLE_GET_CONST(int, (*attrs)["axis"]) != -1) {
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
      if (in_layout == DataLayout::NHWC) {
        (*attrs)["axis"] = 3;
      } else if (in_layout == DataLayout::NCHW) {
        (*attrs)["axis"] = 1;
      }
      this->SetVarsLayout(outs, in_layout);
      return ins;
    } else {
      auto in2_layout = paddle::imperative::GetDataLayout(in2_vars);
      if (in_layout == in2_layout) {
        this->SetVarsLayout(outs, in_layout);
        return ins;
      }
      return LightlyLayoutSensitiveOpTransformer<VarType>::Apply(
          ins, outs, attrs, tracer);
    }
  }
};

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
template <typename VarType>
class TransposeOpTransformer
    : public LightlyLayoutSensitiveOpTransformer<VarType> {
 public:
  explicit TransposeOpTransformer(const std::string& type)
      : LightlyLayoutSensitiveOpTransformer<VarType>(type) {}

  paddle::imperative::NameVarMap<VarType> Apply(
      const paddle::imperative::NameVarMap<VarType>& ins,
      const paddle::imperative::NameVarMap<VarType>& outs,
      paddle::framework::AttributeMap* attrs,
      const std::shared_ptr<paddle::imperative::Tracer>& tracer) {
    VLOG(3) << "Optimze lightly layout sensitive op " << this->Type();
    // When the input layout is the desired format, it means that there
    // is a transpose layer in the network, it is better to transpose
    // the result to the original format.
    // Instead of actually inserting a transpose Op, we fuse the inserted
    // transpose Op with the current transpose Op by transforming 'axis' attr.
    auto& in_var = ins.at("X")[0];
    auto var_layout = paddle::imperative::GetDataLayout(in_var);
338 339
    auto desired_layout = LayoutAutoTune::Instance().GetDesiredLayout();
    if (var_layout == desired_layout && desired_layout == DataLayout::NHWC) {
R
Ruibiao Chen 已提交
340
      auto axis = PADDLE_GET_CONST(std::vector<int>, (*attrs)["axis"]);
341 342 343
      // NHWC->NCHW, permutaion will be set as follows.
      std::vector<int> perm = {0, 3, 1, 2};
      // fuse the transpose Ops by transforming axis.
344 345
      std::vector<int> fusion_axis = {
          perm[axis[0]], perm[axis[1]], perm[axis[2]], perm[axis[3]]};
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
      (*attrs)["axis"] = fusion_axis;
    }
    return ins;
  }
};

template <typename VarType>
class FlattenOpTransformer
    : public LightlyLayoutSensitiveOpTransformer<VarType> {
 public:
  explicit FlattenOpTransformer(const std::string& type)
      : LightlyLayoutSensitiveOpTransformer<VarType>(type) {}

  paddle::imperative::NameVarMap<VarType> Apply(
      const paddle::imperative::NameVarMap<VarType>& ins,
      const paddle::imperative::NameVarMap<VarType>& outs,
      paddle::framework::AttributeMap* attrs,
      const std::shared_ptr<paddle::imperative::Tracer>& tracer) {
    VLOG(3) << "Optimze lightly layout sensitive op " << this->Type();
    // Flatten the C, H, W dimensions will not affect functionality.
    // So transformation is unnecessary. But in other cases, it needs to
    // fall back to the LightlyLayoutSensitiveOpTransformer.
R
Ruibiao Chen 已提交
368 369
    auto start_axis = PADDLE_GET_CONST(int, (*attrs)["start_axis"]);
    auto stop_axis = PADDLE_GET_CONST(int, (*attrs)["stop_axis"]);
370 371 372 373 374
    if (paddle::imperative::GetDataLayout(ins.at("X")[0]) ==
            LayoutAutoTune::Instance().GetDesiredLayout() &&
        start_axis == 1 && stop_axis == 3) {
      return ins;
    } else {
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
      return LightlyLayoutSensitiveOpTransformer<VarType>::Apply(
          ins, outs, attrs, tracer);
    }
  }
};

template <typename VarType>
class ArgmaxOpTransformer
    : public LightlyLayoutSensitiveOpTransformer<VarType> {
 public:
  explicit ArgmaxOpTransformer(const std::string& type)
      : LightlyLayoutSensitiveOpTransformer<VarType>(type) {}

  paddle::imperative::NameVarMap<VarType> Apply(
      const paddle::imperative::NameVarMap<VarType>& ins,
      const paddle::imperative::NameVarMap<VarType>& outs,
      paddle::framework::AttributeMap* attrs,
      const std::shared_ptr<paddle::imperative::Tracer>& tracer) {
    VLOG(3) << "Optimze lightly layout sensitive op " << this->Type();
    auto& in_var = ins.at("X")[0];
    auto var_layout = paddle::imperative::GetDataLayout(in_var);
R
Ruibiao Chen 已提交
396
    bool keep_dims = PADDLE_GET_CONST(bool, (*attrs)["keepdims"]);
397 398
    if (keep_dims) {
      if (var_layout != DataLayout::UNDEFINED) {
399 400 401
        std::vector<int> perm_nhwc = {0, 3, 1, 2};
        std::vector<int> perm_nchw = {0, 2, 3, 1};

402 403 404
        auto perm = var_layout == DataLayout::NHWC ? perm_nhwc : perm_nchw;
        switch (AttrTypeID((*attrs)["axis"])) {
          case paddle::framework::proto::AttrType::INT: {
R
Ruibiao Chen 已提交
405
            auto axis = PADDLE_GET_CONST(int, (*attrs)["axis"]);
406 407 408
            (*attrs)["axis"] = static_cast<int>(perm[axis]);
          }
          case paddle::framework::proto::AttrType::LONG: {
R
Ruibiao Chen 已提交
409
            auto axis = PADDLE_GET_CONST(int64_t, (*attrs)["axis"]);
410 411 412 413 414 415 416 417 418 419
            (*attrs)["axis"] = static_cast<int64_t>(perm[axis]);
          }
          default:
            VLOG(4) << "The data_type of axis is Error, axis must be int or "
                       "int64, bug got "
                    << (AttrTypeID((*attrs)["axis"]));
        }
      }
      this->SetVarsLayout(outs, var_layout);
      return ins;
420
    }
421 422
    return LightlyLayoutSensitiveOpTransformer<VarType>::Apply(
        ins, outs, attrs, tracer);
423 424 425
  }
};

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
template <typename VarType>
class ConcatOpTransformer
    : public LightlyLayoutSensitiveOpTransformer<VarType> {
 public:
  explicit ConcatOpTransformer(const std::string& type)
      : LightlyLayoutSensitiveOpTransformer<VarType>(type) {}

  paddle::imperative::NameVarMap<VarType> Apply(
      const paddle::imperative::NameVarMap<VarType>& ins,
      const paddle::imperative::NameVarMap<VarType>& outs,
      paddle::framework::AttributeMap* attrs,
      const std::shared_ptr<paddle::imperative::Tracer>& tracer) {
    VLOG(3) << "Optimze lightly layout sensitive op " << this->Type();
    auto& in_var = ins.at("X")[0];
    auto var_layout = paddle::imperative::GetDataLayout(in_var);
    bool need_tranppose = false;
    for (auto& pair : ins) {
      for (auto& var : pair.second) {
        if (var != nullptr &&
            (paddle::imperative::GetDataLayout(var) != var_layout)) {
          need_tranppose = true;
          break;
        }
      }
    }

    if (need_tranppose) {
      return LightlyLayoutSensitiveOpTransformer<VarType>::Apply(
          ins, outs, attrs, tracer);
    }

    if (var_layout != DataLayout::UNDEFINED) {
      std::vector<int> perm_nhwc = {0, 3, 1, 2};
      std::vector<int> perm_nchw = {0, 2, 3, 1};
      auto perm = var_layout == DataLayout::NHWC ? perm_nhwc : perm_nchw;
R
Ruibiao Chen 已提交
461
      auto axis = PADDLE_GET_CONST(int, (*attrs)["axis"]);
462 463
      (*attrs)["axis"] = static_cast<int>(perm[axis]);
    }
R
Ruibiao Chen 已提交
464
    auto axis = PADDLE_GET_CONST(int, (*attrs)["axis"]);
465 466 467 468 469 470 471
    VLOG(3) << "Optimze lightly layout sensitive op asdfasdfasdf axis" << axis;

    this->SetVarsLayout(outs, var_layout);
    return ins;
  }
};

472 473
}  // namespace imperative
}  // namespace paddle