ParameterUpdaterHook.cpp 4.5 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"

Z
Zhaolong Xing 已提交
17
#include <algorithm>
Y
Yu Yang 已提交
18
#include <atomic>
Z
zhangjinchao01 已提交
19 20 21
#include <fstream>
#include <mutex>
#include <thread>
Y
Yu Yang 已提交
22
#include <unordered_map>
23
#include <vector>
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
34
 * Static means user specify a sparsity_ratio before training started, and the
X
xzl 已提交
35
 * network will prune the parameters based on the sparsity_ratio. More deatils
36
 * can be found 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
    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) {
60 61 62 63

    VectorPtr maskTemp = Vector::create(para->getSize(), false);
    maskTemp->zeroMem();
    real* maskTempData = maskTemp->getData();
Z
zlx 已提交
64
    size_t nonZeroNum = para->getSize() * (1 - sparsityRatio_);
X
xzl 已提交
65

66 67 68 69
    VectorPtr paraVec = para->getBuf(PARAMETER_VALUE);
    VectorPtr paraCpuCopy = Vector::create(para->getSize(), false);

    paraCpuCopy->copyFrom(*paraVec);
70
    std::vector<std::pair<real, size_t>> param;
X
xzl 已提交
71 72

    for (size_t i = 0; i < para->getSize(); i++)
73
      param.push_back(std::make_pair(fabs(paraCpuCopy->getData()[i]), i));
X
xzl 已提交
74

Z
Zhaolong Xing 已提交
75 76
    std::partial_sort(
        param.begin(), param.begin() + nonZeroNum, param.end(), sortPairAscend);
77
    for (size_t i = 0; i < nonZeroNum; i++) maskTempData[param[i].second] = 1.0;
X
xzl 已提交
78 79 80 81

    // Currently just use a mask vector for hack.
    if (para->useGpu()) {
      maskVec_ = Vector::create(para->getSize(), para->useGpu());
82
      maskVec_->copyFrom(*maskTemp);
X
xzl 已提交
83
    } else {
84
      maskVec_ = maskTemp;
X
xzl 已提交
85
    }
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
                                "in same ParamterUpdater";
    VLOG(3) << "Initialize Parameter " << para;
    SetDevice device(para->getDeviceId());

96 97
    auto& paraVec = para->getBuf(PARAMETER_VALUE);
    paraVec->dotMul(*maskVec_);
X
xzl 已提交
98 99 100 101 102 103 104 105 106
  }

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

Z
zhangjinchao01 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
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_;
};

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

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

  LOG(FATAL) << "Unknown Hook type:  " << type;
Z
zhangjinchao01 已提交
146 147 148 149 150 151 152 153 154 155 156
  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