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

#include "paddle/fluid/imperative/amp_auto_cast.h"
16

17 18
#include <memory>
#include <string>
19

J
Jiabin Yang 已提交
20
#include "paddle/fluid/eager/eager_tensor.h"
21
#include "paddle/fluid/imperative/tracer.h"
J
Jiabin Yang 已提交
22 23
#include "paddle/fluid/imperative/type_defs.h"
#include "paddle/fluid/imperative/var_helper.h"
24

25
DECLARE_bool(low_precision_op_list);
26 27 28
namespace paddle {
namespace imperative {

W
wanghuancoder 已提交
29 30
class VarBase;

L
Leo Chen 已提交
31 32 33 34 35 36 37 38 39
// According to the input `place` and `dtype`, this function returns a tuple
// consists of three sets:
// 1) All operators registered in the Paddle framework.
// 2) All operators supported for `place` and `dtype`.
// 3) All operators unsupported for `place` and `dtype`.
// The input `place` is a type of string, which can only be `GPU` or `CPU`.
// The input `dtype` is a type of paddle::framework::proto::VarType::Type,
// which can be paddle::framework::proto::VarType::FP16,
// paddle::framework::proto::VarType::FP32 and so on.
40 41
std::tuple<std::unordered_set<std::string>,
           std::unordered_set<std::string>,
L
Leo Chen 已提交
42 43 44 45
           std::unordered_set<std::string>>
OpSupportedInfos(const std::string& place,
                 framework::proto::VarType::Type dtype) {
  std::string query_place;
46 47 48
  std::transform(place.begin(),
                 place.end(),
                 std::back_inserter(query_place),
L
Leo Chen 已提交
49 50 51
                 [](unsigned char c) { return std::toupper(c); });
  using fn_type = std::add_pointer<bool(const platform::Place&)>::type;
  std::unordered_map<std::string, fn_type> is_target_place{
52 53 54 55
      {"GPU", &platform::is_gpu_place},
      {"CPU", &platform::is_cpu_place},
      {"XPU", &platform::is_xpu_place},
      {"NPU", &platform::is_npu_place},
L
Leo Chen 已提交
56 57
      {"MLU", &platform::is_mlu_place},
  };
58 59
  PADDLE_ENFORCE_NE(is_target_place.count(query_place),
                    0,
L
Leo Chen 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
                    platform::errors::InvalidArgument(
                        "The argument `place` should be 'GPU', 'CPU', 'XPU', "
                        "'NPU', 'MLU', but got '%s'.",
                        place));

  std::unordered_set<std::string> all_ops;
  const auto& op_info = framework::OpInfoMap::Instance().map();
  for (auto it = op_info.begin(); it != op_info.end(); it++) {
    all_ops.emplace(it->first);
  }

  std::unordered_set<std::string> supported_ops;
  auto& all_kernels = framework::OperatorWithKernel::AllOpKernels();
  for (auto it = all_kernels.begin(); it != all_kernels.end(); it++) {
    for (auto& kernel_type : it->second) {
      if (is_target_place[query_place](kernel_type.first.place_) &&
          kernel_type.first.data_type_ == dtype) {
        supported_ops.emplace(it->first);
      }
    }
  }

82 83
  auto phi_kernels = phi::KernelFactory::Instance().kernels();
  for (auto& kernel_pair : phi_kernels) {
84
    auto op_type = phi::TransToFluidOpName(kernel_pair.first);
L
Leo Chen 已提交
85 86
    for (auto& info_pair : kernel_pair.second) {
      framework::OpKernelType kernel_type =
87
          framework::TransPhiKernelKeyToOpKernelType(info_pair.first);
L
Leo Chen 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
      if (is_target_place[query_place](kernel_type.place_) &&
          kernel_type.data_type_ == dtype && all_ops.count(op_type)) {
        VLOG(4) << op_type << " " << supported_ops.size();
        supported_ops.emplace(op_type);
      }
    }
  }

  std::unordered_set<std::string> unsupported_ops;
  for (auto& op : all_ops) {
    if (!supported_ops.count(op)) {
      unsupported_ops.emplace(op);
    }
  }

  VLOG(4) << "-- The size of all_ops: " << all_ops.size() << " --";
  VLOG(4) << "-- The size of supported_ops: " << supported_ops.size() << " --";
  VLOG(4) << "-- The size of unsupported_ops: " << unsupported_ops.size()
          << " --";
107 108
  return std::make_tuple(
      std::move(all_ops), std::move(supported_ops), std::move(unsupported_ops));
L
Leo Chen 已提交
109 110
}

L
Leo Chen 已提交
111 112 113 114 115 116 117 118 119 120 121
AutoCastGuard::AutoCastGuard(std::shared_ptr<Tracer> tracer, AmpLevel level)
    : tracer_(tracer) {
  pre_amp_level_ = tracer_->GetAmpLevel();

  if (pre_amp_level_ != level) {
    tracer_->SetAmpLevel(level);
  }
}

AutoCastGuard::~AutoCastGuard() { tracer_->SetAmpLevel(pre_amp_level_); }

122 123
AmpOperators::AmpOperators()
    : allow_ops_(new std::unordered_set<std::string>()),
124
      block_ops_(new std::unordered_set<std::string>()),
125 126
      unsupported_fp16_ops_(new std::unordered_set<std::string>()),
      unsupported_bf16_ops_(new std::unordered_set<std::string>()) {
L
Leo Chen 已提交
127
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
128
  auto unsupported_ops_gpu_fp16 = std::get<2>(
L
Leo Chen 已提交
129
      OpSupportedInfos("GPU", paddle::framework::proto::VarType::FP16));
130 131 132 133 134 135
  unsupported_fp16_ops_->insert(unsupported_ops_gpu_fp16.begin(),
                                unsupported_ops_gpu_fp16.end());
  auto unsupported_ops_gpu_bf16 = std::get<2>(
      OpSupportedInfos("GPU", paddle::framework::proto::VarType::BF16));
  unsupported_bf16_ops_->insert(unsupported_ops_gpu_bf16.begin(),
                                unsupported_ops_gpu_bf16.end());
Q
qipengh 已提交
136
// NOTE: GPU/NPU/XPU/MLU is compiled seperatly.
L
Leo Chen 已提交
137
#elif defined(PADDLE_WITH_ASCEND_CL)
138
  auto unsupported_ops_npu_fp16 = std::get<2>(
L
Leo Chen 已提交
139
      OpSupportedInfos("NPU", paddle::framework::proto::VarType::FP16));
140 141 142 143 144 145
  unsupported_fp16_ops_->insert(unsupported_ops_npu_fp16.begin(),
                                unsupported_ops_npu_fp16.end());
  auto unsupported_ops_npu_bf16 = std::get<2>(
      OpSupportedInfos("NPU", paddle::framework::proto::VarType::BF16));
  unsupported_bf16_ops_->insert(unsupported_ops_npu_bf16.begin(),
                                unsupported_ops_npu_bf16.end());
L
Leo Chen 已提交
146
#elif defined(PADDLE_WITH_XPU)
147
  auto unsupported_ops_xpu_fp16 = std::get<2>(
L
Leo Chen 已提交
148
      OpSupportedInfos("XPU", paddle::framework::proto::VarType::FP16));
149 150 151 152 153 154
  unsupported_fp16_ops_->insert(unsupported_ops_xpu_fp16.begin(),
                                unsupported_ops_xpu_fp16.end());
  auto unsupported_ops_xpu_bf16 = std::get<2>(
      OpSupportedInfos("XPU", paddle::framework::proto::VarType::BF16));
  unsupported_bf16_ops_->insert(unsupported_ops_xpu_bf16.begin(),
                                unsupported_ops_xpu_bf16.end());
Q
qipengh 已提交
155 156 157 158 159 160 161 162 163
#elif defined(PADDLE_WITH_MLU)
  auto unsupported_ops_mlu_fp16 = std::get<2>(
      OpSupportedInfos("MLU", paddle::framework::proto::VarType::FP16));
  unsupported_fp16_ops_->insert(unsupported_ops_mlu_fp16.begin(),
                                unsupported_ops_mlu_fp16.end());
  auto unsupported_ops_mlu_bf16 = std::get<2>(
      OpSupportedInfos("MLU", paddle::framework::proto::VarType::BF16));
  unsupported_bf16_ops_->insert(unsupported_ops_mlu_bf16.begin(),
                                unsupported_ops_mlu_bf16.end());
L
Leo Chen 已提交
164 165
#endif
  VLOG(4) << allow_ops_->size() << " " << block_ops_->size() << " "
166 167
          << unsupported_fp16_ops_->size() << " "
          << unsupported_bf16_ops_->size();
168 169
}

170 171 172 173 174 175 176
AmpOperators::~AmpOperators() {}

AmpOperators& AmpOperators::Instance() {
  static AmpOperators instance;
  return instance;
}

177 178
std::shared_ptr<std::unordered_set<std::string>>
AmpOperators::GetMutableAllowOps() {
179 180 181
  return allow_ops_;
}

182 183
std::shared_ptr<std::unordered_set<std::string>>
AmpOperators::GetMutableBlockOps() {
184 185 186
  return block_ops_;
}

187 188 189 190 191
std::shared_ptr<std::unordered_set<std::string>>
AmpOperators::GetMutableUnsupportedFp16Ops() {
  return unsupported_fp16_ops_;
}

192 193 194 195 196
std::shared_ptr<std::unordered_set<std::string>>
AmpOperators::GetMutableUnsupportedBf16Ops() {
  return unsupported_bf16_ops_;
}

197 198 199 200 201 202 203 204 205 206
void AmpOperators::AddToAmpOpList(const std::string& op_name) {
  if (FLAGS_low_precision_op_list) {
    current_amp_ops_[op_name] += 1;
  }
}

std::map<const std::string, int> AmpOperators::GetAmpOpList() {
  return current_amp_ops_;
}

207 208 209
std::ostream& operator<<(std::ostream& os, AmpOperators& ops) {
  os << "allow ops: ";
  auto allow_ops = ops.GetMutableAllowOps();
210 211
  std::copy((*allow_ops).begin(),
            (*allow_ops).end(),
212
            std::ostream_iterator<std::string>(os, " "));
213
  os << "\n";
214 215
  os << "block ops: ";
  auto block_ops = ops.GetMutableBlockOps();
216 217
  std::copy((*block_ops).begin(),
            (*block_ops).end(),
218
            std::ostream_iterator<std::string>(os, " "));
219 220 221
  os << "\n";
  os << "unsupported fp16 ops: ";
  auto unsupported_fp16_ops = ops.GetMutableUnsupportedFp16Ops();
222 223
  std::copy((*unsupported_fp16_ops).begin(),
            (*unsupported_fp16_ops).end(),
224
            std::ostream_iterator<std::string>(os, " "));
225 226 227
  os << "\n";
  os << "unsupported bf16 ops: ";
  auto unsupported_bf16_ops = ops.GetMutableUnsupportedBf16Ops();
228 229
  std::copy((*unsupported_bf16_ops).begin(),
            (*unsupported_bf16_ops).end(),
230
            std::ostream_iterator<std::string>(os, " "));
231 232 233
  return os;
}

J
Jiabin Yang 已提交
234 235 236
template <typename VarType>
inline std::string GetDtypeStr(const std::shared_ptr<VarType>& var) {
  return framework::DataTypeToString(GetDataType<VarType>(var));
237
}
J
Jiabin Yang 已提交
238 239 240 241 242 243
template <typename VarType>
inline bool NeedCast(const std::shared_ptr<VarType>& var) {
  auto place = GetPlace(var);
  auto data_type = GetDataType<VarType>(var);
  if (paddle::platform::is_gpu_place(place) ||
      paddle::platform::is_cuda_pinned_place(place) ||
F
furnace 已提交
244
      paddle::platform::is_xpu_place(place) ||
Q
qipengh 已提交
245
      paddle::platform::is_mlu_place(place) ||
246
      paddle::platform::is_custom_place(place) ||
F
furnace 已提交
247 248
      paddle::platform::is_npu_place(place) ||
      paddle::platform::is_npu_pinned_place(place)) {
L
Leo Chen 已提交
249
    // CudaPinndePlace is added for varbase created by dataloader
J
Jiabin Yang 已提交
250
    if (data_type == paddle::framework::proto::VarType::FP32 ||
251 252
        data_type == paddle::framework::proto::VarType::FP16 ||
        data_type == paddle::framework::proto::VarType::BF16) {
L
Leo Chen 已提交
253 254
      return true;
    }
255
  }
L
Leo Chen 已提交
256
  return false;
257 258 259 260
}

// NOTE: Trace a cast op, so if a var is casted from fp32 to fp16, then the grad
// var will be cast back from fp16 to fp32 during backward phase.
J
Jiabin Yang 已提交
261 262 263
template <typename VarType>
static inline std::shared_ptr<VarType> CastToType(
    const std::shared_ptr<VarType>& var,
264 265
    const framework::proto::VarType::Type dst_type) {
  const auto& tracer = imperative::GetCurrentTracer();
J
Jiabin Yang 已提交
266 267
  imperative::NameVarMap<VarType> ins = {{"X", {var}}};
  framework::AttributeMap attrs = {{"in_dtype", GetDataType<VarType>(var)},
268
                                   {"out_dtype", dst_type}};
J
Jiabin Yang 已提交
269 270 271
  auto out =
      std::shared_ptr<VarType>(new VarType(tracer->GenerateUniqueName()));
  imperative::NameVarMap<VarType> outs = {{"Out", {out}}};
272 273

  {
L
Leo Chen 已提交
274
    AutoCastGuard guard(tracer, AmpLevel::O0);
275 276 277 278 279
    tracer->TraceOp("cast", ins, outs, std::move(attrs));
  }

  return out;
}
J
Jiabin Yang 已提交
280 281 282
template <typename VarType>
static inline std::shared_ptr<VarType> CastToFP16(
    const std::shared_ptr<VarType>& var) {
283
  auto dst_type = framework::proto::VarType::FP16;
J
Jiabin Yang 已提交
284
  if (NeedCast(var) && (GetDataType<VarType>(var) != dst_type)) {
285 286 287 288 289
    return CastToType(var, dst_type);
  }
  return var;
}

J
Jiabin Yang 已提交
290 291 292
template <typename VarType>
static inline std::shared_ptr<VarType> CastToFP32(
    const std::shared_ptr<VarType>& var) {
293
  auto dst_type = framework::proto::VarType::FP32;
J
Jiabin Yang 已提交
294
  if (NeedCast(var) && (GetDataType<VarType>(var) != dst_type)) {
295 296 297 298 299
    return CastToType(var, dst_type);
  }
  return var;
}

300 301 302 303 304 305 306 307 308 309
template <typename VarType>
static inline std::shared_ptr<VarType> CastToBF16(
    const std::shared_ptr<VarType>& var) {
  auto dst_type = framework::proto::VarType::BF16;
  if (NeedCast(var) && (GetDataType<VarType>(var) != dst_type)) {
    return CastToType(var, dst_type);
  }
  return var;
}

J
Jiabin Yang 已提交
310
template <typename VarType>
311
static inline framework::proto::VarType::Type GetPromoteType(
312 313
    const std::string& op_type,
    const NameVarMap<VarType>& ins,
314 315
    const framework::proto::VarType::Type amp_dtype) {
  auto dst_type = amp_dtype;
316 317
  for (const auto& pair : ins) {
    for (const auto& var : pair.second) {
J
Jiabin Yang 已提交
318 319
      if (GetDataType<VarType>(var) == framework::proto::VarType::FP32) {
        dst_type = GetDataType<VarType>(var);
320 321 322 323
        break;
      }
    }
  }
C
cc 已提交
324 325 326 327 328

  // NOTE(juncai): moving_average_abs_max_scale only consider the
  // dtype of input(X)
  if (op_type == "moving_average_abs_max_scale") {
    for (const auto& pair : ins) {
329 330
      if (pair.first == "X" && GetDataType<VarType>(pair.second.front()) ==
                                   framework::proto::VarType::FP16) {
C
cc 已提交
331 332 333 334 335
        dst_type = framework::proto::VarType::FP16;
      }
    }
  }

336 337 338
  return dst_type;
}

J
Jiabin Yang 已提交
339 340 341 342
template <typename VarType>
NameVarMap<VarType> AutoCastInputs(const std::string& op_type,
                                   const NameVarMap<VarType>& ins) {
  NameVarMap<VarType> new_ins(ins);
343 344 345
  if (AmpOperators::Instance().GetMutableAllowOps()->count(op_type)) {
    for (auto& pair : new_ins) {
      // NOTE(zhiqiu): batch_norm and layer_norm support only input x is fp16.
346 347
      if ((op_type == "batch_norm" || op_type == "layer_norm" ||
           op_type == "sync_batch_norm") &&
348 349 350 351
          pair.first != "X") {
        continue;
      }

352 353 354 355 356 357 358 359
      if ((op_type == "fused_attention" || op_type == "fused_feedforward")) {
        if (pair.first == "LnScale" || pair.first == "LnBias" ||
            pair.first == "Ln2Scale" || pair.first == "Ln2Bias" ||
            pair.first == "Ln1Scale" || pair.first == "Ln1Bias") {
          continue;
        }
      }

360 361
      VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
              << GetDtypeStr(*pair.second.cbegin()) << " to float16";
362
      for (auto& var : pair.second) {
J
Jiabin Yang 已提交
363
        var = CastToFP16<VarType>(var);
364 365 366
      }
    }
    return new_ins;
Z
zhangbo9674 已提交
367 368 369
  } else if (AmpOperators::Instance().GetMutableBlockOps()->count(op_type) ||
             AmpOperators::Instance().GetMutableUnsupportedFp16Ops()->count(
                 op_type)) {
370
    for (auto& pair : new_ins) {
371 372
      VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
              << GetDtypeStr(*pair.second.cbegin()) << " to float";
373
      for (auto& var : pair.second) {
J
Jiabin Yang 已提交
374
        var = CastToFP32<VarType>(var);
375 376 377 378
      }
    }
    return new_ins;
  } else {
379 380
    auto dst_type =
        GetPromoteType<VarType>(op_type, ins, framework::proto::VarType::FP16);
C
cc 已提交
381

382 383 384 385 386 387
    // NOTE(zhiqiu): if the op has op fp16 kernel, fall back to fp32.
    if (dst_type == framework::proto::VarType::FP16 &&
        AmpOperators::Instance().GetMutableUnsupportedFp16Ops()->count(
            op_type)) {
      dst_type = framework::proto::VarType::FP32;
    }
388 389
    for (auto& pair : new_ins) {
      // NOTE(zhiqiu): batch_norm and layer_norm support only input x is fp16.
390 391
      if ((op_type == "batch_norm" || op_type == "layer_norm" ||
           op_type == "sync_batch_norm") &&
392 393 394
          pair.first == "X" && dst_type == framework::proto::VarType::FP32) {
        continue;
      }
395 396 397 398 399 400 401 402
      if ((op_type == "fused_attention" || op_type == "fused_feedforwad") &&
          dst_type == framework::proto::VarType::FP32) {
        if (pair.first != "LnScale" && pair.first != "LnBias" &&
            pair.first != "Ln2Scale" && pair.first != "Ln2Bias" &&
            pair.first != "Ln1Scale" && pair.first != "Ln1Bias") {
          continue;
        }
      }
403 404 405
      VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
              << GetDtypeStr(*pair.second.cbegin()) << " to "
              << framework::DataTypeToString(dst_type);
406
      for (auto& var : pair.second) {
J
Jiabin Yang 已提交
407 408 409
        var = (dst_type == framework::proto::VarType::FP32
                   ? CastToFP32<VarType>(var)
                   : CastToFP16<VarType>(var));
410 411 412 413
      }
    }
    return new_ins;
  }
414
  return new_ins;
415
}
J
Jiabin Yang 已提交
416 417
template NameVarMap<VarBase> AutoCastInputs<VarBase>(
    const std::string& op_type, const NameVarMap<VarBase>& ins);
418 419
template NameVarMap<egr::EagerVariable> AutoCastInputs<egr::EagerVariable>(
    const std::string& op_type, const NameVarMap<egr::EagerVariable>& ins);
J
Jiabin Yang 已提交
420 421 422 423
template <typename VarType>
NameVarMap<VarType> CastPureFp16Inputs(const std::string& op_type,
                                       const NameVarMap<VarType>& ins) {
  NameVarMap<VarType> new_ins(ins);
424 425 426 427 428 429
  auto dst_type = framework::proto::VarType::FP16;
  if (AmpOperators::Instance().GetMutableUnsupportedFp16Ops()->count(op_type) ||
      AmpOperators::Instance().GetMutableBlockOps()->count(op_type)) {
    dst_type = framework::proto::VarType::FP32;
  }
  for (auto& pair : new_ins) {
430 431 432 433 434 435 436
    // NOTE: The run_program OP only has FP32 kernel. In dy2stat pure fp16
    // training, we have correctly cast the inputs of run_program OP before,
    // so here should avoid casting for run_program OP.
    if (op_type == "run_program") {
      continue;
    }

437 438 439 440 441
    if ((op_type == "batch_norm" || op_type == "layer_norm" ||
         op_type == "sync_batch_norm") &&
        pair.first != "X") {
      continue;
    }
Z
zhangkaihuo 已提交
442 443 444 445 446 447 448
    if ((op_type == "fused_attention" || op_type == "fused_feedforward")) {
      if (pair.first == "LnScale" || pair.first == "LnBias" ||
          pair.first == "Ln2Scale" || pair.first == "Ln2Bias" ||
          pair.first == "Ln1Scale" || pair.first == "Ln1Bias") {
        continue;
      }
    }
449 450 451 452
    VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
            << GetDtypeStr(*pair.second.cbegin()) << " to "
            << framework::DataTypeToString(dst_type);
    for (auto& var : pair.second) {
J
Jiabin Yang 已提交
453 454 455
      var = (dst_type == framework::proto::VarType::FP32
                 ? CastToFP32<VarType>(var)
                 : CastToFP16<VarType>(var));
456 457 458 459
    }
  }
  return new_ins;
}
J
Jiabin Yang 已提交
460 461
template NameVarMap<VarBase> CastPureFp16Inputs<VarBase>(
    const std::string& op_type, const NameVarMap<VarBase>& ins);
462 463
template NameVarMap<egr::EagerVariable> CastPureFp16Inputs<egr::EagerVariable>(
    const std::string& op_type, const NameVarMap<egr::EagerVariable>& ins);
464 465 466 467 468 469 470 471 472 473 474 475 476 477

template <typename VarType>
NameVarMap<VarType> AutoCastBF16Inputs(const std::string& op_type,
                                       const NameVarMap<VarType>& ins) {
  NameVarMap<VarType> new_ins(ins);
  if (AmpOperators::Instance().GetMutableAllowOps()->count(op_type)) {
    for (auto& pair : new_ins) {
      VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
              << GetDtypeStr(*pair.second.cbegin()) << " to bfloat16";
      for (auto& var : pair.second) {
        var = CastToBF16<VarType>(var);
      }
    }
    return new_ins;
478
  } else if (AmpOperators::Instance().GetMutableBlockOps()->count(op_type)) {
479 480 481 482 483 484 485 486
    for (auto& pair : new_ins) {
      VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
              << GetDtypeStr(*pair.second.cbegin()) << " to float";
      for (auto& var : pair.second) {
        var = CastToFP32<VarType>(var);
      }
    }
    return new_ins;
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
  } else {
    auto dst_type =
        GetPromoteType<VarType>(op_type, ins, framework::proto::VarType::BF16);
    // NOTE(zhangbo): if the op has op fp16 kernel, fall back to fp32.
    if (dst_type == framework::proto::VarType::BF16 &&
        AmpOperators::Instance().GetMutableUnsupportedBf16Ops()->count(
            op_type)) {
      dst_type = framework::proto::VarType::FP32;
    }
    for (auto& pair : new_ins) {
      VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
              << GetDtypeStr(*pair.second.cbegin()) << " to "
              << framework::DataTypeToString(dst_type);
      for (auto& var : pair.second) {
        var = (dst_type == framework::proto::VarType::FP32
                   ? CastToFP32<VarType>(var)
                   : CastToBF16<VarType>(var));
      }
    }
    return new_ins;
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
  }
  return new_ins;
}
template NameVarMap<VarBase> AutoCastBF16Inputs<VarBase>(
    const std::string& op_type, const NameVarMap<VarBase>& ins);
template NameVarMap<egr::EagerVariable> AutoCastBF16Inputs<egr::EagerVariable>(
    const std::string& op_type, const NameVarMap<egr::EagerVariable>& ins);

template <typename VarType>
NameVarMap<VarType> CastPureBf16Inputs(const std::string& op_type,
                                       const NameVarMap<VarType>& ins) {
  NameVarMap<VarType> new_ins(ins);
  auto dst_type = framework::proto::VarType::BF16;
  if (AmpOperators::Instance().GetMutableUnsupportedBf16Ops()->count(op_type) ||
      AmpOperators::Instance().GetMutableBlockOps()->count(op_type)) {
    dst_type = framework::proto::VarType::FP32;
  }
  for (auto& pair : new_ins) {
    VLOG(5) << "Op(" << op_type << "): Cast " << pair.first << " from "
            << GetDtypeStr(*pair.second.cbegin()) << " to "
            << framework::DataTypeToString(dst_type);
    for (auto& var : pair.second) {
      var = (dst_type == framework::proto::VarType::FP32
                 ? CastToFP32<VarType>(var)
                 : CastToBF16<VarType>(var));
    }
  }
  return new_ins;
}
template NameVarMap<VarBase> CastPureBf16Inputs<VarBase>(
    const std::string& op_type, const NameVarMap<VarBase>& ins);
template NameVarMap<egr::EagerVariable> CastPureBf16Inputs<egr::EagerVariable>(
    const std::string& op_type, const NameVarMap<egr::EagerVariable>& ins);

541 542
}  // namespace imperative
}  // namespace paddle