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>
Z
zhangjinchao01 已提交
23 24 25 26

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

namespace paddle {

/**
 * The static pruning hook
X
xzl 已提交
33 34 35
 * 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 已提交
36 37
 */

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

45 46
  static bool sortPairAscend(const std::pair<real, size_t>& pair1,
                             const std::pair<real, size_t>& pair2) {
X
xzl 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
    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();

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

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

    for (size_t i = 0; i < para->getSize() * sparsityRatio_; i++)
      dataPtr[param[i].second] = 1.0;
  }

  void init(Parameter* para) {
    generateMask(para);
    size_t initCount = this->initCount_.fetch_add(1);
79
    CHECK_EQ(initCount, 0UL) << "Currently the StaticPruningHook must invoke "
X
xzl 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
                                "in same ParamterUpdater";
    VLOG(3) << "Initialize Parameter " << para;
    SetDevice device(para->getDeviceId());

    // Currently just use a mask vector for hack.
    // @TODO(yuyang18): Implemented the mask operation in vector.
    if (para->useGpu()) {
      maskVec_ = Vector::create(para->getSize(), para->useGpu());
      maskVec_->copyFrom(*maskTemp_);
    } else {
      maskVec_ = maskTemp_;
    }

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

128 129
static WeakKVCache<std::pair<std::string, int>,
                   IParameterUpdaterHook,
X
xzl 已提交
130
                   StringIntPairHasher> g_hookCache_;
Z
zhangjinchao01 已提交
131 132 133 134 135 136 137

/**
 * ParameterUpdaterHook actually factory method.
 */
static IParameterUpdaterHook* createImpl(
    const ParameterUpdaterHookConfig& config) {
  auto& type = config.type();
138
  if (type == "pruning") {
X
xzl 已提交
139
    if (config.has_sparsity_ratio())
140
      return new StaticPruningHook(config);
X
xzl 已提交
141 142 143
    else
      LOG(FATAL) << "There must be sparsity_ratio parameter for " << type
                 << " Hook";
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