dgc_op.h 8.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#pragma once
#include <vector>
17

18
#include "dgc/dgc.h"
19
#include "paddle/fluid/framework/eigen.h"
20
#include "paddle/fluid/memory/malloc.h"
21 22
#include "paddle/fluid/operators/elementwise/elementwise_op_function.h"
#include "paddle/phi/kernels/funcs/elementwise_functor.h"
23 24 25 26 27

namespace paddle {
namespace operators {

inline float get_period_sparcity(const std::vector<float>& sparsity,
28 29 30 31
                                 float cur_step,
                                 float rampup_steps) {
  PADDLE_ENFORCE_GE(static_cast<int>(cur_step),
                    0,
32 33 34 35
                    platform::errors::InvalidArgument(
                        "DGC current step=%d, but it must >= 0, "
                        "please submit issue in github",
                        static_cast<int>(cur_step)));
36 37 38

  size_t idx = static_cast<int>(cur_step * sparsity.size() / rampup_steps);
  if (idx >= sparsity.size()) {
39
    idx = sparsity.size() - 1;
40 41
  }

42
  PADDLE_ENFORCE_LT(
43 44
      idx,
      sparsity.size(),
45
      platform::errors::OutOfRange(
46 47
          "sparsity index out of bounds. idx=%d >= sparsity.size=%d",
          idx,
48
          sparsity.size()));
49 50 51 52 53 54 55
  return sparsity[idx];
}

template <typename DeviceContext, typename T>
class DGCOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
56 57 58
    auto u = ctx.Input<phi::DenseTensor>("U");
    auto v = ctx.Input<phi::DenseTensor>("V");
    auto g = ctx.Input<phi::DenseTensor>("Grad");
59

60
    auto grad_out = ctx.Output<phi::DenseTensor>("Grad_out");
61

62 63 64 65 66 67 68
    // attrs
    float m = ctx.Attr<float>("m");
    bool use_nesterov = ctx.Attr<bool>("use_nesterov");
    auto sparsity = ctx.Attr<std::vector<float>>("sparsity");
    auto rampup_begin_step = ctx.Attr<float>("rampup_begin_step");
    auto rampup_step = ctx.Attr<float>("rampup_step");

69
    // nranks
70
    auto nranks_tensor = ctx.Input<phi::DenseTensor>("nranks");
71
    const int nranks = static_cast<int>(*nranks_tensor->data<float>());
72 73
    PADDLE_ENFORCE_GT(nranks,
                      1,
74 75 76
                      platform::errors::PreconditionNotMet(
                          "DGC is not useful when num_trainers <= 1. Please "
                          "use multi card or multi machine GPU"));
77

78
    // regularization
79
    auto p = ctx.Input<phi::DenseTensor>("Param");
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
    float regular_coeff = ctx.Attr<float>("regular_coeff");
    int regular_type = ctx.Attr<int>("regular_type");

    auto p_e = framework::EigenVector<T>::Flatten(*p);
    auto g_e = framework::EigenVector<T>::Flatten(*g);
    auto grad_out_e = framework::EigenVector<T>::Flatten(*grad_out);

    auto& dev_ctx = ctx.template device_context<DeviceContext>();
    auto& eigen_ctx = *dev_ctx.eigen_device();

    // NOTE. In paddle, loss has divided by nranks. Because dgc_op is before
    // allreduce, so local regular_coeff need div nranks too. But now we
    // multi grad with nranks in dgc_op, in that case regular_coeff don't
    // need to /nranks, can prevent precision loss. For coeff often equal
    // with 1e-4, if nranks=32, coeff/nranks will be 3.125e-6, the numerical
    // accuracy of coeff/nranks will be too low.
96 97
    PADDLE_ENFORCE_EQ(regular_type >= 0 && regular_type <= 2,
                      true,
98 99 100 101 102 103 104 105 106 107 108 109 110 111
                      platform::errors::InvalidArgument(
                          "DGC only support one of None|L1Decay|L2Decay "
                          "Regularization for now."));
    if (regular_type == 0) {
      grad_out_e.device(eigen_ctx) = (1.0 * nranks) * g_e;
    } else if (regular_type == 1) {
      // L1Decay. grad = grad + coeff * sign(param)
      grad_out_e.device(eigen_ctx) =
          (1.0 * nranks) * g_e + regular_coeff * p_e.sign();
    } else if (regular_type == 2) {
      // L2Decay. grad = grad + coeff * param
      grad_out_e.device(eigen_ctx) = (1.0 * nranks) * g_e + regular_coeff * p_e;
    }

112
    // current step
113
    auto current_step_tensor = ctx.Input<phi::DenseTensor>("current_step");
114 115 116 117 118 119 120 121 122
    const float* current_step = current_step_tensor->data<float>();

    if (static_cast<int>(*current_step) < static_cast<int>(rampup_begin_step)) {
      VLOG(10) << "current_step:" << *current_step
               << " < rampup_begin_step:" << rampup_begin_step
               << " so does't use dgc";
      return;
    }

123 124 125 126
    float ratio = 1 - get_period_sparcity(
                          sparsity,
                          static_cast<float>(*current_step - rampup_begin_step),
                          rampup_step);
127
    PADDLE_ENFORCE_GE(
128 129
        ratio,
        0.0,
130 131
        platform::errors::InvalidArgument("DGC sparsity ratio must >= 0"));
    PADDLE_ENFORCE_LT(
132 133
        ratio,
        1.0,
134
        platform::errors::InvalidArgument("DGC sparsity ratio must < 1"));
135 136 137 138 139 140
    int k = static_cast<int>(g->numel() * ratio);

    VLOG(10) << "m:" << m << ", use_nesterov:" << use_nesterov
             << ", rampup_begin_step:" << rampup_begin_step
             << ", rampup_step:" << rampup_step
             << ",  current_step:" << *current_step << ", ratio:" << ratio
141
             << ", k:" << k << ", nranks:" << nranks;
142

143
    auto k_out = ctx.Output<phi::DenseTensor>("k");
144 145 146
    T* k_out_data = k_out->data<T>();
    *k_out_data = k;

147 148 149 150
    auto u_out = ctx.Output<phi::DenseTensor>("U_out");
    auto v_out = ctx.Output<phi::DenseTensor>("V_out");
    auto encode_grad_out = ctx.Output<phi::DenseTensor>("EncodeGrad");
    auto gather_buff = ctx.Output<phi::DenseTensor>("GatherBuff");
151 152 153 154

    // FIXME(gongwb): use cublas.
    auto u_out_e = framework::EigenVector<T>::Flatten(*u_out);
    auto u_e = framework::EigenVector<T>::Flatten(*u);
155

156 157 158 159 160 161
    // calc local momentum from global momentum
    // NOTE. If grad not multi nranks, need add below code.
    // if (static_cast<int>(*current_step) ==
    //     static_cast<int>(rampup_begin_step)) {
    //   u_out_e.device(eigen_ctx) = (1.0 / nranks) * u_e;
    // }
162

163 164
    if (use_nesterov) {
      // u = m * (u + g)
165
      u_out_e.device(eigen_ctx) = m * (u_e + grad_out_e);
166 167

      // v = u + v + g
168 169
      ElementwiseComputeEx<phi::funcs::AddFunctor<T>, DeviceContext, T>(
          ctx, u, v, 0, phi::funcs::AddFunctor<T>(), v_out);
170

171 172
      ElementwiseComputeEx<phi::funcs::AddFunctor<T>, DeviceContext, T>(
          ctx, g, v, 0, phi::funcs::AddFunctor<T>(), v_out);
173 174
    } else {
      // u = m * u + g
175
      u_out_e.device(eigen_ctx) = m * u_e + grad_out_e;
176 177

      // v = u + v
178 179
      ElementwiseComputeEx<phi::funcs::AddFunctor<T>, DeviceContext, T>(
          ctx, u, v, 0, phi::funcs::AddFunctor<T>(), v_out);
180 181 182 183 184 185
    }

    T* v_out_data = v_out->mutable_data<T>(ctx.GetPlace());
    T* u_out_data = u_out->mutable_data<T>(ctx.GetPlace());
    T* encode_grad_out_data = encode_grad_out->mutable_data<T>(
        framework::DDim{2 * k}, ctx.GetPlace());
186 187
    gather_buff->mutable_data<T>(framework::DDim{2 * k * nranks},
                                 ctx.GetPlace());
188 189

    int buf_size = paddle::communication::dgc::get_buffer_size(k);
190 191 192 193 194 195 196 197 198 199 200 201 202
    paddle::memory::allocation::AllocationPtr tmp_ious_data;
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    if (platform::is_gpu_place(dev_ctx.GetPlace())) {
      tmp_ious_data = memory::Alloc(
          dev_ctx.GetPlace(),
          buf_size,
          phi::Stream(reinterpret_cast<phi::StreamId>(dev_ctx.stream())));
    }
#endif
    if (platform::is_cpu_place(dev_ctx.GetPlace())) {
      tmp_ious_data = memory::Alloc(dev_ctx.GetPlace(), buf_size);
    }

203 204 205
    void* buf = reinterpret_cast<void*>(tmp_ious_data->ptr());

    if (!paddle::communication::dgc::k_select(
206 207 208 209 210 211
            static_cast<void*>(encode_grad_out_data),
            k,
            v_out_data,
            static_cast<int>(v_out->numel()),
            buf,
            dev_ctx.stream(),
212
            u_out_data)) {
213 214 215
      // TODO(weihang): owner should polish this error message
      PADDLE_THROW(platform::errors::InvalidArgument(
          "V_out numel error, V_out numel is %d.", v_out->numel()));
216 217
    }

218
    phi::funcs::SetConstant<DeviceContext, T> tset;
219 220 221 222 223
    tset(dev_ctx, grad_out, static_cast<T>(0));
  }
};
}  // namespace operators
}  // namespace paddle