ParameterUpdaterHook.cpp 4.6 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

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

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

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

#include "ParameterUpdaterHook.h"

Y
Yu Yang 已提交
17
#include <atomic>
Z
zhangjinchao01 已提交
18 19 20
#include <fstream>
#include <mutex>
#include <thread>
Y
Yu Yang 已提交
21
#include <unordered_map>
22
#include <vector>
X
xzl 已提交
23
#include <algorithm>
Z
zhangjinchao01 已提交
24 25 26 27

#include "paddle/math/Vector.h"
#include "paddle/parameter/Parameter.h"
#include "paddle/utils/Flags.h"
Y
Yu Yang 已提交
28
#include "paddle/utils/Util.h"
Z
zhangjinchao01 已提交
29 30 31 32 33

namespace paddle {

/**
 * The static pruning hook
X
xzl 已提交
34 35 36
 * Static means user specific a sparsity_ratio before training start, and the
 * network will prune the parameters based on the sparsity_ratio. More deatils
 * can see https://arxiv.org/pdf/1506.02626.pdf.
Z
zhangjinchao01 已提交
37 38
 */

39
class StaticPruningHook : public IParameterUpdaterHook {
X
xzl 已提交
40
public:
41
  explicit StaticPruningHook(const ParameterUpdaterHookConfig& hookConfig)
X
xzl 已提交
42 43 44 45
      : initCount_(0) {
    sparsityRatio_ = hookConfig.sparsity_ratio();
  }

46 47
  static bool sortPairAscend(const std::pair<real, size_t>& pair1,
                             const std::pair<real, size_t>& pair2) {
X
xzl 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    return pair1.first > pair2.first;
  }

  void update(Parameter* para) {
    updateThreadChecker_.check();
    auto& vec = para->getBuf(PARAMETER_GRADIENT);
    if (vec) {
      vec->dotMul(*maskVec_);
    }
  }

  void generateMask(Parameter* para) {
    VectorPtr vec = para->getBuf(PARAMETER_VALUE);
    maskTemp_ = Vector::create(para->getSize(), false);
    maskTemp_->zeroMem();
    real* dataPtr = maskTemp_->getData();
X
xzl 已提交
64
    size_t sparsityNum = para->getSize() * (1 - sparsityRatio_);
X
xzl 已提交
65 66 67

    VectorPtr vecCpu = Vector::create(para->getSize(), false);
    vecCpu->copyFrom(*vec);
68
    std::vector<std::pair<real, size_t>> param;
X
xzl 已提交
69 70 71 72

    for (size_t i = 0; i < para->getSize(); i++)
      param.push_back(std::make_pair(fabs(vecCpu->getData()[i]), i));

X
xzl 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85
    std::partial_sort(param.begin(),
                      param.begin() + sparsityNum,
                      param.end(),
                      sortPairAscend);
    for (size_t i = 0; i < sparsityNum; i++) dataPtr[param[i].second] = 1.0;

    // Currently just use a mask vector for hack.
    if (para->useGpu()) {
      maskVec_ = Vector::create(para->getSize(), para->useGpu());
      maskVec_->copyFrom(*maskTemp_);
    } else {
      maskVec_ = maskTemp_;
    }
X
xzl 已提交
86 87 88 89 90
  }

  void init(Parameter* para) {
    generateMask(para);
    size_t initCount = this->initCount_.fetch_add(1);
91
    CHECK_EQ(initCount, 0UL) << "Currently the StaticPruningHook must invoke "
X
xzl 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
                                "in same ParamterUpdater";
    VLOG(3) << "Initialize Parameter " << para;
    SetDevice device(para->getDeviceId());

    auto& vec = para->getBuf(PARAMETER_VALUE);
    vec->dotMul(*maskVec_);
  }

private:
  SameThreadChecker updateThreadChecker_;
  std::atomic<size_t> initCount_;
  VectorPtr maskVec_;
  VectorPtr maskTemp_;
  real sparsityRatio_;
};

Z
zhangjinchao01 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
IParameterUpdaterHook::IParameterUpdaterHook() {}

IParameterUpdaterHook::~IParameterUpdaterHook() {}

/**
 * A Hasher used by g_hooks.
 *
 * Use the independent hasher intendedly. There is a hasher in PServer for hash
 * ParameterBlock. But not to use same hasher to reduce dependency.
 *
 * May be extracted to Util.h to unify the hasher.
 */
class StringIntPairHasher {
public:
  size_t operator()(const std::pair<std::string, int>& k) const {
    return intHasher_(strHasher_(k.first) + k.second);
  }

private:
  std::hash<std::string> strHasher_;
  std::hash<int> intHasher_;
};

131 132
static WeakKVCache<std::pair<std::string, int>,
                   IParameterUpdaterHook,
Z
Zhaolong Xing 已提交
133
                   StringIntPairHasher>
Z
Zhaolong Xing 已提交
134
    g_hookCache_;
Z
zhangjinchao01 已提交
135 136 137 138 139 140 141

/**
 * ParameterUpdaterHook actually factory method.
 */
static IParameterUpdaterHook* createImpl(
    const ParameterUpdaterHookConfig& config) {
  auto& type = config.type();
142
  if (type == "pruning") {
X
xzl 已提交
143
    return new StaticPruningHook(config);
Z
zhangjinchao01 已提交
144
  }
X
xzl 已提交
145 146

  LOG(FATAL) << "Unknown Hook type:  " << type;
Z
zhangjinchao01 已提交
147 148 149 150 151 152 153 154 155 156 157
  return nullptr;
}

std::shared_ptr<IParameterUpdaterHook> IParameterUpdaterHook::create(
    const ParameterConfig& paramConfig, int idx) {
  std::pair<std::string, int> key = {paramConfig.name(), idx};
  return g_hookCache_.get(
      key, [&] { return createImpl(paramConfig.update_hooks(idx)); });
}

}  // namespace paddle