layout_transformer.h 18.3 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
template <typename VarType>
void SetOutDataLayout(std::shared_ptr<VarType> var,
27
                      const phi::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
    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) << "["
64
          << phi::DataLayoutToString(paddle::imperative::GetDataLayout(var))
65 66
          << "]"
          << " to " << paddle::imperative::GetNameFromVar(out) << "["
67
          << phi::DataLayoutToString(paddle::imperative::GetDataLayout(out))
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
          << "]";
  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.
93 94 95
        if (in_layout == DataLayout::UNDEFINED) {
          in_layout = paddle::imperative::GetDataLayout(var);
        }
96 97
        if (var != nullptr && (paddle::imperative::GetDataLayout(var) ==
                               LayoutAutoTune::Instance().GetDesiredLayout())) {
98 99 100 101 102
          in_layout = LayoutAutoTune::Instance().GetDesiredLayout();
          break;
        }
      }
    }
103
    VLOG(3) << "Optimze Layout agnostic op: " << type_ << " "
104
            << phi::DataLayoutToString(in_layout);
105 106 107
    if (in_layout != DataLayout::UNDEFINED) {
      SetVarsLayout(outs, in_layout);
    }
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    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 {
127 128 129 130 131 132 133
    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) {
134
              paddle::imperative::SetOutDataLayout(var, layout);
135 136 137
            }
          }
          not_in_out = false;
138 139
        }
      }
140 141 142 143 144 145
    }

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

  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();
186 187
    std::string desired_layout_str =
        phi::DataLayoutToString(LayoutAutoTune::Instance().GetDesiredLayout());
188
    if (attrs->find("data_format") != attrs->end() &&
R
Ruibiao Chen 已提交
189
        PADDLE_GET_CONST(std::string, (*attrs)["data_format"]) !=
190 191
            desired_layout_str) {
      VLOG(4) << "Origin layout attr: "
R
Ruibiao Chen 已提交
192
              << PADDLE_GET_CONST(std::string, (*attrs)["data_format"])
193 194 195
              << ", Desired layout attr: " << desired_layout_str;
      (*attrs)["data_format"] = desired_layout_str;
    } else if (attrs->find("data_layout") != attrs->end() &&
R
Ruibiao Chen 已提交
196
               PADDLE_GET_CONST(std::string, (*attrs)["data_layout"]) !=
197 198
                   desired_layout_str) {
      VLOG(4) << "Origin layout attr: "
R
Ruibiao Chen 已提交
199
              << PADDLE_GET_CONST(std::string, (*attrs)["data_layout"])
200 201 202 203 204 205 206
              << ", 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()) {
207 208 209 210 211 212 213
      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);
          }
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 245 246 247
        }
      }
    }

    // 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.
248
    auto desired_layout = LayoutAutoTune::Instance().GetDesiredLayout();
249 250
    for (auto& pair : new_ins) {
      for (auto& var : pair.second) {
251 252
        if (var != nullptr) {
          VLOG(3) << "Tune the layout from "
253
                  << phi::DataLayoutToString(
254 255
                         paddle::imperative::GetDataLayout(var))
                  << " to "
256
                  << phi::DataLayoutToString(
257 258 259 260 261
                         LayoutAutoTune::Instance().GetDesiredLayout());
        }
        if (var != nullptr &&
            paddle::imperative::GetDataLayout(var) == desired_layout &&
            desired_layout == DataLayout::NHWC) {
262 263 264 265 266 267 268 269 270 271
          // Set layout to UNDEFINED so that TransposeOpTransformer do
          // NHWC->NCHW transformation.
          var = TraceTransposeOp(var, DataLayout::UNDEFINED, tracer);
        }
      }
    }
    return new_ins;
  }
};

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
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 已提交
296
        PADDLE_GET_CONST(int, (*attrs)["axis"]) != -1) {
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
      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);
    }
  }
};

316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
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);
336 337
    auto desired_layout = LayoutAutoTune::Instance().GetDesiredLayout();
    if (var_layout == desired_layout && desired_layout == DataLayout::NHWC) {
R
Ruibiao Chen 已提交
338
      auto axis = PADDLE_GET_CONST(std::vector<int>, (*attrs)["axis"]);
339 340 341
      // NHWC->NCHW, permutaion will be set as follows.
      std::vector<int> perm = {0, 3, 1, 2};
      // fuse the transpose Ops by transforming axis.
342 343
      std::vector<int> fusion_axis = {
          perm[axis[0]], perm[axis[1]], perm[axis[2]], perm[axis[3]]};
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
      (*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 已提交
366 367
    auto start_axis = PADDLE_GET_CONST(int, (*attrs)["start_axis"]);
    auto stop_axis = PADDLE_GET_CONST(int, (*attrs)["stop_axis"]);
368 369 370 371 372
    if (paddle::imperative::GetDataLayout(ins.at("X")[0]) ==
            LayoutAutoTune::Instance().GetDesiredLayout() &&
        start_axis == 1 && stop_axis == 3) {
      return ins;
    } else {
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
      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 已提交
394
    bool keep_dims = PADDLE_GET_CONST(bool, (*attrs)["keepdims"]);
395 396
    if (keep_dims) {
      if (var_layout != DataLayout::UNDEFINED) {
397 398 399
        std::vector<int> perm_nhwc = {0, 3, 1, 2};
        std::vector<int> perm_nchw = {0, 2, 3, 1};

400 401 402
        auto perm = var_layout == DataLayout::NHWC ? perm_nhwc : perm_nchw;
        switch (AttrTypeID((*attrs)["axis"])) {
          case paddle::framework::proto::AttrType::INT: {
R
Ruibiao Chen 已提交
403
            auto axis = PADDLE_GET_CONST(int, (*attrs)["axis"]);
404
            (*attrs)["axis"] = static_cast<int>(perm[axis]);
405
            break;
406 407
          }
          case paddle::framework::proto::AttrType::LONG: {
R
Ruibiao Chen 已提交
408
            auto axis = PADDLE_GET_CONST(int64_t, (*attrs)["axis"]);
409
            (*attrs)["axis"] = static_cast<int64_t>(perm[axis]);
410
            break;
411 412 413 414 415 416 417 418 419
          }
          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