distributed_fused_lamb_op.cu 88.7 KB
Newer Older
1
// Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14
//
// 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 "paddle/fluid/operators/optimizers/multi_tensor_apply.h"
16
#include "paddle/fluid/platform/collective_helper.h"
17 18 19 20

#include "paddle/phi/backends/context_pool.h"
#include "paddle/phi/backends/gpu/gpu_launch_config.h"
#include "paddle/phi/common/amp_type_traits.h"
21
#include "paddle/phi/common/memory_utils.h"
22 23 24 25
#include "paddle/phi/core/cuda_stream.h"
#include "paddle/phi/core/dense_tensor.h"
#include "paddle/phi/core/enforce.h"
#include "paddle/phi/core/kernel_registry.h"
26
#include "paddle/phi/core/utils/data_type.h"
27
#include "paddle/phi/kernels/funcs/aligned_vector.h"
T
Thomas Young 已提交
28
#include "paddle/phi/kernels/funcs/tensor_to_string.h"
29
#include "paddle/utils/optional.h"
30 31 32 33 34 35 36 37

#ifdef __NVCC__
#include "cub/cub.cuh"
#include "math.h"  // NOLINT
#endif

#ifdef __HIPCC__
#include <hipcub/hipcub.hpp>
38

39 40 41 42
#include "math.h"  // NOLINT
namespace cub = hipcub;
#endif

43 44
namespace phi {
namespace fusion {
45 46

template <typename T>
47
using MasterT = typename phi::dtype::MPTypeTrait<T>::Type;
T
Thomas Young 已提交
48 49
using phi::funcs::FlattenToString;
using phi::funcs::ToVector;
50

51 52 53 54 55 56 57 58 59 60 61 62
template <typename T>
static void FillZeroWithPtr(T *x, size_t n, gpuStream_t stream) {
  static_assert(!std::is_same<T, void>::value, "T cannot be void.");
#ifdef PADDLE_WITH_HIP
  PADDLE_ENFORCE_GPU_SUCCESS(hipMemsetAsync(x, 0, n * sizeof(T), stream));
#else
  PADDLE_ENFORCE_GPU_SUCCESS(cudaMemsetAsync(x, 0, n * sizeof(T), stream));
#endif
}

template <typename T, int BlockDim, int VecSize>
struct L2NormFunctor {
63 64 65 66 67 68 69
  DEVICE void operator()(int tensor_id,
                         int chunk_id,
                         int offset,
                         int size,
                         const T *x,
                         MasterT<T> *y,
                         int max_chunk_num) const {
70 71 72 73 74 75 76 77 78 79
    using MT = MasterT<T>;
    const T *ptr = x + offset;

    using BlockReduce = cub::BlockReduce<MT, BlockDim>;
    __shared__ typename BlockReduce::TempStorage storage;

    MT square_sum = static_cast<MT>(0);
    int i;
    for (i = threadIdx.x * VecSize; i + VecSize <= size;
         i += (BlockDim * VecSize)) {
80 81
      phi::AlignedVector<T, VecSize> tmp_vec;
      phi::Load(ptr + i, &tmp_vec);
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
#pragma unroll
      for (int j = 0; j < VecSize; ++j) {
        auto tmp = static_cast<MT>(tmp_vec[j]);
        square_sum += (tmp * tmp);
      }
    }

    for (; i < size; ++i) {
      auto tmp = static_cast<MT>(ptr[i]);
      square_sum += (tmp * tmp);
    }

    square_sum = BlockReduce(storage).Reduce(square_sum, cub::Sum());
    if (threadIdx.x == 0) {
      y[tensor_id * max_chunk_num + chunk_id] = square_sum;
    }
  }
};

101
template <typename InT, typename OutT, int BlockDim>
102 103 104 105 106 107 108 109 110 111 112 113
static __global__ void MultiTensorL2NormReduceAgainCUDAKernel(
    const InT *x, OutT *y, int max_chunk_num) {
  int tensor_id = blockIdx.x;
  x += (tensor_id * max_chunk_num);
  using BlockReduce = cub::BlockReduce<InT, BlockDim>;
  __shared__ typename BlockReduce::TempStorage storage;
  InT sum = static_cast<InT>(0);
  for (int i = threadIdx.x; i < max_chunk_num; i += BlockDim) {
    sum += x[i];
  }
  sum = BlockReduce(storage).Reduce(sum, cub::Sum());
  if (threadIdx.x == 0) {
114
    y[blockIdx.x] = static_cast<OutT>(sum);
115 116 117 118 119 120 121 122 123 124
  }
}

template <typename T>
static int GetChunkedVecSize(const T *ptr, int chunk_size) {
  static_assert(!std::is_same<T, void>::value, "T cannot be void.");

  constexpr int max_load_bits = 128;
  int valid_vec_size = max_load_bits / CHAR_BIT / sizeof(T);
  auto address = reinterpret_cast<uintptr_t>(ptr);
125 126 127
  constexpr int vec8 = alignof(phi::AlignedVector<T, 8>);
  constexpr int vec4 = alignof(phi::AlignedVector<T, 4>);
  constexpr int vec2 = alignof(phi::AlignedVector<T, 2>);
128
  chunk_size *= sizeof(T);
129 130 131 132 133 134 135 136 137 138 139
  if (address % vec8 == 0 && chunk_size % vec8 == 0) {
    return std::min(8, valid_vec_size);
  } else if (address % vec4 == 0 && chunk_size % vec4 == 0) {
    return std::min(4, valid_vec_size);
  } else if (address % vec2 == 0 && chunk_size % vec2 == 0) {
    return std::min(2, valid_vec_size);
  } else {
    return 1;
  }
}

140 141 142 143 144
#define PD_VEC_LAUNCH_KERNEL_CASE(__vec_size, ...) \
  case __vec_size: {                               \
    constexpr int kVecSize = __vec_size;           \
    __VA_ARGS__;                                   \
    break;                                         \
145 146
  }

147 148 149 150 151 152 153 154
#define PD_VEC_LAUNCH_KERNEL(__vec_size, ...)    \
  do {                                           \
    switch (__vec_size) {                        \
      PD_VEC_LAUNCH_KERNEL_CASE(8, __VA_ARGS__); \
      PD_VEC_LAUNCH_KERNEL_CASE(4, __VA_ARGS__); \
      PD_VEC_LAUNCH_KERNEL_CASE(2, __VA_ARGS__); \
      PD_VEC_LAUNCH_KERNEL_CASE(1, __VA_ARGS__); \
    }                                            \
155 156 157
  } while (0)

// TODO(zengjinle): which chunk_size is better?
158 159 160
template <typename InT,
          typename OutT,
          int MaxTensorNumPerLaunch = 160,
161
          int MaxChunkNumPerLaunch = 780>
162
static void MultiTensorL2Norm(const phi::GPUPlace &place,
163 164 165 166 167
                              gpuStream_t stream,
                              const InT *x,
                              const int *offsets,
                              int n,
                              OutT *y,
168 169 170 171 172
                              int chunk_size = 65536) {
  if (n <= 0) return;

  constexpr int kNumTensor = MaxTensorNumPerLaunch;
  constexpr int kNumChunk = MaxChunkNumPerLaunch;
173 174 175
#ifdef PADDLE_WITH_HIP
  constexpr int kBlockDim = 256;
#else
176
  constexpr int kBlockDim = 512;
177
#endif
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

  int max_chunk_num = -1;
  int vec_size = 8;
  int total_chunk_num = 0;
  for (int i = 0; i < n; ++i) {
    vec_size = std::min(
        vec_size, GetChunkedVecSize(x + offsets[i] - offsets[0], chunk_size));
    int length = offsets[i + 1] - offsets[i];
    auto tmp_chunk_num = (length + chunk_size - 1) / chunk_size;
    max_chunk_num = std::max(max_chunk_num, tmp_chunk_num);
    total_chunk_num += tmp_chunk_num;
  }

  VLOG(1) << "MultiTensorL2Norm max_chunk_num = " << max_chunk_num
          << " , total_chunk_num = " << total_chunk_num
          << " , tensor_num = " << n;

  using MT = MasterT<InT>;
196
  memory_utils::Buffer tmp_out(place);
197 198 199
  auto *tmp_out_ptr = tmp_out.Alloc<MT>(n * max_chunk_num);
  FillZeroWithPtr(tmp_out_ptr, n * max_chunk_num, stream);

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
#define PD_LAUNCH_MULTI_TENSOR_APPLY_L2_NORM_KERNEL                       \
  do {                                                                    \
    using FunctorT = L2NormFunctor<InT, kBlockDim, kVecSize>;             \
    VLOG(10) << __func__ << " " << typeid(InT).name()                     \
             << " VecSize = " << kVecSize;                                \
    paddle::operators::MultiTensorApply<FunctorT, kNumTensor, kNumChunk>( \
        FunctorT(),                                                       \
        stream,                                                           \
        offsets,                                                          \
        n,                                                                \
        chunk_size,                                                       \
        kBlockDim,                                                        \
        x,                                                                \
        tmp_out_ptr,                                                      \
        max_chunk_num);                                                   \
215 216
  } while (0)

217 218
  PD_VEC_LAUNCH_KERNEL(vec_size, PD_LAUNCH_MULTI_TENSOR_APPLY_L2_NORM_KERNEL);
#undef PD_LAUNCH_MULTI_TENSOR_APPLY_L2_NORM_KERNEL
219

220 221
  MultiTensorL2NormReduceAgainCUDAKernel<MT, OutT, kBlockDim>
      <<<n, kBlockDim, 0, stream>>>(tmp_out_ptr, y, max_chunk_num);
222 223
}

224 225
template <int LogLevel>
static void LogParamAndTrustRatioDivSquareNorm(
226 227
    const std::vector<const DenseTensor *> &param,
    const DenseTensor &order,
228
    const float *param_square_norm,
229 230 231
    const float *trust_ratio_div_square_norm) {
  if (!VLOG_IS_ON(LogLevel)) return;

232
  if (param.empty()) return;
233

234
  const auto *order_data = order.data<int>();
235

236 237
  size_t n = param.size();
  auto place = param[0]->place();
238 239 240 241

  auto pn_vec = ToVector(param_square_norm, n, place);
  auto tn_vec = ToVector(trust_ratio_div_square_norm, n, place);

242
  for (size_t i = 0; i < n; ++i) {
243 244 245 246
    auto idx = order_data[i];
    VLOG(LogLevel) << "Param " << param[idx]->dtype() << " "
                   << param[idx]->name() << " pn = " << pn_vec[i]
                   << " , tn = " << tn_vec[i];
247 248 249
  }
}

L
Leo Chen 已提交
250
static bool IsFinite(const phi::GPUContext &dev_ctx, const float *ptr) {
251 252 253
  auto stream = dev_ctx.stream();
  float cpu_value;
#ifdef PADDLE_WITH_HIP
254 255
  PADDLE_ENFORCE_GPU_SUCCESS(hipMemcpyAsync(
      &cpu_value, ptr, sizeof(float), hipMemcpyDeviceToHost, stream));
256 257
  PADDLE_ENFORCE_GPU_SUCCESS(hipStreamSynchronize(stream));
#else
258 259
  PADDLE_ENFORCE_GPU_SUCCESS(cudaMemcpyAsync(
      &cpu_value, ptr, sizeof(float), cudaMemcpyDeviceToHost, stream));
260 261 262 263 264 265 266
  PADDLE_ENFORCE_GPU_SUCCESS(cudaStreamSynchronize(stream));
#endif
  LOG(INFO) << "NAN_INF indicator value: " << cpu_value;
  return isfinite(cpu_value);
}

template <typename T>
267
static const T *GetInputTensorPtr(const DenseTensor *in_tensor,
268 269
                                  const char *in_name,
                                  int64_t *numel = nullptr) {
270 271
  PADDLE_ENFORCE_NOT_NULL(
      in_tensor,
272
      phi::errors::InvalidArgument("Input(%s) cannot be NULL.", in_name));
273
  if (in_tensor->initialized()) {
274 275 276 277 278 279 280 281
    if (numel) *numel = in_tensor->numel();
    return in_tensor->data<T>();
  } else {
    if (numel) *numel = 0;
    return nullptr;
  }
}

282 283 284 285
template <typename T, typename Context, bool AllowNotExist = false>
static T *GetSameInOutTensorPtr(const Context &dev_ctx,
                                const DenseTensor *in_tensor,
                                DenseTensor *out_tensor,
286 287
                                const char *in_name,
                                const char *out_name,
288
                                int64_t *numel = nullptr) {
289
  if (in_tensor == nullptr || !in_tensor->initialized()) {
290 291 292 293
    PADDLE_ENFORCE_EQ(
        AllowNotExist,
        true,
        phi::errors::InvalidArgument("Input(%s) cannot be NULL.", in_name));
294 295 296 297
    if (numel) *numel = 0;
    return nullptr;
  }

298 299
  PADDLE_ENFORCE_NOT_NULL(
      in_tensor,
300 301 302 303
      phi::errors::InvalidArgument("Input(%s) cannot be NULL.", in_name));
  PADDLE_ENFORCE_NOT_NULL(
      out_tensor,
      phi::errors::InvalidArgument("Output(%s) cannot be NULL.", out_name));
304
  const T *in_data = in_tensor->data<T>();
305 306

  T *out_data = dev_ctx.template Alloc<T>(out_tensor);
307 308
  PADDLE_ENFORCE_EQ(in_data,
                    out_data,
309
                    phi::errors::InvalidArgument(
310
                        "Input(%s) and Output(%s) must be the same Tensor.",
311 312
                        in_name,
                        out_name));
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
  if (numel) *numel = out_tensor->numel();
  return out_data;
}

template <typename T>
struct SquareFunctor {
  HOSTDEVICE MasterT<T> operator()(T x) const {
    auto y = static_cast<MasterT<T>>(x);
    return y * y;
  }
};

template <typename T>
struct IsNanInfFunctor {
  HOSTDEVICE bool operator()(T x) const { return !isfinite(x); }
};

struct OrFunctor {
  HOSTDEVICE bool operator()(bool x, bool y) const { return x || y; }
};

struct AndFunctor {
  HOSTDEVICE bool operator()(bool x, bool y) const { return x && y; }
};

S
sneaxiy 已提交
338
template <typename T1, typename T2, int VecSize>
339 340
static __global__ void ScaleCUDAKernel(const T1 *__restrict__ x,
                                       const T2 *__restrict__ scale,
341 342
                                       T1 *__restrict__ y,
                                       int num) {
343 344 345
  static_assert(sizeof(T1) <= sizeof(T2),
                "sizeof(T1) must be not greater than sizeof(T2).");
  T2 s = scale[0];
S
sneaxiy 已提交
346 347 348 349 350

  int i = (threadIdx.x + blockIdx.x * blockDim.x) * VecSize;
  int stride = blockDim.x * gridDim.x * VecSize;

  for (; i + VecSize <= num; i += stride) {
351 352
    phi::AlignedVector<T1, VecSize> x_vec;
    phi::AlignedVector<T1, VecSize> y_vec;
S
sneaxiy 已提交
353

354
    phi::Load(x + i, &x_vec);
S
sneaxiy 已提交
355 356 357 358
#pragma unroll
    for (int j = 0; j < VecSize; ++j) {
      y_vec[j] = static_cast<T1>(static_cast<T2>(x_vec[j]) * s);
    }
359
    phi::Store(y_vec, y + i);
S
sneaxiy 已提交
360 361 362
  }

  for (; i < num; ++i) {
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
    y[i] = static_cast<T1>(static_cast<T2>(x[i]) * s);
  }
}

template <typename T>
static __global__ void AddToCUDAKernel(const T *__restrict__ x,
                                       T *__restrict__ y) {
  y[0] += x[0];
}

// If clip before allreduce,
// coeff = global_scale * max_global_grad_norm / (1e-6 + sqrt(square_grad_norm)
// * rescale_grad)
// if coeff >= 1 or coeff is Nan/Inf, scale = 1.0
// else scale = coeff
template <typename T1, typename T2>
static __global__ void CalcGradNormClipBeforeAllReduceScale(
380 381 382 383 384 385
    const T1 *__restrict__ global_scale,
    T1 max_global_grad_norm,
    const T1 *__restrict__ square_grad_norm,
    T1 *__restrict__ out1,
    T2 *__restrict__ out2,
    T1 clip_rescale_grad) {
386
  T1 grad_norm = static_cast<T1>(sqrtf(*square_grad_norm)) * clip_rescale_grad;
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  T1 scale = global_scale[0] * max_global_grad_norm / (1e-6 + grad_norm);
  bool found_nan_inf = !isfinite(scale);
  if (scale >= 1 || found_nan_inf) {
    scale = static_cast<T1>(1.0);
  }

  if (out1) {
    *out1 = scale;
  }
  if (out2) {
    *out2 = static_cast<T2>(scale);
  }
}

static __global__ void SetNanInfValueCUDAKernelOneFlag(const bool *in_flag_p,
                                                       float *out_p) {
  *out_p = (*in_flag_p) ? __int_as_float(0x7fffffffU) : 0.0f;
}

static __global__ void SetNanInfValueCUDAKernelTwoFlag(const bool *in_flag_p_1,
                                                       const bool *in_flag_p_2,
                                                       float *out_p) {
  *out_p =
      ((*in_flag_p_1) || (*in_flag_p_2)) ? __int_as_float(0x7fffffffU) : 0.0f;
}

413 414
template <typename T, typename GradT, int VecSize>
static __global__ void UpdateLambMomentAndTrustRatioDivCUDAKernel(
415 416
    const T *__restrict__ param_p,
    const GradT *__restrict__ grad_p,
417
    const T *__restrict__ square_grad_norm_p,
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    const T *__restrict__ global_scale,
    const T *__restrict__ beta1pow_p,
    const T *__restrict__ beta2pow_p,
    T *__restrict__ mom1_p,
    T *__restrict__ mom2_p,
    T *__restrict__ trust_ratio_div_p,
    bool *__restrict__ found_inf,
    int64_t *__restrict__ step,
    T weight_decay,
    int weight_decay_end_numel,
    T beta1,
    T beta2,
    T epsilon,
    T max_global_grad_norm,
    int num,
    T rescale_grad) {
434
  T square_grad_norm = *square_grad_norm_p;
435 436 437 438 439 440 441
  bool need_update_found_inf =
      (found_inf && threadIdx.x == 0 && blockIdx.x == 0);
  if (!isfinite(square_grad_norm)) {
    if (need_update_found_inf) *found_inf = true;
    return;
  } else if (need_update_found_inf) {
    *found_inf = false;
442
    ++(*step);
443
  }
444 445 446 447 448 449 450 451 452 453 454 455 456

  T scale = rescale_grad / global_scale[0];
  if (max_global_grad_norm > 0) {
    T clip_scale =
        max_global_grad_norm / (sqrtf(square_grad_norm) * scale + 1e-6);
    if (clip_scale < static_cast<T>(1)) {
      scale *= clip_scale;
    }
  }

  T one_minus_beta1pow = 1 - beta1pow_p[0];
  T one_minus_beta2pow = 1 - beta2pow_p[0];

457 458 459 460
  int i = (threadIdx.x + blockIdx.x * blockDim.x) * VecSize;
  int stride = blockDim.x * gridDim.x * VecSize;

  for (; i + VecSize <= num; i += stride) {
461 462 463 464 465
    phi::AlignedVector<T, VecSize> param_vec;
    phi::AlignedVector<GradT, VecSize> grad_vec;
    phi::AlignedVector<T, VecSize> mom1_vec;
    phi::AlignedVector<T, VecSize> mom2_vec;
    phi::AlignedVector<T, VecSize> trust_ratio_div_vec;
466 467 468

    T cur_weight_decay = (i < weight_decay_end_numel) * weight_decay;
    if (cur_weight_decay != static_cast<T>(0.0)) {
469
      phi::Load(param_p + i, &param_vec);
470 471 472 473 474 475
    } else {
#pragma unroll
      for (int j = 0; j < VecSize; ++j) {
        param_vec[j] = static_cast<T>(0);
      }
    }
476 477 478
    phi::Load(grad_p + i, &grad_vec);
    phi::Load(mom1_p + i, &mom1_vec);
    phi::Load(mom2_p + i, &mom2_vec);
479

480 481
#define PD_LAMB_MOM_TRUST_RATIO_DIV_UPDATE(                                    \
    __param, __grad, __mom1, __mom2, __trust_ratio_div, __idx)                 \
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
  T p = __param[__idx];                                                        \
  T g = static_cast<T>(__grad[__idx]) * scale;                                 \
  T mom1 = __mom1[__idx];                                                      \
  T mom2 = __mom2[__idx];                                                      \
  mom1 = beta1 * mom1 + (1 - beta1) * g;                                       \
  mom2 = beta2 * mom2 + (1 - beta2) * g * g;                                   \
  T mom1_unbiased = mom1 / one_minus_beta1pow;                                 \
  T mom2_unbiased = mom2 / one_minus_beta2pow;                                 \
  __trust_ratio_div[__idx] =                                                   \
      mom1_unbiased / (sqrtf(mom2_unbiased) + epsilon) + cur_weight_decay * p; \
  __mom1[__idx] = mom1;                                                        \
  __mom2[__idx] = mom2;

#pragma unroll
    for (int j = 0; j < VecSize; ++j) {
497 498
      PD_LAMB_MOM_TRUST_RATIO_DIV_UPDATE(
          param_vec, grad_vec, mom1_vec, mom2_vec, trust_ratio_div_vec, j);
499 500
    }

501 502 503
    phi::Store(mom1_vec, mom1_p + i);
    phi::Store(mom2_vec, mom2_p + i);
    phi::Store(trust_ratio_div_vec, trust_ratio_div_p + i);
504 505 506 507
  }

  for (; i < num; ++i) {
    T cur_weight_decay = (i < weight_decay_end_numel) * weight_decay;
508 509
    PD_LAMB_MOM_TRUST_RATIO_DIV_UPDATE(
        param_p, grad_p, mom1_p, mom2_p, trust_ratio_div_p, i);
510 511 512
  }
}

513 514
template <typename T, typename GradT>
static void MultiTensorUpdateLambMomentAndTrustRatioDiv(
L
Leo Chen 已提交
515
    const phi::GPUContext &dev_ctx,
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    const int *offsets,
    int n,
    const T *param_p,
    const GradT *grad_p,
    const T *square_grad_norm_p,
    const T *global_scale,
    const T *beta1pow_p,
    const T *beta2pow_p,
    T *mom1_p,
    T *mom2_p,
    T *trust_ratio_div_p,
    bool *found_inf_p,
    int64_t *step,
    T weight_decay,
    int weight_decay_end_idx,
    T beta1,
    T beta2,
    T epsilon,
    T max_global_grad_norm,
    T rescale_grad) {
536 537
  if (n <= 0) return;
  int numel = offsets[n] - offsets[0];
538 539
  PADDLE_ENFORCE_GE(weight_decay_end_idx,
                    0,
540
                    phi::errors::InvalidArgument(
541
                        "The weight decay end index should be >= 0."));
542 543
  PADDLE_ENFORCE_LE(weight_decay_end_idx,
                    n,
544
                    phi::errors::InvalidArgument(
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
                        "The weight decay end index should be < %d.", n));
  auto weight_decay_end_numel = offsets[weight_decay_end_idx] - offsets[0];

  int vec_size = GetChunkedVecSize(param_p, 0);
  vec_size = std::min(vec_size, GetChunkedVecSize(grad_p, 0));
  vec_size = std::min(vec_size, GetChunkedVecSize(mom1_p, 0));
  vec_size = std::min(vec_size, GetChunkedVecSize(mom2_p, 0));
  vec_size = std::min(vec_size, GetChunkedVecSize(trust_ratio_div_p, 0));
  for (int i = 0; i < n; ++i) {
    auto length = offsets[i + 1] - offsets[i];
    while (length % vec_size != 0) {
      vec_size /= 2;
    }
  }

  VLOG(1) << __func__ << " VecSize = " << vec_size;

  auto stream = dev_ctx.stream();
563 564
  auto config =
      phi::backends::gpu::GetGpuLaunchConfig1D(dev_ctx, numel, vec_size);
565 566
  if (found_inf_p == nullptr) {
    PADDLE_ENFORCE_EQ(
567 568
        step,
        nullptr,
569
        phi::errors::InvalidArgument(
570 571
            "Output(Step) cannot be updated twice in one mini-batch."));
  } else {
572
    PADDLE_ENFORCE_NOT_NULL(
573
        step, phi::errors::InvalidArgument("Output(Step) cannot be nullptr."));
574
  }
575

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
#define PD_LAUNCH_LAMB_MOM_TRUST_RATIO_DIV_KERNEL                        \
  do {                                                                   \
    UpdateLambMomentAndTrustRatioDivCUDAKernel<T, GradT, kVecSize>       \
        <<<config.block_per_grid, config.thread_per_block, 0, stream>>>( \
            param_p,                                                     \
            grad_p,                                                      \
            square_grad_norm_p,                                          \
            global_scale,                                                \
            beta1pow_p,                                                  \
            beta2pow_p,                                                  \
            mom1_p,                                                      \
            mom2_p,                                                      \
            trust_ratio_div_p,                                           \
            found_inf_p,                                                 \
            step,                                                        \
            weight_decay,                                                \
            weight_decay_end_numel,                                      \
            beta1,                                                       \
            beta2,                                                       \
            epsilon,                                                     \
            max_global_grad_norm,                                        \
            numel,                                                       \
            rescale_grad);                                               \
599 600 601 602 603 604
  } while (0)

  PD_VEC_LAUNCH_KERNEL(vec_size, PD_LAUNCH_LAMB_MOM_TRUST_RATIO_DIV_KERNEL);
#undef PD_LAUNCH_LAMB_MOM_TRUST_RATIO_DIV_KERNEL
}

605 606 607
template <typename T, bool NeedUpdate /*=true*/>
struct LambBetaPowUpdateOnceHelper {
  LambBetaPowUpdateOnceHelper(T *beta1pow, T *beta2pow, T beta1, T beta2) {
608 609 610 611 612 613
    PADDLE_ENFORCE_NOT_NULL(
        beta1pow,
        phi::errors::InvalidArgument("The beta1pow should not be nullptr."));
    PADDLE_ENFORCE_NOT_NULL(
        beta2pow,
        phi::errors::InvalidArgument("The beta2pow should not be nullptr."));
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    beta1pow_ = beta1pow;
    beta2pow_ = beta2pow;
    beta1_ = beta1;
    beta2_ = beta2;
  }

  HOSTDEVICE void UpdateBetaPows() const {
    beta1pow_[0] *= beta1_;
    beta2pow_[0] *= beta2_;
  }

 private:
  T *__restrict__ beta1pow_;
  T *__restrict__ beta2pow_;
  T beta1_;
  T beta2_;
};

template <typename T>
struct LambBetaPowUpdateOnceHelper<T, false> {
  LambBetaPowUpdateOnceHelper(T *beta1pow, T *beta2pow, T beta1, T beta2) {
    PADDLE_ENFORCE_EQ(
636 637
        beta1pow,
        nullptr,
638
        phi::errors::InvalidArgument("The beta1pow should be nullptr."));
639
    PADDLE_ENFORCE_EQ(
640 641
        beta2pow,
        nullptr,
642
        phi::errors::InvalidArgument("The beta2pow should be nullptr."));
643 644 645 646 647 648 649 650 651
  }

  HOSTDEVICE void UpdateBetaPows() const {}
};

template <typename T, bool HasMasterParam /*=true*/>
struct LambParamHelper {
  LambParamHelper(T *param, MasterT<T> *master_param) {
    constexpr bool kIsSameType = std::is_same<T, MasterT<T>>::value;
652 653
    PADDLE_ENFORCE_EQ(kIsSameType,
                      false,
654
                      phi::errors::InvalidArgument(
655
                          "T must not be the same with MasterT<T>."));
656 657 658
    PADDLE_ENFORCE_NOT_NULL(
        master_param,
        phi::errors::InvalidArgument("Master parameter must be provided."));
659 660 661 662
    param_ = param;
    master_param_ = master_param;
  }

663
  HOSTDEVICE T *__restrict__ ParamPtr() { return param_; }
664

665
  HOSTDEVICE MasterT<T> *__restrict__ MasterParamPtr() { return master_param_; }
666 667 668 669 670 671 672 673 674 675

 private:
  T *__restrict__ param_;
  MasterT<T> *__restrict__ master_param_;
};

template <typename T>
struct LambParamHelper<T, false> {
  LambParamHelper(T *param, MasterT<T> *master_param) {
    constexpr bool kIsSameType = std::is_same<T, MasterT<T>>::value;
676 677 678 679
    PADDLE_ENFORCE_EQ(
        kIsSameType,
        true,
        phi::errors::InvalidArgument("T must be the same with MasterT<T>."));
680 681 682
    if (master_param != nullptr) {
      PADDLE_ENFORCE_EQ(static_cast<void *>(param),
                        static_cast<void *>(master_param),
683
                        phi::errors::InvalidArgument(
684 685 686 687 688 689
                            "Master parameter must be nullptr or the same as "
                            "non-master parameter."));
    }
    param_ = param;
  }

690
  HOSTDEVICE T *__restrict__ ParamPtr() { return param_; }
691

692
  HOSTDEVICE constexpr MasterT<T> *MasterParamPtr() { return nullptr; }
693 694 695 696 697

 private:
  T *__restrict__ param_;
};

698 699 700
template <typename ParamT,
          bool HasMasterParam,
          bool NeedUpdateBetaPow,
701 702 703
          int VecSize>
struct LambUpdateParamAndBetaPowsFunctor {
  DEVICE void operator()(
704 705 706 707
      int tensor_id,
      int chunk_id,
      int offset,
      int size,
708
      LambParamHelper<ParamT, HasMasterParam> param_helper,
709 710
      const MasterT<ParamT> *trust_ratio_div,
      const MasterT<ParamT> *lr,
711
      const MasterT<ParamT> *param_square_norm,
712 713
      const MasterT<ParamT> *trust_ratio_div_square_norm,
      const bool *found_inf,
714 715 716 717 718
      LambBetaPowUpdateOnceHelper<MasterT<ParamT>, NeedUpdateBetaPow>
          betapow_helper) const {
    if (*found_inf) return;

    using MT = MasterT<ParamT>;
719

720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
    MT p_square_norm = param_square_norm[tensor_id];
    MT t_square_norm = trust_ratio_div_square_norm[tensor_id];
    MT lr_value = *lr;
    MT ratio = (p_square_norm != static_cast<MT>(0) &&
                        t_square_norm != static_cast<MT>(0)
                    ? lr_value * sqrtf(p_square_norm / t_square_norm)
                    : lr_value);

    int i;
    int stride = blockDim.x * VecSize;

    ParamT *param = param_helper.ParamPtr() + offset;
    MT *master_param = HasMasterParam ? param_helper.MasterParamPtr() + offset
                                      : param_helper.MasterParamPtr();
    trust_ratio_div += offset;

    for (i = threadIdx.x * VecSize; i + VecSize <= size; i += stride) {
737 738
      phi::AlignedVector<MT, VecSize> trust_ratio_div_vec;
      phi::Load(trust_ratio_div + i, &trust_ratio_div_vec);
739
      if (HasMasterParam) {
740 741 742
        phi::AlignedVector<MT, VecSize> master_param_vec;
        phi::Load(master_param + i, &master_param_vec);
        phi::AlignedVector<ParamT, VecSize> param_vec;
743 744 745 746 747 748
#pragma unroll
        for (int j = 0; j < VecSize; ++j) {
          MT p = master_param_vec[j] - ratio * trust_ratio_div_vec[j];
          master_param_vec[j] = p;
          param_vec[j] = static_cast<ParamT>(p);
        }
749 750
        phi::Store(master_param_vec, master_param + i);
        phi::Store(param_vec, param + i);
751
      } else {
752 753
        phi::AlignedVector<ParamT, VecSize> param_vec;
        phi::Load(param + i, &param_vec);
754 755 756 757 758
#pragma unroll
        for (int j = 0; j < VecSize; ++j) {
          MT p = static_cast<MT>(param_vec[j]) - ratio * trust_ratio_div_vec[j];
          param_vec[j] = static_cast<ParamT>(p);
        }
759
        phi::Store(param_vec, param + i);
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
      }
    }

    for (; i < size; ++i) {
      if (HasMasterParam) {
        MT p = master_param[i] - ratio * trust_ratio_div[i];
        master_param[i] = p;
        param[i] = static_cast<ParamT>(p);
      } else {
        MT p = static_cast<MT>(param[i]) - ratio * trust_ratio_div[i];
        param[i] = static_cast<ParamT>(p);
      }
    }

    if (NeedUpdateBetaPow && threadIdx.x == 0 && blockIdx.x == 0) {
      betapow_helper.UpdateBetaPows();
776 777
    }
  }
778
};
779

780
// TODO(zengjinle): which block_dim and chunk_size would be better?
781 782
template <typename ParamT,
          int MaxTensorNumPerLaunch = 160,
783 784
          int MaxChunkNumPerLaunch = 780>
static void MultiTensorUpdateLambParamAndBetaPows(
L
Leo Chen 已提交
785
    const phi::GPUContext &dev_ctx,
786 787 788 789
    const int *offsets,
    int n,
    const MasterT<ParamT> *trust_ratio_div,
    const MasterT<ParamT> *lr,
790
    const MasterT<ParamT> *param_square_norm,
791 792 793 794 795 796 797 798
    const MasterT<ParamT> *trust_ratio_div_square_norm,
    const bool *found_inf,
    ParamT *param,
    MasterT<ParamT> *master_param,
    MasterT<ParamT> *beta1pow,
    MasterT<ParamT> *beta2pow,
    MasterT<ParamT> beta1,
    MasterT<ParamT> beta2,
799 800 801 802 803 804
    int chunk_size = 65536) {
  constexpr bool kHasMasterParam =
      !(std::is_same<ParamT, MasterT<ParamT>>::value);

  bool has_beta_pow = (beta1pow != nullptr);
  if (has_beta_pow) {
805 806
    PADDLE_ENFORCE_NOT_NULL(
        beta2pow,
807
        phi::errors::InvalidArgument("Beta2Pow should not be nullptr."));
808
  } else {
809
    PADDLE_ENFORCE_EQ(
810 811
        beta2pow,
        nullptr,
812
        phi::errors::InvalidArgument("Beta2Pow should be nullptr."));
813 814
  }

815 816 817
#ifdef PADDLE_WITH_HIP
  const int block_dim = 256;
#else
818
  const int block_dim = 512;
819
#endif
820

821 822 823 824 825 826 827 828 829 830 831 832
  int vec_size = 8;
  for (int i = 0; i < n; ++i) {
    int offset = offsets[i] - offsets[0];
    vec_size =
        std::min(vec_size, GetChunkedVecSize(param + offset, chunk_size));
    if (kHasMasterParam) {
      vec_size = std::min(vec_size,
                          GetChunkedVecSize(master_param + offset, chunk_size));
    }
    vec_size = std::min(
        vec_size, GetChunkedVecSize(trust_ratio_div + offset, chunk_size));
  }
833

834
  VLOG(1) << __func__ << " VecSize = " << vec_size;
835

836 837
  constexpr auto kNumTensor = MaxTensorNumPerLaunch;
  constexpr auto kNumChunk = MaxChunkNumPerLaunch;
838

839
  auto stream = dev_ctx.stream();
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
#define PD_LAUNCH_MULTI_TENSOR_UPDATE_PARAM_BETAPOW(__has_beta_pow)      \
  do {                                                                   \
    using FunctorT = LambUpdateParamAndBetaPowsFunctor<ParamT,           \
                                                       kHasMasterParam,  \
                                                       __has_beta_pow,   \
                                                       kVecSize>;        \
    LambParamHelper<ParamT, kHasMasterParam> param_helper(param,         \
                                                          master_param); \
    LambBetaPowUpdateOnceHelper<MasterT<ParamT>, __has_beta_pow>         \
        betapow_helper(beta1pow, beta2pow, beta1, beta2);                \
    launcher.Launch(FunctorT(),                                          \
                    param_helper,                                        \
                    trust_ratio_div,                                     \
                    lr,                                                  \
                    param_square_norm,                                   \
                    trust_ratio_div_square_norm,                         \
                    found_inf,                                           \
                    betapow_helper);                                     \
858
  } while (0)
859

860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
#define PD_LAUNCH_VEC_MULTI_TENSOR_UPDATE_PARAM_BETAPOW_CASE                   \
  do {                                                                         \
    auto callback =                                                            \
        [&](const paddle::operators::MultiTensorLauncher<kNumTensor,           \
                                                         kNumChunk> &launcher, \
            int launch_n) {                                                    \
          if (has_beta_pow && launch_n == 0) {                                 \
            PD_LAUNCH_MULTI_TENSOR_UPDATE_PARAM_BETAPOW(true);                 \
            beta1pow = nullptr;                                                \
            beta2pow = nullptr;                                                \
          } else {                                                             \
            PD_LAUNCH_MULTI_TENSOR_UPDATE_PARAM_BETAPOW(false);                \
          }                                                                    \
        };                                                                     \
    paddle::operators::MultiTensorApplyWithCallback<kNumTensor, kNumChunk>(    \
        stream, offsets, n, chunk_size, block_dim, callback);                  \
876 877
  } while (0)

878 879
  PD_VEC_LAUNCH_KERNEL(vec_size,
                       PD_LAUNCH_VEC_MULTI_TENSOR_UPDATE_PARAM_BETAPOW_CASE);
880

881 882
#undef PD_LAUNCH_MULTI_TENSOR_UPDATE_PARAM_BETAPOW
#undef PD_LAUNCH_VEC_MULTI_TENSOR_UPDATE_PARAM_BETAPOW_CASE
883 884 885 886
}

#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
static bool CreatePreMulScaleOpIfSupported(ncclDataType_t dtype,
887 888
                                           ncclComm_t comm,
                                           const void *scale,
889 890 891
                                           ncclRedOp_t *op) {
#if NCCL_VERSION_CODE >= 21100
  int ver;
892
  PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::ncclGetVersion(&ver));
893 894
  if (ver >= 21100) {
    VLOG(10) << "ncclRedOpCreatePreMulSum is supported.";
895
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::ncclRedOpCreatePreMulSum(
896 897 898 899 900 901 902 903
        op, const_cast<void *>(scale), dtype, ncclScalarDevice, comm));
    return true;
  }
#endif
  VLOG(10) << "ncclRedOpCreatePreMulSum is not supported.";
  return false;
}

S
sneaxiy 已提交
904
template <typename T1, typename T2>
L
Leo Chen 已提交
905
static void LaunchScaleKernel(const phi::GPUContext &dev_ctx,
906 907 908 909
                              const T1 *x,
                              const T2 *scale,
                              T1 *y,
                              int n,
S
sneaxiy 已提交
910 911
                              gpuStream_t stream) {
  int vec_size = std::min(GetChunkedVecSize(x, 0), GetChunkedVecSize(y, 0));
912
  auto config = phi::backends::gpu::GetGpuLaunchConfig1D(dev_ctx, n, vec_size);
S
sneaxiy 已提交
913

914 915 916 917 918
#define PD_LAMB_VEC_SCALE_KERNEL_CASE                                    \
  do {                                                                   \
    ScaleCUDAKernel<T1, T2, kVecSize>                                    \
        <<<config.block_per_grid, config.thread_per_block, 0, stream>>>( \
            x, scale, y, n);                                             \
S
sneaxiy 已提交
919 920 921 922 923 924
  } while (0)

  PD_VEC_LAUNCH_KERNEL(vec_size, PD_LAMB_VEC_SCALE_KERNEL_CASE);
#undef PD_LAMB_VEC_SCALE_KERNEL_CASE
}

925
template <typename T, bool UseReduceScatter>
926 927 928 929 930 931
static void NCCLSumWithScaleBase(const T *sendbuff,
                                 T *recvbuff,
                                 size_t recvcount,
                                 size_t nranks,
                                 ncclComm_t comm,
                                 gpuStream_t stream,
L
Leo Chen 已提交
932
                                 const phi::GPUContext &dev_ctx,
933
                                 const T *scale = nullptr) {
934 935 936
  static_assert(
      std::is_same<T, float>::value || std::is_same<T, dtype::float16>::value,
      "T must be either float32 or float16.");
937 938
  if (recvcount == 0) return;

939
  auto numel = UseReduceScatter ? (recvcount * nranks) : recvcount;
940 941
  if (comm == nullptr) {
    if (scale != nullptr) {
942 943
      PADDLE_ENFORCE_EQ(nranks,
                        1,
944
                        phi::errors::InvalidArgument(
945
                            "nranks must be 1 when scale != nullptr."));
946
      LaunchScaleKernel(dev_ctx, sendbuff, scale, recvbuff, numel, stream);
947 948 949 950 951 952 953 954 955
    }
    return;
  }

  ncclRedOp_t op = ncclSum;
  ncclDataType_t dtype =
      std::is_same<T, float>::value ? ncclFloat32 : ncclFloat16;
  bool should_destroy_op =
      scale && CreatePreMulScaleOpIfSupported(dtype, comm, scale, &op);
956
  memory_utils::Buffer buffer(dev_ctx.GetPlace());
957 958
  if (scale && !should_destroy_op) {
    T *new_sendbuff = buffer.Alloc<T>(numel);
S
sneaxiy 已提交
959
    LaunchScaleKernel(dev_ctx, sendbuff, scale, new_sendbuff, numel, stream);
960 961 962
    sendbuff = new_sendbuff;
  }

963
  if (UseReduceScatter) {
964
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::ncclReduceScatter(
965 966
        sendbuff, recvbuff, recvcount, dtype, op, comm, stream));
  } else {
967
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::ncclAllReduce(
968 969
        sendbuff, recvbuff, recvcount, dtype, op, comm, stream));
  }
970 971 972 973

#if NCCL_VERSION_CODE >= 21100
  if (should_destroy_op) {
    VLOG(10) << "ncclRedOpDestroy starts";
974
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::ncclRedOpDestroy(op, comm));
975 976 977 978
    VLOG(10) << "ncclRedOpDestroy ends";
  }
#endif
}
979 980

template <typename T>
L
Leo Chen 已提交
981 982 983 984 985 986 987 988
static void NCCLReduceScatterWithScale(const T *sendbuff,
                                       T *recvbuff,
                                       size_t recvcount,
                                       size_t nranks,
                                       ncclComm_t comm,
                                       gpuStream_t stream,
                                       const phi::GPUContext &dev_ctx,
                                       const T *scale = nullptr) {
989 990
  NCCLSumWithScaleBase<T, true>(
      sendbuff, recvbuff, recvcount, nranks, comm, stream, dev_ctx, scale);
991 992 993
}

template <typename T>
994 995 996 997 998 999
static void NCCLAllReduceWithScale(const T *sendbuff,
                                   T *recvbuff,
                                   size_t recvcount,
                                   size_t nranks,
                                   ncclComm_t comm,
                                   gpuStream_t stream,
L
Leo Chen 已提交
1000
                                   const phi::GPUContext &dev_ctx,
1001
                                   const T *scale = nullptr) {
1002 1003
  NCCLSumWithScaleBase<T, false>(
      sendbuff, recvbuff, recvcount, nranks, comm, stream, dev_ctx, scale);
1004 1005
}

1006 1007
#endif

1008 1009 1010
template <typename InputIteratorT,
          typename OutputIteratorT,
          typename ReduceOpT,
1011
          typename T>
1012 1013 1014 1015 1016 1017
static void CubDeviceReduce(InputIteratorT d_in,
                            OutputIteratorT d_out,
                            int num_items,
                            ReduceOpT reduction_op,
                            T init,
                            gpuStream_t stream,
1018
                            memory_utils::Buffer *buffer) {
1019 1020
  void *d_temp_storage = nullptr;
  size_t temp_storage_bytes = 0;
1021 1022 1023 1024 1025 1026 1027 1028
  PADDLE_ENFORCE_GPU_SUCCESS(cub::DeviceReduce::Reduce(d_temp_storage,
                                                       temp_storage_bytes,
                                                       d_in,
                                                       d_out,
                                                       num_items,
                                                       reduction_op,
                                                       init,
                                                       stream));
1029 1030 1031
  d_temp_storage = buffer->Alloc<void>(temp_storage_bytes);
  VLOG(10) << "cub::DeviceReduce::Reduce needs " << temp_storage_bytes
           << " byte(s), ptr = " << d_temp_storage;
1032 1033 1034 1035 1036 1037 1038 1039
  PADDLE_ENFORCE_GPU_SUCCESS(cub::DeviceReduce::Reduce(d_temp_storage,
                                                       temp_storage_bytes,
                                                       d_in,
                                                       d_out,
                                                       num_items,
                                                       reduction_op,
                                                       init,
                                                       stream));
1040 1041 1042
}

template <typename T>
1043 1044 1045
static void GetSquareGradNormImpl(const T *grad,
                                  int n,
                                  float *square_norm,
1046
                                  gpuStream_t stream,
1047
                                  memory_utils::Buffer *cub_tmp_buffer) {
1048 1049 1050
  using Iterator =
      cub::TransformInputIterator<float, SquareFunctor<T>, const T *>;
  Iterator iter(grad, SquareFunctor<T>());
1051 1052 1053 1054 1055 1056 1057
  CubDeviceReduce(iter,
                  square_norm,
                  n,
                  cub::Sum(),
                  static_cast<float>(0),
                  stream,
                  cub_tmp_buffer);
1058 1059 1060
}

// square_norm is of length 2 at least
1061 1062
static void GetSquareGradNorm(const float *fp32_grad,
                              int fp32_numel,
1063
                              const dtype::float16 *fp16_grad,
1064 1065
                              int fp16_numel,
                              float *square_norm,
1066
                              gpuStream_t stream,
1067
                              memory_utils::Buffer *cub_tmp_buffer) {
1068 1069 1070
  VLOG(10) << "GetSquareGradNorm starts, fp32_numel = " << fp32_numel
           << " , fp16_numel = " << fp16_numel;
  if (fp32_numel > 0) {
1071 1072
    GetSquareGradNormImpl(
        fp32_grad, fp32_numel, square_norm, stream, cub_tmp_buffer);
1073 1074 1075 1076 1077 1078
    VLOG(10) << "FP32 square L2-Norm: "
             << FlattenToString(square_norm, 1, cub_tmp_buffer->GetPlace());
  }

  if (fp16_numel > 0) {
    float *fp16_square_norm = fp32_numel > 0 ? square_norm + 1 : square_norm;
1079 1080
    GetSquareGradNormImpl(
        fp16_grad, fp16_numel, fp16_square_norm, stream, cub_tmp_buffer);
1081
    VLOG(10) << "FP16 square L2-Norm: "
1082 1083
             << FlattenToString(
                    fp16_square_norm, 1, cub_tmp_buffer->GetPlace());
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    if (fp32_numel > 0) {
      AddToCUDAKernel<<<1, 1, 0, stream>>>(fp16_square_norm, square_norm);
      VLOG(10) << "FP32+FP16 square L2-Norm: "
               << FlattenToString(square_norm, 1, cub_tmp_buffer->GetPlace());
    }
  }
  VLOG(10) << "GetSquareGradNorm ends, fp32_numel = " << fp32_numel
           << " , fp16_numel = " << fp16_numel;
}

template <typename T>
std::string NumToString(T x) {
  std::stringstream ss;
  ss << x;
  return ss.str();
}

template <typename T>
1102
static std::string GetMinMaxStr(const T *x, size_t n, const phi::Place &place) {
1103
  PADDLE_ENFORCE_EQ(
1104
      place.GetType() == phi::AllocationType::GPU,
1105
      true,
1106
      phi::errors::InvalidArgument("Only support CUDAPlace currently."));
1107

L
Leo Chen 已提交
1108
  auto *dev_ctx = static_cast<phi::GPUContext *>(
1109
      phi::DeviceContextPool::Instance().Get(place));
1110 1111
  auto stream = dev_ctx->stream();

1112
  memory_utils::Buffer ret_buffer(place);
1113 1114 1115
  T *ret = ret_buffer.Alloc<T>(2);

  if (n > 0) {
1116
    memory_utils::Buffer cub_buffer(place);
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    CubDeviceReduce(x,
                    ret,
                    n,
                    cub::Min(),
                    std::numeric_limits<T>::max(),
                    stream,
                    &cub_buffer);
    CubDeviceReduce(x,
                    ret + 1,
                    n,
                    cub::Max(),
                    std::numeric_limits<T>::lowest(),
                    stream,
                    &cub_buffer);
1131 1132
    T ret_cpu[2];
#ifdef PADDLE_WITH_HIP
1133 1134
    PADDLE_ENFORCE_GPU_SUCCESS(hipMemcpyAsync(
        &ret_cpu[0], ret, 2 * sizeof(T), hipMemcpyDeviceToHost, stream));
1135 1136
    PADDLE_ENFORCE_GPU_SUCCESS(hipStreamSynchronize(stream));
#else
1137 1138
    PADDLE_ENFORCE_GPU_SUCCESS(cudaMemcpyAsync(
        &ret_cpu[0], ret, 2 * sizeof(T), cudaMemcpyDeviceToHost, stream));
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
    PADDLE_ENFORCE_GPU_SUCCESS(cudaStreamSynchronize(stream));
#endif
    return std::string("{\"min\": ") + NumToString(ret_cpu[0]) +
           " , \"max\": " + NumToString(ret_cpu[1]) + "}";
  } else {
    return "{\"min\": null, \"max\": null}";
  }
}

struct VisitDTypeFunctor {
1149
  VisitDTypeFunctor(const phi::DenseTensor *x, std::string *s) : x_(x), s_(s) {}
1150 1151 1152 1153 1154 1155 1156

  template <typename T>
  void apply() const {
    *s_ = GetMinMaxStr<T>(x_->template data<T>(), x_->numel(), x_->place());
  }

 private:
1157
  const phi::DenseTensor *x_;
1158 1159 1160
  std::string *s_;
};

1161
static std::string GetMinMaxStr(const phi::DenseTensor *x) {
1162
  if (x == nullptr) return "null";
1163
  if (!x->initialized()) return "not_inited";
1164
  if (x->place().GetType() != phi::AllocationType::GPU) return "CPUTensor";
1165 1166
  std::string str;
  VisitDTypeFunctor functor(x, &str);
1167
  phi::VisitDataType(x->dtype(), functor);
1168 1169 1170
  return str;
}

1171 1172 1173 1174 1175
template <typename T>
static bool HasNanInf(const phi::GPUContext &dev_ctx, const T *x, int numel) {
  if (numel <= 0) return false;
  cub::TransformInputIterator<bool, IsNanInfFunctor<T>, const T *> iter(
      x, IsNanInfFunctor<T>());
1176 1177
  memory_utils::Buffer buffer(dev_ctx.GetPlace());
  memory_utils::Buffer out(dev_ctx.GetPlace());
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
  CubDeviceReduce(iter,
                  out.Alloc<bool>(1),
                  numel,
                  OrFunctor(),
                  false,
                  dev_ctx.stream(),
                  &buffer);
  bool flag;
#ifdef PADDLE_WITH_HIP
  PADDLE_ENFORCE_GPU_SUCCESS(hipMemcpyAsync(&flag,
                                            out.Get<bool>(),
                                            sizeof(flag),
                                            hipMemcpyDeviceToHost,
                                            dev_ctx.stream()));
#else
  PADDLE_ENFORCE_GPU_SUCCESS(cudaMemcpyAsync(&flag,
                                             out.Get<bool>(),
                                             sizeof(flag),
                                             cudaMemcpyDeviceToHost,
                                             dev_ctx.stream()));
#endif
  dev_ctx.Wait();
  return flag;
}

1203 1204
static void CheckHasNanInfGrad(const float *fp32_grad,
                               int fp32_numel,
1205
                               const dtype::float16 *fp16_grad,
1206 1207
                               int fp16_numel,
                               float *nan_inf_flag,
1208
                               gpuStream_t stream,
1209
                               memory_utils::Buffer *cub_tmp_buffer) {
1210 1211 1212 1213 1214
  bool *fp32_has_nan_inf = nullptr;
  bool *fp16_has_nan_inf = nullptr;
  if (fp32_numel > 0) {
    fp32_has_nan_inf = reinterpret_cast<bool *>(nan_inf_flag + 1);
    cub::TransformInputIterator<bool, IsNanInfFunctor<float>, const float *>
1215
        iter(fp32_grad, IsNanInfFunctor<float>());
1216 1217 1218 1219 1220 1221 1222
    CubDeviceReduce(iter,
                    fp32_has_nan_inf,
                    fp32_numel,
                    OrFunctor(),
                    false,
                    stream,
                    cub_tmp_buffer);
1223 1224 1225 1226
  }

  if (fp16_numel > 0) {
    fp16_has_nan_inf = reinterpret_cast<bool *>(nan_inf_flag + 1) + 1;
1227
    cub::TransformInputIterator<bool,
1228 1229 1230
                                IsNanInfFunctor<dtype::float16>,
                                const dtype::float16 *>
        iter(fp16_grad, IsNanInfFunctor<dtype::float16>());
1231 1232 1233 1234 1235 1236 1237
    CubDeviceReduce(iter,
                    fp16_has_nan_inf,
                    fp16_numel,
                    OrFunctor(),
                    false,
                    stream,
                    cub_tmp_buffer);
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
  }

  if (fp32_has_nan_inf && fp16_has_nan_inf) {
    SetNanInfValueCUDAKernelTwoFlag<<<1, 1, 0, stream>>>(
        fp32_has_nan_inf, fp16_has_nan_inf, nan_inf_flag);
  } else if (fp32_has_nan_inf) {
    SetNanInfValueCUDAKernelOneFlag<<<1, 1, 0, stream>>>(fp32_has_nan_inf,
                                                         nan_inf_flag);
  } else {
    SetNanInfValueCUDAKernelOneFlag<<<1, 1, 0, stream>>>(fp16_has_nan_inf,
                                                         nan_inf_flag);
  }
}

1252 1253
template <typename T1, typename T2, typename T3, int VecSize>
static __global__ void ElementwiseAddWithCastCUDAKernel(const T1 *x,
1254 1255
                                                        const T2 *y,
                                                        T3 *z,
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
                                                        int n) {
  static_assert(sizeof(T1) <= sizeof(T2),
                "sizeof(T1) must be smaller than sizeof(T2).");
  using MT = MasterT<T2>;

  int i = (threadIdx.x + blockIdx.x * blockDim.x) * VecSize;
  int stride = (blockDim.x * gridDim.x) * VecSize;
  for (; i + VecSize <= n; i += stride) {
    phi::AlignedVector<T1, VecSize> x_vec;
    phi::AlignedVector<T2, VecSize> y_vec;
    phi::AlignedVector<T3, VecSize> z_vec;
    phi::Load(x + i, &x_vec);
    phi::Load(y + i, &y_vec);
#pragma unroll
    for (int j = 0; j < VecSize; ++j) {
      auto x_tmp = static_cast<MT>(x_vec[j]);
      auto y_tmp = static_cast<MT>(y_vec[j]);
      z_vec[j] = static_cast<T3>(x_tmp + y_tmp);
    }
    phi::Store(z_vec, z + i);
  }

  for (; i < n; ++i) {
    auto x_tmp = static_cast<MT>(x[i]);
    auto y_tmp = static_cast<MT>(y[i]);
    z[i] = static_cast<T3>(x_tmp + y_tmp);
  }
}

template <typename T1, typename T2, typename T3>
L
Leo Chen 已提交
1286 1287 1288 1289 1290 1291
static void LaunchElementwiseAddWithCastKernel(const phi::GPUContext &dev_ctx,
                                               const T1 *x,
                                               const T2 *y,
                                               T3 *z,
                                               int n,
                                               gpuStream_t stream) {
1292 1293 1294
  int vec_size =
      std::min(std::min(GetChunkedVecSize(x, 0), GetChunkedVecSize(y, 0)),
               GetChunkedVecSize(z, 0));
1295
  auto config = phi::backends::gpu::GetGpuLaunchConfig1D(dev_ctx, n, vec_size);
1296

1297 1298 1299 1300 1301
#define PD_LAUNCH_ELEMENTWISE_ADD_WITH_CAST_KERNEL                       \
  do {                                                                   \
    ElementwiseAddWithCastCUDAKernel<T1, T2, T3, kVecSize>               \
        <<<config.block_per_grid, config.thread_per_block, 0, stream>>>( \
            x, y, z, n);                                                 \
1302 1303 1304 1305 1306 1307
  } while (0)

  PD_VEC_LAUNCH_KERNEL(vec_size, PD_LAUNCH_ELEMENTWISE_ADD_WITH_CAST_KERNEL);
#undef PD_LAUNCH_ELEMENTWISE_ADD_WITH_CAST_KERNEL
}

1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
template <typename T, typename Context>
void DistributedFusedLambKernel(
    const Context &dev_ctx,
    const std::vector<const DenseTensor *> &param,
    const std::vector<const DenseTensor *> &grad, /*unused*/
    const paddle::optional<DenseTensor> &fp32_param,
    const paddle::optional<DenseTensor> &fp32_grad,
    const paddle::optional<DenseTensor> &fp16_param,
    const paddle::optional<DenseTensor> &fp16_grad,
    const DenseTensor &moment1,
    const DenseTensor &moment2,
    const DenseTensor &beta1_pow,
    const DenseTensor &beta2_pow,
    const DenseTensor &param_offsets,
    const DenseTensor &fp32_partial_offsets,
    const DenseTensor &fp16_partial_offsets,
    const DenseTensor &param_info,
    const DenseTensor &param_order,
    const DenseTensor &learning_rate,
    const DenseTensor &global_scale,
    int acc_steps,
    float beta1,
    float beta2,
    float epsilon,
    float max_global_grad_norm,
    float weight_decay,
    bool clip_after_allreduce,
    bool use_master_param_norm,
    bool use_master_acc_grad,
    bool is_grad_scaled_by_nranks,
    bool use_hierarchical_allreduce,
    int64_t nranks,
    const std::vector<int> &ring_ids,
    DenseTensor *fp32_param_out,
    DenseTensor *fp16_param_out,
    DenseTensor *fp32_acc_grad,
    DenseTensor *fp16_acc_grad,
    DenseTensor *moment1_out,
    DenseTensor *moment2_out,
    DenseTensor *beta1_pow_out,
    DenseTensor *beta2_pow_out,
    DenseTensor *param_out, /*unused*/
    DenseTensor *found_inf,
    DenseTensor *acc_step,
    DenseTensor *stop_update,
    DenseTensor *step) {
1354
#if defined(PADDLE_WITH_NCCL) || defined(PADDLE_WITH_RCCL)
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
  auto stream = dev_ctx.stream();
  auto place = dev_ctx.GetPlace();
  found_inf->Resize({1});
  // Step 1: Get fp16 param and grad tensors
  int64_t fp16_numel;
  auto *fp16_param_data =
      GetSameInOutTensorPtr<dtype::float16, Context, true>(dev_ctx,
                                                           fp16_param.get_ptr(),
                                                           fp16_param_out,
                                                           "FP16FusedParam",
                                                           "FP16FusedParamOut",
                                                           &fp16_numel);
  bool has_fp16_param = (fp16_numel > 0);
  const dtype::float16 *fp16_grad_data = nullptr;
  if (has_fp16_param) {
    fp16_grad_data =
        GetInputTensorPtr<dtype::float16>(fp16_grad.get_ptr(), "FP16FusedGrad");
  } else {
    fp16_param_data = nullptr;
  }
  // Step 2: Get fp32 param and grad tensors
  int64_t fp32_numel = 0;
  auto *fp32_param_data =
      GetSameInOutTensorPtr<float, Context, true>(dev_ctx,
                                                  fp32_param.get_ptr(),
                                                  fp32_param_out,
                                                  "FP32FusedParam",
                                                  "FP32FusedParamOut",
                                                  &fp32_numel);
  PADDLE_ENFORCE_GE(fp32_numel,
                    fp16_numel,
                    phi::errors::InvalidArgument(
                        "The element number in FP32FusedParam should be not "
                        "less than FP16FusedParam."));
  fp32_numel -= fp16_numel;  // the FP32FusedParam contains fp32 param and
                             // fp16 master weight
  bool has_fp32_param = (fp32_numel > 0);
  const float *fp32_grad_data = nullptr;
  if (has_fp32_param) {
    fp32_grad_data =
        GetInputTensorPtr<float>(fp32_grad.get_ptr(), "FP32FusedGrad");
  } else {
    PADDLE_ENFORCE_EQ(
        has_fp16_param,
        true,
        phi::errors::InvalidArgument(
            "Either FP32FusedGrad or FP16FusedGrad cannot be NULL."));
  }
  auto numel = fp32_numel + fp16_numel;
  VLOG(1) << "numel = " << numel << " , fp32_numel = " << fp32_numel
          << " , fp16_numel = " << fp16_numel;

  // The NVIDIA cub library does not support number > INT32_MAX
  PADDLE_ENFORCE_LE(numel,
                    std::numeric_limits<int>::max(),
                    phi::errors::Unimplemented(
                        "Too many parameter number. Only <= %d is supported.",
                        std::numeric_limits<int>::max()));

  PADDLE_ENFORCE_GE(
      acc_steps,
      1,
      phi::errors::InvalidArgument(
          "The gradient accumulation steps should be not less than 1."));
  if (acc_steps > 1) {
    PADDLE_ENFORCE_NOT_NULL(
        acc_step,
        phi::errors::InvalidArgument(
            "Output(AccStep) cannot be nullptr when Attr(acc_steps) > 1."));
1424
    bool is_initialized = acc_step->initialized();
1425 1426 1427 1428
    int64_t *acc_step_data;
    if (is_initialized) {
      acc_step_data = dev_ctx.template HostAlloc<int64_t>(acc_step);
      ++(*acc_step_data);
1429
    } else {
1430 1431 1432
      acc_step->Resize({1});
      acc_step_data = dev_ctx.template HostAlloc<int64_t>(acc_step);
      *acc_step_data = 1;
1433
    }
1434 1435
    int64_t rounded_step = (*acc_step_data) % acc_steps;
    float *fp32_acc_grad_data = nullptr;
1436
    if (has_fp32_param) {
1437 1438 1439 1440
      PADDLE_ENFORCE_NOT_NULL(fp32_acc_grad,
                              phi::errors::InvalidArgument(
                                  "Output(FP32AccFusedGrad) cannot be nullptr "
                                  "when Attr(acc_steps) > 1."));
1441
      if (!fp32_acc_grad->initialized()) {
1442 1443 1444 1445 1446
        fp32_acc_grad->Resize({static_cast<int64_t>(fp32_numel)});
        fp32_acc_grad_data = dev_ctx.template Alloc<float>(fp32_acc_grad);
      } else {
        fp32_acc_grad_data = fp32_acc_grad->data<float>();
      }
1447 1448
    }

1449 1450 1451 1452 1453 1454 1455
    dtype::float16 *fp16_acc_grad_data = nullptr;
    float *master_acc_grad = nullptr;
    if (has_fp16_param) {
      PADDLE_ENFORCE_NOT_NULL(fp16_acc_grad,
                              phi::errors::InvalidArgument(
                                  "Output(FP16AccFusedGrad) cannot be nullptr "
                                  "when Attr(acc_steps) > 1."));
1456
      if (!fp16_acc_grad->initialized()) {
1457 1458 1459 1460 1461
        auto acc_grad_size =
            use_master_acc_grad ? (3 * fp16_numel) : fp16_numel;
        fp16_acc_grad->Resize({static_cast<int64_t>(acc_grad_size)});
        fp16_acc_grad_data =
            dev_ctx.template Alloc<dtype::float16>(fp16_acc_grad);
1462
      } else {
1463
        fp16_acc_grad_data = fp16_acc_grad->data<dtype::float16>();
1464
      }
1465 1466 1467
      if (use_master_acc_grad) {
        master_acc_grad =
            reinterpret_cast<float *>(fp16_acc_grad_data + fp16_numel);
1468
      }
1469 1470 1471
    } else {
      use_master_acc_grad = false;
    }
1472

1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
    // Inplace addto
    if (has_fp32_param) {
      if (rounded_step == 1) {
        memory_utils::Copy(place,
                           fp32_acc_grad_data,
                           place,
                           fp32_grad_data,
                           fp32_numel * sizeof(float),
                           stream);
      } else {
        LaunchElementwiseAddWithCastKernel(dev_ctx,
                                           fp32_grad_data,
                                           fp32_acc_grad_data,
                                           fp32_acc_grad_data,
                                           fp32_numel,
                                           stream);
1489
      }
1490
    }
1491

1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    if (has_fp16_param) {
      if (acc_steps == 2 || !use_master_acc_grad) {
        if (rounded_step != 1) {
          LaunchElementwiseAddWithCastKernel(dev_ctx,
                                             fp16_acc_grad_data,
                                             fp16_grad_data,
                                             fp16_acc_grad_data,
                                             fp16_numel,
                                             stream);
        } else {
          memory_utils::Copy(place,
                             fp16_acc_grad_data,
                             place,
                             fp16_grad_data,
                             fp16_numel * sizeof(dtype::float16),
                             stream);
        }
      } else {  // acc_steps >= 3
        if (rounded_step == 0) {
          LaunchElementwiseAddWithCastKernel(dev_ctx,
                                             fp16_grad_data,
                                             master_acc_grad,
                                             fp16_acc_grad_data,
                                             fp16_numel,
                                             stream);
        } else if (rounded_step == 1) {
          memory_utils::Copy(place,
                             fp16_acc_grad_data,
                             place,
                             fp16_grad_data,
                             fp16_numel * sizeof(dtype::float16),
                             stream);
        } else if (rounded_step == 2) {
          LaunchElementwiseAddWithCastKernel(dev_ctx,
                                             fp16_grad_data,
                                             fp16_acc_grad_data,
                                             master_acc_grad,
                                             fp16_numel,
                                             stream);
1531
        } else {
1532
          LaunchElementwiseAddWithCastKernel(dev_ctx,
1533 1534 1535 1536
                                             fp16_grad_data,
                                             master_acc_grad,
                                             master_acc_grad,
                                             fp16_numel,
1537
                                             stream);
1538 1539
        }
      }
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
    }
    stop_update->Resize({1});
    auto *stop_update_data = dev_ctx.template HostAlloc<bool>(stop_update);
    auto *found_inf_cpu = dev_ctx.template HostAlloc<bool>(found_inf);
    if (rounded_step != 0) {
      *stop_update_data = true;
      *found_inf_cpu = false;
      return;
    } else {
      // swap pointer
      fp32_grad_data = fp32_acc_grad_data;
      fp16_grad_data = fp16_acc_grad_data;
      *stop_update_data = false;
      found_inf->clear();
    }
  }
1556

1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
  // Step 3: Get ParamInfo
  const auto *param_info_data =
      GetInputTensorPtr<int>(&param_info, "ParamInfo");
  auto fp32_local_start_idx = param_info_data[0];
  auto fp32_local_param_num = param_info_data[1];
  auto fp32_global_param_num = param_info_data[2];
  auto fp32_weight_decay_end_idx = param_info_data[3];
  auto fp16_local_start_idx = param_info_data[4];
  auto fp16_local_param_num = param_info_data[5];
  auto fp16_global_param_num = param_info_data[6];
  auto fp16_weight_decay_end_idx = param_info_data[7];

  auto local_param_num = fp32_local_param_num + fp16_local_param_num;
  auto param_num = fp32_global_param_num + fp16_global_param_num;
  PADDLE_ENFORCE_LE(local_param_num,
                    param_num,
                    phi::errors::InvalidArgument(
                        "The local parameter number should not exceed the "
                        "global parameter number."));
  VLOG(1) << "local_param_num = " << local_param_num
          << " , global_param_num = " << param_num
          << " , fp32_local_start_idx = " << fp32_local_start_idx
          << " , fp32_local_param_num = " << fp32_local_param_num
          << " , fp32_global_param_num = " << fp32_global_param_num
          << " , fp16_local_start_idx = " << fp16_local_start_idx
          << " , fp16_local_param_num = " << fp16_local_param_num
          << " , fp16_global_param_num = " << fp16_global_param_num;

  // Step 4: Get LearningRate, Moment1, Moment2, Beta1Pow, Beta2Pow,
  // GlobalScale
  const auto *global_scale_data =
      GetInputTensorPtr<float>(&global_scale, "GlobalScale");
  const auto *lr_data =
      GetInputTensorPtr<float>(&learning_rate, "LearningRate");
  int64_t partial_numel = 0;
  auto *moment1_data = GetSameInOutTensorPtr<float, Context>(
      dev_ctx, &moment1, moment1_out, "Moment1", "Moment1Out", &partial_numel);
  PADDLE_ENFORCE_EQ(numel % partial_numel,
                    0,
                    phi::errors::InvalidArgument(
                        "The total parameter number %d should be divided "
                        "exactly by the element number %d of Moment1.",
                        numel,
                        partial_numel));

  // The num_devices means the number of devices that shard a complete set
  // of all parameters. It may be num_devices < nranks or num_devices ==
  // nranks.
  int64_t num_devices = numel / partial_numel;
  VLOG(1) << "num_devices = " << num_devices
          << " , partial_numel = " << partial_numel;

  PADDLE_ENFORCE_EQ(fp32_numel % num_devices,
                    0,
                    phi::errors::InvalidArgument(
                        "The fp32 parameter number %d should be divided "
                        "exactly by the device number %d.",
                        fp32_numel,
                        num_devices));
  PADDLE_ENFORCE_EQ(fp16_numel % num_devices,
                    0,
                    phi::errors::InvalidArgument(
                        "The fp16 parameter number %d should be divided "
                        "exactly by the device number %d.",
                        fp16_numel,
                        num_devices));
  auto *moment2_data = GetSameInOutTensorPtr<float, Context>(
      dev_ctx, &moment2, moment2_out, "Moment2", "Moment2Out");
  auto *beta1_pow_data = GetSameInOutTensorPtr<float, Context>(
      dev_ctx, &beta1_pow, beta1_pow_out, "Beta1Pow", "Beta1PowOut");
  auto *beta2_pow_data = GetSameInOutTensorPtr<float, Context>(
      dev_ctx, &beta2_pow, beta2_pow_out, "Beta2Pow", "Beta2PowOut");
  auto *found_inf_data = dev_ctx.template Alloc<bool>(found_inf);
  // Step 5: Get attributes weight_decay, beta1, beta2, epsilon,
  // max_grad_norm, ring_id,
  // use_master_param_norm, is_grad_scaled_by_nranks
  PADDLE_ENFORCE_GE(nranks,
                    num_devices,
                    phi::errors::InvalidArgument(
                        "The nranks must be not less than num_devices."));
  PADDLE_ENFORCE_EQ(nranks % num_devices,
                    0,
                    phi::errors::InvalidArgument(
                        "The nranks must be exactly divided by num_devices."));
  bool local_shard = (nranks > num_devices);

  VLOG(10) << "max_global_grad_norm = " << max_global_grad_norm
           << " , clip_after_allreduce = " << clip_after_allreduce
           << " , use_master_param_norm = " << use_master_param_norm
           << " , is_grad_scaled_by_nranks = " << is_grad_scaled_by_nranks
           << " , local_shard = " << local_shard
           << " , use_hierarchical_allreduce = " << use_hierarchical_allreduce;

  // Step 6: allreduce + global norm gradient clip
  int64_t global_rank = 0, local_rank = 0;
  ncclComm_t global_comm = nullptr, local_comm = nullptr,
             external_comm = nullptr;
  if (nranks > 1) {
    auto *nccl_comm_handle =
        paddle::platform::NCCLCommContext::Instance().Get(ring_ids[0], place);
    global_comm = nccl_comm_handle->comm();
    global_rank = nccl_comm_handle->rank();
    if (local_shard) {
      auto *local_nccl_comm_handle =
          paddle::platform::NCCLCommContext::Instance().Get(ring_ids[1], place);
      local_comm = local_nccl_comm_handle->comm();
      local_rank = local_nccl_comm_handle->rank();
      if (use_hierarchical_allreduce) {
        external_comm = paddle::platform::NCCLCommContext::Instance()
                            .Get(ring_ids[2], place)
                            ->comm();
1668
      }
1669 1670 1671
    } else {
      local_comm = global_comm;
      local_rank = global_rank;
1672
    }
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
  }
  memory_utils::Buffer grad_norm_square_buffer(place);
  auto *fp32_square_grad_norm = grad_norm_square_buffer.Alloc<float>(2);
  memory_utils::Buffer cub_tmp_buffer(place);
  memory_utils::Buffer sum_grad_buffer(place);
  float *fp32_sum_grad;
  dtype::float16 *fp16_sum_grad;
  auto fp32_numel_each_device = fp32_numel / num_devices;
  auto fp16_numel_each_device = fp16_numel / num_devices;
  if (local_shard) {
    auto ptr = sum_grad_buffer.Alloc<uint8_t>(
        fp32_numel * sizeof(float) + fp16_numel * sizeof(dtype::float16));
    fp32_sum_grad = has_fp32_param ? reinterpret_cast<float *>(ptr) : nullptr;
    fp16_sum_grad = has_fp16_param ? reinterpret_cast<dtype::float16 *>(
                                         ptr + fp32_numel * sizeof(float))
                                   : nullptr;
  } else if (nranks > 1 ||
             (max_global_grad_norm > 0 && !clip_after_allreduce)) {
    auto ptr = sum_grad_buffer.Alloc<uint8_t>(
        fp32_numel_each_device * sizeof(float) +
        fp16_numel_each_device * sizeof(dtype::float16));
    fp32_sum_grad = has_fp32_param ? reinterpret_cast<float *>(ptr) : nullptr;
    fp16_sum_grad = has_fp16_param
                        ? reinterpret_cast<dtype::float16 *>(
                              ptr + fp32_numel_each_device * sizeof(float))
                        : nullptr;
  } else {
    // NOTE: The const_cast here is not important. The fp32_sum_grad and
    // fp16_sum_grad would not be changed when num_devices == 1
    // But if I do not perform const_cast here, there would be more
    // if-else codes (num_devices > 1) when I write the following code.
    // So I prefer to use const_cast to unify the following code to reduce
    // the if-else codes.
    fp32_sum_grad = const_cast<float *>(fp32_grad_data);
    fp16_sum_grad = const_cast<dtype::float16 *>(fp16_grad_data);
  }
  float rescale_grad = 1.0f;
  if (!is_grad_scaled_by_nranks) {
    rescale_grad /= nranks;
  }
1713

1714 1715 1716
  if (max_global_grad_norm > 0) {
    if (clip_after_allreduce) {
      // (1) ReduceScater first
1717
      if (local_shard) {
1718
        if (use_hierarchical_allreduce) {
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
          NCCLReduceScatterWithScale(
              fp32_grad_data,
              fp32_sum_grad + local_rank * fp32_numel_each_device,
              fp32_numel_each_device,
              num_devices,
              local_comm,
              stream,
              dev_ctx);
          NCCLAllReduceWithScale(
              fp32_sum_grad + local_rank * fp32_numel_each_device,
              fp32_sum_grad + local_rank * fp32_numel_each_device,
              fp32_numel_each_device,
              nranks / num_devices,
              external_comm,
              stream,
              dev_ctx);

          NCCLReduceScatterWithScale(
              fp16_grad_data,
              fp16_sum_grad + local_rank * fp16_numel_each_device,
              fp16_numel_each_device,
              num_devices,
              local_comm,
              stream,
              dev_ctx);
          NCCLAllReduceWithScale(
              fp16_sum_grad + local_rank * fp16_numel_each_device,
              fp16_sum_grad + local_rank * fp16_numel_each_device,
              fp16_numel_each_device,
              nranks / num_devices,
              external_comm,
              stream,
              dev_ctx);
        } else {
          NCCLAllReduceWithScale(fp32_grad_data,
                                 fp32_sum_grad,
                                 fp32_numel,
                                 nranks,
                                 global_comm,
                                 stream,
                                 dev_ctx);
          NCCLAllReduceWithScale(fp16_grad_data,
                                 fp16_sum_grad,
                                 fp16_numel,
                                 nranks,
                                 global_comm,
                                 stream,
                                 dev_ctx);
1767
        }
1768 1769
        fp32_sum_grad += (local_rank * fp32_numel_each_device);
        fp16_sum_grad += (local_rank * fp16_numel_each_device);
1770
      } else {
1771
        NCCLReduceScatterWithScale(fp32_grad_data,
1772
                                   fp32_sum_grad,
1773
                                   fp32_numel_each_device,
1774 1775 1776 1777
                                   nranks,
                                   global_comm,
                                   stream,
                                   dev_ctx);
1778
        NCCLReduceScatterWithScale(fp16_grad_data,
1779
                                   fp16_sum_grad,
1780
                                   fp16_numel_each_device,
1781 1782 1783 1784
                                   nranks,
                                   global_comm,
                                   stream,
                                   dev_ctx);
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
      }
      // (2) Calculate the global grad norm
      GetSquareGradNorm(fp32_sum_grad,
                        fp32_numel_each_device,
                        fp16_sum_grad,
                        fp16_numel_each_device,
                        fp32_square_grad_norm,
                        stream,
                        &cub_tmp_buffer);
      VLOG(1) << "Grad square norm before all reduce: "
              << FlattenToString(fp32_square_grad_norm, 1, place);
      if (num_devices > 1) {
        PADDLE_ENFORCE_GPU_SUCCESS(
            phi::dynload::ncclAllReduce(fp32_square_grad_norm,
                                        fp32_square_grad_norm,
                                        1,
                                        ncclFloat32,
                                        ncclSum,
                                        local_comm,
                                        stream));
      }
      VLOG(1) << "Grad square norm after all reduce: "
              << FlattenToString(fp32_square_grad_norm, 1, place);
    } else {
      // (1) Calculate the local grad norm
      GetSquareGradNorm(fp32_grad_data,
                        fp32_numel,
                        fp16_grad_data,
                        fp16_numel,
                        fp32_square_grad_norm,
                        stream,
                        &cub_tmp_buffer);
      VLOG(1) << "Grad square norm before all reduce: "
              << FlattenToString(fp32_square_grad_norm, 1, place);
      // (2) Calculate the gradient clip scale
      float *fp32_scale = nullptr;
      dtype::float16 *fp16_scale = nullptr;
      if (has_fp32_param && has_fp16_param) {
        auto *ptr = cub_tmp_buffer.Alloc<uint8_t>(sizeof(float) +
                                                  sizeof(dtype::float16));
        fp32_scale = reinterpret_cast<float *>(ptr);
        fp16_scale = reinterpret_cast<dtype::float16 *>(ptr + sizeof(float));
      } else if (has_fp32_param) {
        fp32_scale = cub_tmp_buffer.Alloc<float>(1);
1829
      } else {
1830 1831 1832 1833 1834
        fp16_scale = cub_tmp_buffer.Alloc<dtype::float16>(1);
      }
      float clip_scale = 1.0f;
      if (is_grad_scaled_by_nranks) {
        clip_scale *= nranks;
1835
      }
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
      CalcGradNormClipBeforeAllReduceScale<float, dtype::float16>
          <<<1, 1, 0, stream>>>(global_scale_data,
                                max_global_grad_norm,
                                fp32_square_grad_norm,
                                fp32_scale,
                                fp16_scale,
                                clip_scale);
      if (fp32_scale) {
        VLOG(1) << "Grad scale: " << FlattenToString(fp32_scale, 1, place);
      } else {
        VLOG(1) << "Grad scale: " << FlattenToString(fp16_scale, 1, place);
      }
      // (3) Do ReduceScatter with scale
      VLOG(1) << "FP32 HasNanInf before all reduce: "
              << HasNanInf(dev_ctx, fp32_grad_data, fp32_numel);
      VLOG(1) << "FP16 HasNanInf before all reduce: "
              << HasNanInf(dev_ctx, fp16_grad_data, fp16_numel);
1853
      if (local_shard) {
1854 1855
        if (use_hierarchical_allreduce) {
          NCCLReduceScatterWithScale(
1856
              fp32_grad_data,
1857 1858 1859 1860 1861
              fp32_sum_grad + local_rank * fp32_numel_each_device,
              fp32_numel_each_device,
              num_devices,
              local_comm,
              stream,
1862 1863
              dev_ctx,
              fp32_scale);
S
sneaxiy 已提交
1864 1865 1866 1867 1868 1869 1870 1871
          NCCLAllReduceWithScale(
              fp32_sum_grad + local_rank * fp32_numel_each_device,
              fp32_sum_grad + local_rank * fp32_numel_each_device,
              fp32_numel_each_device,
              nranks / num_devices,
              external_comm,
              stream,
              dev_ctx);
1872 1873

          NCCLReduceScatterWithScale(
1874
              fp16_grad_data,
1875 1876 1877 1878 1879
              fp16_sum_grad + local_rank * fp16_numel_each_device,
              fp16_numel_each_device,
              num_devices,
              local_comm,
              stream,
1880 1881
              dev_ctx,
              fp16_scale);
S
sneaxiy 已提交
1882 1883 1884 1885 1886 1887 1888 1889
          NCCLAllReduceWithScale(
              fp16_sum_grad + local_rank * fp16_numel_each_device,
              fp16_sum_grad + local_rank * fp16_numel_each_device,
              fp16_numel_each_device,
              nranks / num_devices,
              external_comm,
              stream,
              dev_ctx);
1890
        } else {
1891
          NCCLAllReduceWithScale(fp32_grad_data,
1892 1893 1894 1895 1896
                                 fp32_sum_grad,
                                 fp32_numel,
                                 nranks,
                                 global_comm,
                                 stream,
1897 1898 1899
                                 dev_ctx,
                                 fp32_scale);
          NCCLAllReduceWithScale(fp16_grad_data,
1900 1901 1902 1903 1904
                                 fp16_sum_grad,
                                 fp16_numel,
                                 nranks,
                                 global_comm,
                                 stream,
1905 1906
                                 dev_ctx,
                                 fp16_scale);
1907
        }
1908 1909 1910
        fp32_sum_grad += (local_rank * fp32_numel_each_device);
        fp16_sum_grad += (local_rank * fp16_numel_each_device);
      } else {
1911
        NCCLReduceScatterWithScale(fp32_grad_data,
1912 1913
                                   fp32_sum_grad,
                                   fp32_numel_each_device,
1914
                                   nranks,
1915 1916
                                   global_comm,
                                   stream,
1917 1918 1919
                                   dev_ctx,
                                   fp32_scale);
        NCCLReduceScatterWithScale(fp16_grad_data,
1920 1921
                                   fp16_sum_grad,
                                   fp16_numel_each_device,
1922
                                   nranks,
1923 1924
                                   global_comm,
                                   stream,
1925 1926
                                   dev_ctx,
                                   fp16_scale);
1927
      }
1928 1929 1930 1931
      VLOG(1) << "FP32 HasNanInf after all reduce: "
              << HasNanInf(dev_ctx, fp32_sum_grad, fp32_numel_each_device);
      VLOG(1) << "FP16 HasNanInf after all reduce: "
              << HasNanInf(dev_ctx, fp16_sum_grad, fp16_numel_each_device);
1932 1933 1934 1935 1936 1937
      CheckHasNanInfGrad(fp32_sum_grad,
                         fp32_numel_each_device,
                         fp16_sum_grad,
                         fp16_numel_each_device,
                         fp32_square_grad_norm,
                         stream,
1938 1939
                         &cub_tmp_buffer);
      if (num_devices > 1) {
1940
        PADDLE_ENFORCE_GPU_SUCCESS(
1941 1942 1943 1944 1945 1946 1947 1948 1949
            phi::dynload::ncclAllReduce(fp32_square_grad_norm,
                                        fp32_square_grad_norm,
                                        1,
                                        ncclFloat32,
                                        ncclSum,
                                        local_comm,
                                        stream));
        VLOG(1) << "Grad square norm after all reduce: "
                << FlattenToString(fp32_square_grad_norm, 1, place);
1950
      }
1951 1952
      // (4) mark max_global_grad_norm as 0, meaning that clip has been
      // already performed
1953 1954
      max_global_grad_norm = 0;
    }
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
  } else {
    if (local_shard) {
      if (use_hierarchical_allreduce) {
        NCCLReduceScatterWithScale(
            fp32_grad_data,
            fp32_sum_grad + local_rank * fp32_numel_each_device,
            fp32_numel_each_device,
            num_devices,
            local_comm,
            stream,
            dev_ctx);
        NCCLAllReduceWithScale(
            fp32_sum_grad + local_rank * fp32_numel_each_device,
            fp32_sum_grad + local_rank * fp32_numel_each_device,
            fp32_numel_each_device,
            nranks / num_devices,
            external_comm,
            stream,
            dev_ctx);
        NCCLReduceScatterWithScale(
            fp16_grad_data,
            fp16_sum_grad + local_rank * fp16_numel_each_device,
            fp16_numel_each_device,
            num_devices,
            local_comm,
            stream,
            dev_ctx);
        NCCLAllReduceWithScale(
            fp16_sum_grad + local_rank * fp16_numel_each_device,
            fp16_sum_grad + local_rank * fp16_numel_each_device,
            fp16_numel_each_device,
            nranks / num_devices,
            external_comm,
            stream,
            dev_ctx);
      } else {
        NCCLAllReduceWithScale(fp32_grad_data,
                               fp32_sum_grad,
                               fp32_numel,
                               nranks,
                               global_comm,
                               stream,
                               dev_ctx);
        NCCLAllReduceWithScale(fp16_grad_data,
                               fp16_sum_grad,
                               fp16_numel,
                               nranks,
                               global_comm,
                               stream,
                               dev_ctx);
      }
      fp32_sum_grad += (local_rank * fp32_numel_each_device);
      fp16_sum_grad += (local_rank * fp16_numel_each_device);
    } else {
      NCCLReduceScatterWithScale(fp32_grad_data,
                                 fp32_sum_grad,
                                 fp32_numel_each_device,
                                 num_devices,
                                 global_comm,
                                 stream,
                                 dev_ctx);
      NCCLReduceScatterWithScale(fp16_grad_data,
                                 fp16_sum_grad,
                                 fp16_numel_each_device,
                                 num_devices,
                                 global_comm,
                                 stream,
                                 dev_ctx);
2023
    }
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
    CheckHasNanInfGrad(fp32_sum_grad,
                       fp32_numel_each_device,
                       fp16_sum_grad,
                       fp16_numel_each_device,
                       fp32_square_grad_norm,
                       stream,
                       &cub_tmp_buffer);
    if (num_devices > 1) {
      PADDLE_ENFORCE_GPU_SUCCESS(
          phi::dynload::ncclAllReduce(fp32_square_grad_norm,
                                      fp32_square_grad_norm,
                                      1,
                                      ncclFloat32,
                                      ncclSum,
                                      local_comm,
                                      stream));
2040
    }
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
    max_global_grad_norm = 0;
  }
  VLOG(10) << "ReduceScatter done";

  // Step 7: update the moment1, moment2. Calcuate the trust_ratio_div
  auto *param_offsets_data = param_offsets.data<int>();
  const auto *fp32_partial_offsets_data = fp32_partial_offsets.data<int>();
  const auto *fp16_partial_offsets_data = fp16_partial_offsets.data<int>();
  auto *step_data = step->data<int64_t>();
  VLOG(1) << "FusedParamOffsets: "
          << FlattenToString(param_offsets_data,
                             param_offsets.numel(),
                             param_offsets.place());
  VLOG(1) << "FP32ShardFusedParamOffsets: "
          << FlattenToString(fp32_partial_offsets_data,
                             fp32_partial_offsets.numel(),
                             fp32_partial_offsets.place());
  VLOG(1) << "FP16ShardFusedParamOffsets: "
          << FlattenToString(fp16_partial_offsets_data,
                             fp16_partial_offsets.numel(),
                             fp16_partial_offsets.place());
  memory_utils::Buffer trust_ratio_div_buffer(place);
  auto *trust_ratio_div = trust_ratio_div_buffer.Alloc<float>(partial_numel);
  auto fp32_offset = local_rank * fp32_numel_each_device;
  auto fp16_offset = local_rank * fp16_numel_each_device;
  if (has_fp32_param) {
    VLOG(10) << "Update FP32 Moment and TrustRatioDiv starts";
    MultiTensorUpdateLambMomentAndTrustRatioDiv(dev_ctx,
                                                fp32_partial_offsets_data,
                                                fp32_local_param_num,
                                                fp32_param_data + fp32_offset,
                                                fp32_sum_grad,
                                                fp32_square_grad_norm,
                                                global_scale_data,
                                                beta1_pow_data,
                                                beta2_pow_data,
                                                moment1_data,
                                                moment2_data,
                                                trust_ratio_div,
                                                found_inf_data,
                                                step_data,
                                                weight_decay,
                                                fp32_weight_decay_end_idx,
                                                beta1,
                                                beta2,
                                                epsilon,
                                                max_global_grad_norm,
                                                rescale_grad);
    VLOG(10) << "Update FP32 Moment and TrustRatioDiv done";
  }
  float *master_param = nullptr;
  if (has_fp16_param) {
    master_param = fp32_param_data + fp32_numel;
    VLOG(10) << "Update FP16 Moment and TrustRatioDiv starts";
    auto tmp_found_inf = has_fp32_param ? nullptr : found_inf_data;
    auto tmp_step = has_fp32_param ? nullptr : step_data;
    MultiTensorUpdateLambMomentAndTrustRatioDiv(
        dev_ctx,
        fp16_partial_offsets_data,
        fp16_local_param_num,
        master_param + fp16_offset,
        fp16_sum_grad,
        fp32_square_grad_norm,
        global_scale_data,
        beta1_pow_data,
        beta2_pow_data,
        moment1_data + fp32_numel_each_device,
        moment2_data + fp32_numel_each_device,
        trust_ratio_div + fp32_numel_each_device,
        tmp_found_inf,
        tmp_step,
        weight_decay,
        fp16_weight_decay_end_idx,
        beta1,
        beta2,
        epsilon,
        max_global_grad_norm,
        rescale_grad);
    VLOG(10) << "Update FP16 Moment and TrustRatioDiv done";
  }
2121

2122
  VLOG(10) << "Update Moment and TrustRatioDiv done hehahaha";
2123

2124 2125 2126 2127 2128
  // Step 8: calculate L2-Norm square of parameter and trust_ratio_div
  memory_utils::Buffer square_norm_buffer(place);
  auto *param_square_norm = square_norm_buffer.Alloc<float>(2 * param_num);
  auto *trust_ratio_div_square_norm = param_square_norm + param_num;
  if (num_devices > 1) {
2129
    if (use_master_param_norm) {
2130 2131 2132
      FillZeroWithPtr(param_square_norm + fp32_global_param_num,
                      2 * param_num - fp32_global_param_num,
                      stream);
2133
    } else {
2134
      FillZeroWithPtr(trust_ratio_div_square_norm, param_num, stream);
2135
    }
2136 2137 2138 2139 2140 2141 2142 2143
  }
  MultiTensorL2Norm(place,
                    stream,
                    fp32_param_data,
                    param_offsets_data,
                    fp32_global_param_num,
                    param_square_norm);
  if (use_master_param_norm) {
2144 2145
    MultiTensorL2Norm(place,
                      stream,
2146 2147 2148 2149 2150
                      master_param + fp16_offset,
                      fp16_partial_offsets_data,
                      fp16_local_param_num,
                      param_square_norm + fp16_local_start_idx);
  } else {
2151 2152
    MultiTensorL2Norm(place,
                      stream,
2153 2154 2155 2156
                      fp16_param_data +
                          param_offsets_data[fp16_local_start_idx] -
                          param_offsets_data[fp32_global_param_num],
                      param_offsets_data + fp16_local_start_idx,
2157
                      fp16_local_param_num,
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
                      param_square_norm + fp16_local_start_idx);
  }
  MultiTensorL2Norm(place,
                    stream,
                    trust_ratio_div,
                    fp32_partial_offsets_data,
                    fp32_local_param_num,
                    trust_ratio_div_square_norm + fp32_local_start_idx);
  MultiTensorL2Norm(place,
                    stream,
                    trust_ratio_div + fp32_numel_each_device,
                    fp16_partial_offsets_data,
                    fp16_local_param_num,
                    trust_ratio_div_square_norm + fp16_local_start_idx);
  VLOG(1) << "TrustRatioDiv L2-Norm before allreduce: "
          << FlattenToString(trust_ratio_div_square_norm, param_num, place);
  if (num_devices > 1) {
    if (use_master_param_norm) {
      PADDLE_ENFORCE_GPU_SUCCESS(
          phi::dynload::ncclAllReduce(param_square_norm + fp32_global_param_num,
                                      param_square_norm + fp32_global_param_num,
                                      2 * param_num - fp32_global_param_num,
                                      ncclFloat32,
                                      ncclSum,
                                      local_comm,
                                      stream));
    } else {
      PADDLE_ENFORCE_GPU_SUCCESS(
          phi::dynload::ncclAllReduce(trust_ratio_div_square_norm,
                                      trust_ratio_div_square_norm,
                                      param_num,
                                      ncclFloat32,
                                      ncclSum,
                                      local_comm,
                                      stream));
2193
    }
2194 2195
    VLOG(10) << "ncclAllReduce done";
  }
2196

2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
  LogParamAndTrustRatioDivSquareNorm<1>(
      param, param_order, param_square_norm, trust_ratio_div_square_norm);
  VLOG(10) << "Calculate L2-Norm of Param and TrustRatioDiv done";

  // Step 9: update parameter, beta1pow, beta2pow. All gather parameters.
  if (has_fp32_param) {
    MultiTensorUpdateLambParamAndBetaPows<float>(
        dev_ctx,
        fp32_partial_offsets_data,
        fp32_local_param_num,
        trust_ratio_div,
        lr_data,
        param_square_norm + fp32_local_start_idx,
        trust_ratio_div_square_norm + fp32_local_start_idx,
        found_inf_data,
        fp32_param_data + fp32_offset,
        nullptr,
        beta1_pow_data,
        beta2_pow_data,
        beta1,
        beta2);
    if (num_devices > 1) {
      // ncclAllGather
      PADDLE_ENFORCE_GPU_SUCCESS(
          phi::dynload::ncclAllGather(fp32_param_data + fp32_offset,
                                      fp32_param_data,
                                      fp32_numel_each_device,
                                      ncclFloat32,
                                      local_comm,
                                      stream));
2227
    }
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256

    beta1_pow_data = nullptr;
    beta2_pow_data = nullptr;
  }
  if (has_fp16_param) {
    MultiTensorUpdateLambParamAndBetaPows<dtype::float16>(
        dev_ctx,
        fp16_partial_offsets_data,
        fp16_local_param_num,
        trust_ratio_div + fp32_numel_each_device,
        lr_data,
        param_square_norm + fp16_local_start_idx,
        trust_ratio_div_square_norm + fp16_local_start_idx,
        found_inf_data,
        fp16_param_data + fp16_offset,
        master_param + fp16_offset,
        beta1_pow_data,
        beta2_pow_data,
        beta1,
        beta2);
    if (num_devices > 1) {
      // ncclAllGather
      PADDLE_ENFORCE_GPU_SUCCESS(
          phi::dynload::ncclAllGather(fp16_param_data + fp16_offset,
                                      fp16_param_data,
                                      fp16_numel_each_device,
                                      ncclFloat16,
                                      local_comm,
                                      stream));
2257
    }
2258 2259
  }
  VLOG(10) << "Update Param done";
2260

2261
  VLOG(1) << "IsFinite: " << IsFinite(dev_ctx, fp32_square_grad_norm);
2262
#else
2263 2264
  PADDLE_THROW(phi::errors::Unimplemented(
      "distributed_fused_lamb op should be used with NCCL/RCCL."));
2265
#endif
2266
}
2267

2268 2269 2270 2271 2272 2273 2274 2275
}  // namespace fusion
}  // namespace phi

PD_REGISTER_KERNEL(distributed_fused_lamb,
                   GPU,
                   ALL_LAYOUT,
                   phi::fusion::DistributedFusedLambKernel,
                   float) {
2276 2277 2278 2279 2280 2281
  kernel->InputAt(10).SetBackend(phi::Backend::CPU);
  kernel->InputAt(11).SetBackend(phi::Backend::CPU);
  kernel->InputAt(12).SetBackend(phi::Backend::CPU);
  kernel->InputAt(13).SetBackend(phi::Backend::CPU);
  kernel->InputAt(14).SetBackend(phi::Backend::CPU);

2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294
  kernel->OutputAt(0).SetDataType(phi::DataType::FLOAT32);
  kernel->OutputAt(1).SetDataType(phi::DataType::FLOAT16);
  kernel->OutputAt(2).SetDataType(phi::DataType::FLOAT32);
  kernel->OutputAt(3).SetDataType(phi::DataType::FLOAT16);
  kernel->OutputAt(4).SetDataType(phi::DataType::FLOAT32);
  kernel->OutputAt(5).SetDataType(phi::DataType::FLOAT32);
  kernel->OutputAt(6).SetDataType(phi::DataType::FLOAT32);
  kernel->OutputAt(7).SetDataType(phi::DataType::FLOAT32);
  kernel->OutputAt(9).SetDataType(phi::DataType::BOOL);
  kernel->OutputAt(10).SetDataType(phi::DataType::INT64);
  kernel->OutputAt(11).SetDataType(phi::DataType::BOOL);
  kernel->OutputAt(12).SetDataType(phi::DataType::INT64);
}