“2719599e62c364ea76ec0e9116c36da0e451fe8c”上不存在“paddle/fluid/inference/api/api_impl_tester.cc”
matrix_bit_code.h 8.8 KB
Newer Older
Y
Yancey1989 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2017 PaddlePaddle Authors. All Rights Reserve.

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
W
weixing02 已提交
16
#include "paddle/fluid/framework/eigen.h"
J
JiabinYang 已提交
17 18
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/selected_rows.h"
W
weixing02 已提交
19 20
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/platform/device_context.h"
Y
Yancey1989 已提交
21

D
dzhwinter 已提交
22 23 24 25 26
#if defined(_WIN32)
#include <intrin.h>
#include <windows.h>
#endif  // _WIN32

Y
Yancey1989 已提交
27 28 29
namespace paddle {
namespace operators {
namespace math {
W
weixing02 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
/**
 * SimpleCodeTable class should support 3 functions:
 *
 * size_t size()
 *   return the number of ids
 *
 * int get_max_code_length()
 *   return the maximal code length
 *
 * SimpleCode operator()(size_t i)
 *   return the i-th code. Code class is descriebed below.
 *
 * SimpleCode class should support 3 functions:
 *
 * int get_length()
 *   return the length of the code
 *
 * size_t cal_index(int bit)
 *   bit ranges from 0 to get_length() - 1
 *   return the index for the (1+bit) level parent
 *
 * bool calc_bit(int bit)
 *   return true if the bit level parent is the right child of (1+bit) level
 *   parent
 *
 */
Y
Yancey1989 已提交
56 57 58 59 60 61

/**
 * return the 1-based index of the highest bit set
 *
 * for x > 0:
 * \f[
W
weixing02 已提交
62
 *    FindLastSet(x) = 1 + \floor*{\log_{2}x}
Y
Yancey1989 已提交
63 64
 * \f]
 */
D
dzhwinter 已提交
65
#if !defined(_WIN32)
Y
Yancey1989 已提交
66 67 68 69 70 71
inline constexpr size_t FindLastSet(size_t x) {
  return std::is_same<size_t, unsigned int>::value
             ? (x ? 8 * sizeof(x) - __builtin_clz(x) : 0)
             : (std::is_same<size_t, unsigned long>::value  // NOLINT
                    ? (x ? 8 * sizeof(x) - __builtin_clzl(x) : 0)
                    : (x ? 8 * sizeof(x) - __builtin_clzll(x) : 0));
W
wopeizl 已提交
72
}
D
dzhwinter 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
#else
// windows don't have built-in clz, ctz function
template <typename T>
inline int ctz(const T& value) {
  DWORD trailing_zero = 0;
  if (_BitScanForward(&trailing_zero, value)) {
    return static_cast<int>(trailing_zero);
  } else {
    return static_cast<int>(0);
  }
}

template <typename T>
inline int clz(const T& value) {
  DWORD leadning_zero = 0;
  if (_BitScanReverse(&leadning_zero, value)) {
    return static_cast<int>(sizeof(T) * 8 - leadning_zero);
  } else {
    return static_cast<int>(0);
  }
}

inline size_t FindLastSet(size_t x) { return sizeof(size_t) * 8 - clz(x); }
#endif  // !_WIN32
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
// set a code interface to create multiple code
class Code {
 public:
  virtual ~Code() {}
  virtual size_t calc_index(int bit) const = 0;
  virtual bool calc_bit(int bit) const = 0;
  virtual int get_length() const = 0;
};
// set a CodeTable interface to create multiple code table
class CodeTable {
 public:
  virtual std::unique_ptr<Code> get_code(int64_t code) const = 0;
  virtual size_t size() const = 0;
  virtual int get_max_code_length() const = 0;
  virtual ~CodeTable() {}
};
Y
Yancey1989 已提交
113

114 115 116 117
class SimpleCode : public Code {
 public:
  SimpleCode(size_t code, size_t num_classes, const int64_t* ids)
      : c_(static_cast<size_t>(ids[code]) + num_classes) {}
G
guosheng 已提交
118
  /**
119 120 121 122 123 124 125
   * Here the id of root shoud be 1 rather than 0, thus the encoding of class c
   * is `c + num_classes` and all siblings can get the same weight indice using
   * prefixes.
   * Weight index is the prefixes of encoding, thus leave out the right most
   * bit in calc_index.
   * Binary classification path is the suffixes of encoding, thus leave out the
   * left most bit in calc_bit.
G
guosheng 已提交
126
   */
127 128 129
  size_t calc_index(int bit) const { return (c_ >> (bit + 1)) - 1; }
  bool calc_bit(int bit) const { return c_ & (1 << bit); }
  int get_length() const { return FindLastSet(c_) - 1; }
Y
Yancey1989 已提交
130 131

 private:
132
  size_t c_;
Y
Yancey1989 已提交
133 134
};

135 136 137
template <typename R>
class CustomCode : public Code {
 public:
J
JiabinYang 已提交
138 139 140
  CustomCode(const framework::LoDTensor* ptable,
             const framework::LoDTensor* pcode, const int64_t* ids,
             const int index)
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
      : ptable_(ptable), pcode_(pcode), ids_(ids), index_(index) {}
  /**
   * Here the id of root shoud be 1 rather than 0, thus the encoding of class c
   * is `c + num_classes` and all siblings can get the same weight indice using
   * prefixes.
   * Weight index is the prefixes of encoding, thus leave out the right most
   * bit in calc_index.
   * Binary classification path is the suffixes of encoding, thus leave out the
   * left most bit in calc_bit.
   */
  size_t calc_index(int bit) const {
    return ptable_
        ->data<R>()[index_ * static_cast<int>(ptable_->dims()[1]) + bit];
  }
  bool calc_bit(int bit) const {
    return pcode_
        ->data<R>()[index_ * static_cast<int>(ptable_->dims()[1]) + bit];
  }
  int get_length() const {
    int length = 0;

J
JiabinYang 已提交
162
    for (int i = 0; i < static_cast<int>(ptable_->dims()[1]); i++) {
163
      if (ptable_->data<R>()[index_ * static_cast<int>(ptable_->dims()[1]) +
J
JiabinYang 已提交
164
                             i] >= 0) {
165 166 167 168 169 170 171 172 173
        length++;
      } else {
        return length;
      }
    }
    return length;
  }

 private:
J
JiabinYang 已提交
174 175
  const framework::LoDTensor* ptable_;
  const framework::LoDTensor* pcode_;
176 177 178 179 180 181 182 183 184 185 186
  const int64_t* ids_;
  const int index_;
};

class SimpleCodeTable : public CodeTable {
 public:
  explicit SimpleCodeTable(size_t num_classes, const int64_t* ids)
      : num_classes_(num_classes), ids_(ids) {}
  std::unique_ptr<Code> get_code(int64_t code) const {
    std::unique_ptr<Code> coder(new SimpleCode(code, num_classes_, ids_));
    return coder;
Y
Yancey1989 已提交
187 188 189 190 191 192
  }
  size_t size() const { return num_classes_; }
  int get_max_code_length() const { return FindLastSet(num_classes_ - 1); }

 private:
  size_t num_classes_;
193 194 195 196 197 198
  const int64_t* ids_;
};

template <typename R>
class CustomCodeTable : public CodeTable {
 public:
J
JiabinYang 已提交
199 200 201
  explicit CustomCodeTable(const framework::LoDTensor* ptable,
                           const framework::LoDTensor* pcode,
                           const int64_t* ids)
202 203 204 205 206 207 208 209 210 211 212 213 214
      : ptable_(ptable), pcode_(pcode), ids_(ids) {}

  std::unique_ptr<Code> get_code(int64_t code) const {
    std::unique_ptr<Code> coder(new CustomCode<R>(ptable_, pcode_, ids_, code));
    return coder;
  }

  size_t size() const { return static_cast<size_t>(ptable_->dims()[1]); }
  int get_max_code_length() const {
    return static_cast<size_t>(ptable_->dims()[1]);
  }

 private:
J
JiabinYang 已提交
215 216
  const framework::LoDTensor* ptable_;
  const framework::LoDTensor* pcode_;
217
  const int64_t* ids_;
Y
Yancey1989 已提交
218 219
};

Y
Yancey1989 已提交
220
template <typename T>
Y
Yancey1989 已提交
221 222
class MatrixBitCodeFunctor {
 public:
Y
Yancey1989 已提交
223
  explicit MatrixBitCodeFunctor(size_t num_classes, const int64_t* ids)
224 225 226 227
      : num_classes_(num_classes),
        ids_(ids),
        code_table(new SimpleCodeTable(num_classes, ids)) {}

J
JiabinYang 已提交
228 229
  explicit MatrixBitCodeFunctor(const framework::LoDTensor* ptable,
                                const framework::LoDTensor* pcode,
230 231 232 233
                                const int64_t* ids)
      : num_classes_(static_cast<size_t>(ptable->dims()[1])),
        ids_(ids),
        code_table(new CustomCodeTable<int64_t>(ptable, pcode, ids)) {}
Y
Yancey1989 已提交
234 235 236
  /* For j < code_length
       tmat(i, j) += vec(0, index(i, j))
  */
J
JiabinYang 已提交
237
  void Add(framework::LoDTensor* tmat, const framework::LoDTensor& vec);
Y
Yancey1989 已提交
238

Y
Yancey1989 已提交
239 240 241
  /* For j < code_length
       vec(0, index(i, j)) += tmat(i, j)
  */
J
JiabinYang 已提交
242
  void AddGrad(const framework::LoDTensor& tmat, framework::LoDTensor* vec);
Y
Yancey1989 已提交
243 244

  /* For j < code_length
Y
Yancey1989 已提交
245
    sum(i, 0) = \sum_j bit(i, j) * tmat(i, j)
Y
Yancey1989 已提交
246
  */
J
JiabinYang 已提交
247 248
  void Sum(const framework::LoDTensor& tmat, framework::LoDTensor* sum,
           T scale_sum);
Y
Yancey1989 已提交
249

Y
Yancey1989 已提交
250 251 252
  /* For j < code_length
       tmat(i, j) -= bit(i, j)
  */
J
JiabinYang 已提交
253
  void Sub(framework::LoDTensor* tmat);
Y
Yancey1989 已提交
254 255 256
  /* For j < code_length
       input.row(i) += tmat(i, j) * weight.row(index(i, j))
  */
J
JiabinYang 已提交
257 258
  void Mul(framework::LoDTensor* tmat, const framework::LoDTensor& weight,
           const framework::LoDTensor& input);
Y
Yancey1989 已提交
259

Y
Yancey1989 已提交
260 261 262
  /* For index(i, j) >= 0:
      weight.row(index(i, j)) += tmat(i, j) * input.row(i)
  */
J
JiabinYang 已提交
263 264 265 266 267 268 269 270 271
  void MulGradWeight(const framework::LoDTensor& tmat,
                     framework::LoDTensor* weight,
                     const framework::LoDTensor& input);
  /* For SelectedRows Weight, For index(i, j) >= 0:
      weight.row(index(i, j)) += tmat(i, j) * input.row(i)
  */
  void MulGradWeight(const framework::LoDTensor& tmat,
                     framework::SelectedRows* weight,
                     const framework::LoDTensor& input);
Y
Yancey1989 已提交
272 273 274
  /* For j < code_length
    input.row(i) += tmat(i, j) * weight.row(index(i, j))
  */
J
JiabinYang 已提交
275 276 277
  void MulGradError(const framework::LoDTensor& tmat,
                    const framework::LoDTensor& weight,
                    framework::LoDTensor* input);
W
weixing02 已提交
278

Y
Yancey1989 已提交
279 280
  size_t num_classes_;
  const int64_t* ids_;
281
  std::unique_ptr<CodeTable> code_table;
Y
Yancey1989 已提交
282
};
Y
Yancey1989 已提交
283 284 285
}  // namespace math
}  // namespace operators
}  // namespace paddle