tesseract  4.0.0-beta.1-59-g2cc4
tesseract::WeightMatrix Class Reference

#include <weightmatrix.h>

Public Member Functions

 WeightMatrix ()
 
int InitWeightsFloat (int no, int ni, bool use_adam, float weight_range, TRand *randomizer)
 
int RemapOutputs (const std::vector< int > &code_map)
 
void ConvertToInt ()
 
int RoundInputs (int size) const
 
bool is_int_mode () const
 
int NumOutputs () const
 
const double * GetWeights (int index) const
 
double GetDW (int i, int j) const
 
void InitBackward ()
 
bool Serialize (bool training, TFile *fp) const
 
bool DeSerialize (bool training, TFile *fp)
 
bool DeSerializeOld (bool training, TFile *fp)
 
void MatrixDotVector (const double *u, double *v) const
 
void MatrixDotVector (const int8_t *u, double *v) const
 
void MultiplyAccumulate (const double *v, double *inout)
 
void VectorDotMatrix (const double *u, double *v) const
 
void SumOuterTransposed (const TransposedArray &u, const TransposedArray &v, bool parallel)
 
void Update (double learning_rate, double momentum, double adam_beta, int num_samples)
 
void AddDeltas (const WeightMatrix &other)
 
void CountAlternators (const WeightMatrix &other, double *same, double *changed) const
 
void Debug2D (const char *msg)
 

Static Public Member Functions

static double DotProduct (const double *u, const double *v, int n)
 
static void FloatToDouble (const GENERIC_2D_ARRAY< float > &wf, GENERIC_2D_ARRAY< double > *wd)
 

Detailed Description

Definition at line 65 of file weightmatrix.h.

Constructor & Destructor Documentation

◆ WeightMatrix()

tesseract::WeightMatrix::WeightMatrix ( )
inline

Definition at line 67 of file weightmatrix.h.

67 : int_mode_(false), use_adam_(false) {}

Member Function Documentation

◆ AddDeltas()

void tesseract::WeightMatrix::AddDeltas ( const WeightMatrix other)

Definition at line 306 of file weightmatrix.cpp.

306  {
307  ASSERT_HOST(dw_.dim1() == other.dw_.dim1());
308  ASSERT_HOST(dw_.dim2() == other.dw_.dim2());
309  dw_ += other.dw_;
310 }
int dim1() const
Definition: matrix.h:205
#define ASSERT_HOST(x)
Definition: errcode.h:84
int dim2() const
Definition: matrix.h:206

◆ ConvertToInt()

void tesseract::WeightMatrix::ConvertToInt ( )

Definition at line 100 of file weightmatrix.cpp.

100  {
101  wi_.ResizeNoInit(wf_.dim1(), wf_.dim2());
102  scales_.init_to_size(wi_.dim1(), 0.0);
103  int dim2 = wi_.dim2();
104  for (int t = 0; t < wi_.dim1(); ++t) {
105  double* f_line = wf_[t];
106  int8_t* i_line = wi_[t];
107  double max_abs = 0.0;
108  for (int f = 0; f < dim2; ++f) {
109  double abs_val = fabs(f_line[f]);
110  if (abs_val > max_abs) max_abs = abs_val;
111  }
112  double scale = max_abs / INT8_MAX;
113  scales_[t] = scale;
114  if (scale == 0.0) scale = 1.0;
115  for (int f = 0; f < dim2; ++f) {
116  i_line[f] = IntCastRounded(f_line[f] / scale);
117  }
118  }
119  wf_.Resize(1, 1, 0.0);
120  int_mode_ = true;
121  multiplier_.reset(IntSimdMatrix::GetFastestMultiplier());
122  if (multiplier_ != nullptr) multiplier_->Init(wi_);
123 }
void ResizeNoInit(int size1, int size2, int pad=0)
Definition: matrix.h:88
void Resize(int size1, int size2, const T &empty)
Definition: matrix.h:102
static IntSimdMatrix * GetFastestMultiplier()
int dim1() const
Definition: matrix.h:205
int dim2() const
Definition: matrix.h:206
int IntCastRounded(double x)
Definition: helpers.h:179
void init_to_size(int size, T t)

◆ CountAlternators()

void tesseract::WeightMatrix::CountAlternators ( const WeightMatrix other,
double *  same,
double *  changed 
) const

Definition at line 315 of file weightmatrix.cpp.

316  {
317  int num_outputs = updates_.dim1();
318  int num_inputs = updates_.dim2();
319  ASSERT_HOST(num_outputs == other.updates_.dim1());
320  ASSERT_HOST(num_inputs == other.updates_.dim2());
321  for (int i = 0; i < num_outputs; ++i) {
322  const double* this_i = updates_[i];
323  const double* other_i = other.updates_[i];
324  for (int j = 0; j < num_inputs; ++j) {
325  double product = this_i[j] * other_i[j];
326  if (product < 0.0)
327  *changed -= product;
328  else
329  *same += product;
330  }
331  }
332 }
int dim1() const
Definition: matrix.h:205
#define ASSERT_HOST(x)
Definition: errcode.h:84
int dim2() const
Definition: matrix.h:206

◆ Debug2D()

void tesseract::WeightMatrix::Debug2D ( const char *  msg)

Definition at line 346 of file weightmatrix.cpp.

346  {
347  STATS histogram(0, kHistogramBuckets);
348  if (int_mode_) {
349  for (int i = 0; i < wi_.dim1(); ++i) {
350  for (int j = 0; j < wi_.dim2(); ++j) {
351  HistogramWeight(wi_[i][j] * scales_[i], &histogram);
352  }
353  }
354  } else {
355  for (int i = 0; i < wf_.dim1(); ++i) {
356  for (int j = 0; j < wf_.dim2(); ++j) {
357  HistogramWeight(wf_[i][j], &histogram);
358  }
359  }
360  }
361  tprintf("%s\n", msg);
362  histogram.print();
363 }
const int kHistogramBuckets
int dim1() const
Definition: matrix.h:205
Definition: statistc.h:33
#define tprintf(...)
Definition: tprintf.h:31
int dim2() const
Definition: matrix.h:206

◆ DeSerialize()

bool tesseract::WeightMatrix::DeSerialize ( bool  training,
TFile fp 
)

Definition at line 165 of file weightmatrix.cpp.

165  {
166  uint8_t mode = 0;
167  if (fp->FRead(&mode, sizeof(mode), 1) != 1) return false;
168  int_mode_ = (mode & kInt8Flag) != 0;
169  use_adam_ = (mode & kAdamFlag) != 0;
170  if ((mode & kDoubleFlag) == 0) return DeSerializeOld(training, fp);
171  if (int_mode_) {
172  if (!wi_.DeSerialize(fp)) return false;
173  if (!scales_.DeSerialize(fp)) return false;
174  multiplier_.reset(IntSimdMatrix::GetFastestMultiplier());
175  if (multiplier_ != nullptr) multiplier_->Init(wi_);
176  } else {
177  if (!wf_.DeSerialize(fp)) return false;
178  if (training) {
179  InitBackward();
180  if (!updates_.DeSerialize(fp)) return false;
181  if (use_adam_ && !dw_sq_sum_.DeSerialize(fp)) return false;
182  }
183  }
184  return true;
185 }
static IntSimdMatrix * GetFastestMultiplier()
const int kDoubleFlag
const int kInt8Flag
bool DeSerialize(bool swap, FILE *fp)
Definition: matrix.h:159
bool DeSerialize(bool swap, FILE *fp)
const int kAdamFlag
CMD_EVENTS mode
Definition: pgedit.cpp:116
bool DeSerializeOld(bool training, TFile *fp)

◆ DeSerializeOld()

bool tesseract::WeightMatrix::DeSerializeOld ( bool  training,
TFile fp 
)

Definition at line 189 of file weightmatrix.cpp.

189  {
190  GENERIC_2D_ARRAY<float> float_array;
191  if (int_mode_) {
192  if (!wi_.DeSerialize(fp)) return false;
193  GenericVector<float> old_scales;
194  if (!old_scales.DeSerialize(fp)) return false;
195  scales_.resize_no_init(old_scales.size());
196  for (int i = 0; i < old_scales.size(); ++i) scales_[i] = old_scales[i];
197  } else {
198  if (!float_array.DeSerialize(fp)) return false;
199  FloatToDouble(float_array, &wf_);
200  }
201  if (training) {
202  InitBackward();
203  if (!float_array.DeSerialize(fp)) return false;
204  FloatToDouble(float_array, &updates_);
205  // Errs was only used in int training, which is now dead.
206  if (!float_array.DeSerialize(fp)) return false;
207  }
208  return true;
209 }
bool DeSerialize(bool swap, FILE *fp)
Definition: matrix.h:159
int size() const
Definition: genericvector.h:72
void resize_no_init(int size)
Definition: genericvector.h:66
bool DeSerialize(bool swap, FILE *fp)
static void FloatToDouble(const GENERIC_2D_ARRAY< float > &wf, GENERIC_2D_ARRAY< double > *wd)

◆ DotProduct()

double tesseract::WeightMatrix::DotProduct ( const double *  u,
const double *  v,
int  n 
)
static

Definition at line 367 of file weightmatrix.cpp.

367  {
368  // Note: because the order of addition is different among the 3 DotProduct
369  // functions, the results can (and do) vary slightly (although they agree
370  // to within about 4e-15). This produces different results when running
371  // training, despite all random inputs being precisely equal.
372  // To get consistent results, use just one of these DotProduct functions.
373  // On a test multi-layer network, serial is 57% slower than sse, and avx
374  // is about 8% faster than sse. This suggests that the time is memory
375  // bandwidth constrained and could benefit from holding the reused vector
376  // in AVX registers.
377  if (SIMDDetect::IsAVXAvailable()) return DotProductAVX(u, v, n);
378  if (SIMDDetect::IsSSEAvailable()) return DotProductSSE(u, v, n);
379  double total = 0.0;
380  for (int k = 0; k < n; ++k) total += u[k] * v[k];
381  return total;
382 }
static bool IsAVXAvailable()
Definition: simddetect.h:26
static bool IsSSEAvailable()
Definition: simddetect.h:38
double DotProductSSE(const double *u, const double *v, int n)
double DotProductAVX(const double *u, const double *v, int n)

◆ FloatToDouble()

void tesseract::WeightMatrix::FloatToDouble ( const GENERIC_2D_ARRAY< float > &  wf,
GENERIC_2D_ARRAY< double > *  wd 
)
static

Definition at line 387 of file weightmatrix.cpp.

388  {
389  int dim1 = wf.dim1();
390  int dim2 = wf.dim2();
391  wd->ResizeNoInit(dim1, dim2);
392  for (int i = 0; i < dim1; ++i) {
393  const float* wfi = wf[i];
394  double* wdi = (*wd)[i];
395  for (int j = 0; j < dim2; ++j) wdi[j] = static_cast<double>(wfi[j]);
396  }
397 }
void ResizeNoInit(int size1, int size2, int pad=0)
Definition: matrix.h:88
int dim1() const
Definition: matrix.h:205
int dim2() const
Definition: matrix.h:206

◆ GetDW()

double tesseract::WeightMatrix::GetDW ( int  i,
int  j 
) const
inline

Definition at line 105 of file weightmatrix.h.

105 { return dw_(i, j); }

◆ GetWeights()

const double* tesseract::WeightMatrix::GetWeights ( int  index) const
inline

Definition at line 103 of file weightmatrix.h.

103 { return wf_[index]; }

◆ InitBackward()

void tesseract::WeightMatrix::InitBackward ( )

Definition at line 127 of file weightmatrix.cpp.

127  {
128  int no = int_mode_ ? wi_.dim1() : wf_.dim1();
129  int ni = int_mode_ ? wi_.dim2() : wf_.dim2();
130  dw_.Resize(no, ni, 0.0);
131  updates_.Resize(no, ni, 0.0);
132  wf_t_.Transpose(wf_);
133  if (use_adam_) dw_sq_sum_.Resize(no, ni, 0.0);
134 }
void Resize(int size1, int size2, const T &empty)
Definition: matrix.h:102
void Transpose(const GENERIC_2D_ARRAY< double > &input)
int dim1() const
Definition: matrix.h:205
int dim2() const
Definition: matrix.h:206

◆ InitWeightsFloat()

int tesseract::WeightMatrix::InitWeightsFloat ( int  no,
int  ni,
bool  use_adam,
float  weight_range,
TRand randomizer 
)

Definition at line 51 of file weightmatrix.cpp.

52  {
53  int_mode_ = false;
54  wf_.Resize(no, ni, 0.0);
55  if (randomizer != nullptr) {
56  for (int i = 0; i < no; ++i) {
57  for (int j = 0; j < ni; ++j) {
58  wf_[i][j] = randomizer->SignedRand(weight_range);
59  }
60  }
61  }
62  use_adam_ = use_adam;
63  InitBackward();
64  return ni * no;
65 }
void Resize(int size1, int size2, const T &empty)
Definition: matrix.h:102

◆ is_int_mode()

bool tesseract::WeightMatrix::is_int_mode ( ) const
inline

Definition at line 98 of file weightmatrix.h.

98  {
99  return int_mode_;
100  }

◆ MatrixDotVector() [1/2]

void tesseract::WeightMatrix::MatrixDotVector ( const double *  u,
double *  v 
) const

Definition at line 216 of file weightmatrix.cpp.

216  {
217  ASSERT_HOST(!int_mode_);
218  MatrixDotVectorInternal(wf_, true, false, u, v);
219 }
#define ASSERT_HOST(x)
Definition: errcode.h:84

◆ MatrixDotVector() [2/2]

void tesseract::WeightMatrix::MatrixDotVector ( const int8_t *  u,
double *  v 
) const

Definition at line 221 of file weightmatrix.cpp.

221  {
222  ASSERT_HOST(int_mode_);
223  ASSERT_HOST(multiplier_ != nullptr);
224  multiplier_->MatrixDotVector(wi_, scales_, u, v);
225 }
#define ASSERT_HOST(x)
Definition: errcode.h:84

◆ MultiplyAccumulate()

void tesseract::WeightMatrix::MultiplyAccumulate ( const double *  v,
double *  inout 
)

Definition at line 229 of file weightmatrix.cpp.

229  {
230  ASSERT_HOST(!int_mode_);
231  ASSERT_HOST(wf_.dim1() == 1);
232  int n = wf_.dim2();
233  const double* u = wf_[0];
234  for (int i = 0; i < n; ++i) {
235  inout[i] += u[i] * v[i];
236  }
237 }
int dim1() const
Definition: matrix.h:205
#define ASSERT_HOST(x)
Definition: errcode.h:84
int dim2() const
Definition: matrix.h:206

◆ NumOutputs()

int tesseract::WeightMatrix::NumOutputs ( ) const
inline

Definition at line 101 of file weightmatrix.h.

101 { return int_mode_ ? wi_.dim1() : wf_.dim1(); }
int dim1() const
Definition: matrix.h:205

◆ RemapOutputs()

int tesseract::WeightMatrix::RemapOutputs ( const std::vector< int > &  code_map)

Definition at line 72 of file weightmatrix.cpp.

72  {
73  GENERIC_2D_ARRAY<double> old_wf(wf_);
74  int old_no = wf_.dim1();
75  int new_no = code_map.size();
76  int ni = wf_.dim2();
77  std::vector<double> means(ni, 0.0);
78  for (int c = 0; c < old_no; ++c) {
79  const double* weights = wf_[c];
80  for (int i = 0; i < ni; ++i) means[i] += weights[i];
81  }
82  for (double& mean : means) mean /= old_no;
83  wf_.ResizeNoInit(new_no, ni);
84  InitBackward();
85  for (int dest = 0; dest < new_no; ++dest) {
86  int src = code_map[dest];
87  const double* src_data = src >= 0 ? old_wf[src] : means.data();
88  memcpy(wf_[dest], src_data, ni * sizeof(*src_data));
89  }
90  return ni * new_no;
91 }
void ResizeNoInit(int size1, int size2, int pad=0)
Definition: matrix.h:88
int dim1() const
Definition: matrix.h:205
int dim2() const
Definition: matrix.h:206

◆ RoundInputs()

int tesseract::WeightMatrix::RoundInputs ( int  size) const
inline

Definition at line 92 of file weightmatrix.h.

92  {
93  if (multiplier_ == nullptr) return size;
94  return multiplier_->RoundInputs(size);
95  }

◆ Serialize()

bool tesseract::WeightMatrix::Serialize ( bool  training,
TFile fp 
) const

Definition at line 146 of file weightmatrix.cpp.

146  {
147  // For backward compatibility, add kDoubleFlag to mode to indicate the doubles
148  // format, without errs, so we can detect and read old format weight matrices.
149  uint8_t mode =
150  (int_mode_ ? kInt8Flag : 0) | (use_adam_ ? kAdamFlag : 0) | kDoubleFlag;
151  if (fp->FWrite(&mode, sizeof(mode), 1) != 1) return false;
152  if (int_mode_) {
153  if (!wi_.Serialize(fp)) return false;
154  if (!scales_.Serialize(fp)) return false;
155  } else {
156  if (!wf_.Serialize(fp)) return false;
157  if (training && !updates_.Serialize(fp)) return false;
158  if (training && use_adam_ && !dw_sq_sum_.Serialize(fp)) return false;
159  }
160  return true;
161 }
const int kDoubleFlag
const int kInt8Flag
bool Serialize(FILE *fp) const
Definition: matrix.h:141
bool Serialize(FILE *fp) const
const int kAdamFlag
CMD_EVENTS mode
Definition: pgedit.cpp:116

◆ SumOuterTransposed()

void tesseract::WeightMatrix::SumOuterTransposed ( const TransposedArray u,
const TransposedArray v,
bool  parallel 
)

Definition at line 253 of file weightmatrix.cpp.

255  {
256  ASSERT_HOST(!int_mode_);
257  int num_outputs = dw_.dim1();
258  ASSERT_HOST(u.dim1() == num_outputs);
259  ASSERT_HOST(u.dim2() == v.dim2());
260  int num_inputs = dw_.dim2() - 1;
261  int num_samples = u.dim2();
262  // v is missing the last element in dim1.
263  ASSERT_HOST(v.dim1() == num_inputs);
264 #ifdef _OPENMP
265 #pragma omp parallel for num_threads(4) if (in_parallel)
266 #endif
267  for (int i = 0; i < num_outputs; ++i) {
268  double* dwi = dw_[i];
269  const double* ui = u[i];
270  for (int j = 0; j < num_inputs; ++j) {
271  dwi[j] = DotProduct(ui, v[j], num_samples);
272  }
273  // The last element of v is missing, presumed 1.0f.
274  double total = 0.0;
275  for (int k = 0; k < num_samples; ++k) total += ui[k];
276  dwi[num_inputs] = total;
277  }
278 }
int dim1() const
Definition: matrix.h:205
#define ASSERT_HOST(x)
Definition: errcode.h:84
int dim2() const
Definition: matrix.h:206
static double DotProduct(const double *u, const double *v, int n)

◆ Update()

void tesseract::WeightMatrix::Update ( double  learning_rate,
double  momentum,
double  adam_beta,
int  num_samples 
)

Definition at line 283 of file weightmatrix.cpp.

284  {
285  ASSERT_HOST(!int_mode_);
286  if (use_adam_ && num_samples > 0 && num_samples < kAdamCorrectionIterations) {
287  learning_rate *= sqrt(1.0 - pow(adam_beta, num_samples));
288  learning_rate /= 1.0 - pow(momentum, num_samples);
289  }
290  if (use_adam_ && num_samples > 0 && momentum > 0.0) {
291  dw_sq_sum_.SumSquares(dw_, adam_beta);
292  dw_ *= learning_rate * (1.0 - momentum);
293  updates_ *= momentum;
294  updates_ += dw_;
295  wf_.AdamUpdate(updates_, dw_sq_sum_, learning_rate * kAdamEpsilon);
296  } else {
297  dw_ *= learning_rate;
298  updates_ += dw_;
299  if (momentum > 0.0) wf_ += updates_;
300  if (momentum >= 0.0) updates_ *= momentum;
301  }
302  wf_t_.Transpose(wf_);
303 }
void Transpose(const GENERIC_2D_ARRAY< double > &input)
const int kAdamCorrectionIterations
const double kAdamEpsilon
void AdamUpdate(const GENERIC_2D_ARRAY< T > &sum, const GENERIC_2D_ARRAY< T > &sqsum, T epsilon)
Definition: matrix.h:378
#define ASSERT_HOST(x)
Definition: errcode.h:84
void SumSquares(const GENERIC_2D_ARRAY< T > &src, T decay_factor)
Definition: matrix.h:367

◆ VectorDotMatrix()

void tesseract::WeightMatrix::VectorDotMatrix ( const double *  u,
double *  v 
) const

Definition at line 243 of file weightmatrix.cpp.

243  {
244  ASSERT_HOST(!int_mode_);
245  MatrixDotVectorInternal(wf_t_, false, true, u, v);
246 }
#define ASSERT_HOST(x)
Definition: errcode.h:84

The documentation for this class was generated from the following files: