tesseract  4.0.0-1-g2a2b
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 66 of file weightmatrix.h.

Constructor & Destructor Documentation

◆ WeightMatrix()

tesseract::WeightMatrix::WeightMatrix ( )
inline

Definition at line 68 of file weightmatrix.h.

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

Member Function Documentation

◆ AddDeltas()

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

Definition at line 311 of file weightmatrix.cpp.

311  {
312  ASSERT_HOST(dw_.dim1() == other.dw_.dim1());
313  ASSERT_HOST(dw_.dim2() == other.dw_.dim2());
314  dw_ += other.dw_;
315 }
int dim1() const
Definition: matrix.h:206
int dim2() const
Definition: matrix.h:207
#define ASSERT_HOST(x)
Definition: errcode.h:84

◆ ConvertToInt()

void tesseract::WeightMatrix::ConvertToInt ( )

Definition at line 105 of file weightmatrix.cpp.

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

◆ CountAlternators()

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

Definition at line 320 of file weightmatrix.cpp.

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

◆ Debug2D()

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

Definition at line 351 of file weightmatrix.cpp.

351  {
352  STATS histogram(0, kHistogramBuckets);
353  if (int_mode_) {
354  for (int i = 0; i < wi_.dim1(); ++i) {
355  for (int j = 0; j < wi_.dim2(); ++j) {
356  HistogramWeight(wi_[i][j] * scales_[i], &histogram);
357  }
358  }
359  } else {
360  for (int i = 0; i < wf_.dim1(); ++i) {
361  for (int j = 0; j < wf_.dim2(); ++j) {
362  HistogramWeight(wf_[i][j], &histogram);
363  }
364  }
365  }
366  tprintf("%s\n", msg);
367  histogram.print();
368 }
Definition: statistc.h:33
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:37
int dim1() const
Definition: matrix.h:206
int dim2() const
Definition: matrix.h:207
const int kHistogramBuckets

◆ DeSerialize()

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

Definition at line 170 of file weightmatrix.cpp.

170  {
171  uint8_t mode;
172  if (!fp->DeSerialize(&mode)) return false;
173  int_mode_ = (mode & kInt8Flag) != 0;
174  use_adam_ = (mode & kAdamFlag) != 0;
175  if ((mode & kDoubleFlag) == 0) return DeSerializeOld(training, fp);
176  if (int_mode_) {
177  if (!wi_.DeSerialize(fp)) return false;
178  if (!scales_.DeSerialize(fp)) return false;
179  multiplier_.reset(IntSimdMatrix::GetFastestMultiplier());
180  if (multiplier_ != nullptr) multiplier_->Init(wi_);
181  } else {
182  if (!wf_.DeSerialize(fp)) return false;
183  if (training) {
184  InitBackward();
185  if (!updates_.DeSerialize(fp)) return false;
186  if (use_adam_ && !dw_sq_sum_.DeSerialize(fp)) return false;
187  }
188  }
189  return true;
190 }
const int kDoubleFlag
const int kInt8Flag
static IntSimdMatrix * GetFastestMultiplier()
bool DeSerialize(bool swap, FILE *fp)
bool DeSerialize(bool swap, FILE *fp)
Definition: matrix.h:161
const int kAdamFlag
bool DeSerializeOld(bool training, TFile *fp)

◆ DeSerializeOld()

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

Definition at line 194 of file weightmatrix.cpp.

194  {
195  GENERIC_2D_ARRAY<float> float_array;
196  if (int_mode_) {
197  if (!wi_.DeSerialize(fp)) return false;
198  GenericVector<float> old_scales;
199  if (!old_scales.DeSerialize(fp)) return false;
200  scales_.resize_no_init(old_scales.size());
201  for (int i = 0; i < old_scales.size(); ++i) scales_[i] = old_scales[i];
202  } else {
203  if (!float_array.DeSerialize(fp)) return false;
204  FloatToDouble(float_array, &wf_);
205  }
206  if (training) {
207  InitBackward();
208  if (!float_array.DeSerialize(fp)) return false;
209  FloatToDouble(float_array, &updates_);
210  // Errs was only used in int training, which is now dead.
211  if (!float_array.DeSerialize(fp)) return false;
212  }
213  return true;
214 }
void resize_no_init(int size)
Definition: genericvector.h:65
int size() const
Definition: genericvector.h:71
bool DeSerialize(bool swap, FILE *fp)
bool DeSerialize(bool swap, FILE *fp)
Definition: matrix.h:161
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 372 of file weightmatrix.cpp.

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

◆ FloatToDouble()

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

Definition at line 392 of file weightmatrix.cpp.

393  {
394  int dim1 = wf.dim1();
395  int dim2 = wf.dim2();
396  wd->ResizeNoInit(dim1, dim2);
397  for (int i = 0; i < dim1; ++i) {
398  const float* wfi = wf[i];
399  double* wdi = (*wd)[i];
400  for (int j = 0; j < dim2; ++j) wdi[j] = static_cast<double>(wfi[j]);
401  }
402 }
void ResizeNoInit(int size1, int size2, int pad=0)
Definition: matrix.h:91
int dim1() const
Definition: matrix.h:206
int dim2() const
Definition: matrix.h:207

◆ GetDW()

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

Definition at line 106 of file weightmatrix.h.

106 { return dw_(i, j); }

◆ GetWeights()

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

Definition at line 104 of file weightmatrix.h.

104 { return wf_[index]; }

◆ InitBackward()

void tesseract::WeightMatrix::InitBackward ( )

Definition at line 132 of file weightmatrix.cpp.

132  {
133  int no = int_mode_ ? wi_.dim1() : wf_.dim1();
134  int ni = int_mode_ ? wi_.dim2() : wf_.dim2();
135  dw_.Resize(no, ni, 0.0);
136  updates_.Resize(no, ni, 0.0);
137  wf_t_.Transpose(wf_);
138  if (use_adam_) dw_sq_sum_.Resize(no, ni, 0.0);
139 }
void Transpose(const GENERIC_2D_ARRAY< double > &input)
int dim1() const
Definition: matrix.h:206
int dim2() const
Definition: matrix.h:207
void Resize(int size1, int size2, const T &empty)
Definition: matrix.h:105

◆ InitWeightsFloat()

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

Definition at line 56 of file weightmatrix.cpp.

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

◆ is_int_mode()

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

Definition at line 99 of file weightmatrix.h.

99  {
100  return int_mode_;
101  }

◆ MatrixDotVector() [1/2]

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

Definition at line 221 of file weightmatrix.cpp.

221  {
222  ASSERT_HOST(!int_mode_);
223  MatrixDotVectorInternal(wf_, true, false, u, v);
224 }
#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 226 of file weightmatrix.cpp.

226  {
227  ASSERT_HOST(int_mode_);
228  ASSERT_HOST(multiplier_ != nullptr);
229  multiplier_->MatrixDotVector(wi_, scales_, u, v);
230 }
#define ASSERT_HOST(x)
Definition: errcode.h:84

◆ MultiplyAccumulate()

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

Definition at line 234 of file weightmatrix.cpp.

234  {
235  ASSERT_HOST(!int_mode_);
236  ASSERT_HOST(wf_.dim1() == 1);
237  int n = wf_.dim2();
238  const double* u = wf_[0];
239  for (int i = 0; i < n; ++i) {
240  inout[i] += u[i] * v[i];
241  }
242 }
int dim1() const
Definition: matrix.h:206
int dim2() const
Definition: matrix.h:207
#define ASSERT_HOST(x)
Definition: errcode.h:84

◆ NumOutputs()

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

Definition at line 102 of file weightmatrix.h.

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

◆ RemapOutputs()

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

Definition at line 77 of file weightmatrix.cpp.

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

◆ RoundInputs()

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

Definition at line 93 of file weightmatrix.h.

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

◆ Serialize()

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

Definition at line 151 of file weightmatrix.cpp.

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

◆ SumOuterTransposed()

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

Definition at line 258 of file weightmatrix.cpp.

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

◆ Update()

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

Definition at line 288 of file weightmatrix.cpp.

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

◆ VectorDotMatrix()

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

Definition at line 248 of file weightmatrix.cpp.

248  {
249  ASSERT_HOST(!int_mode_);
250  MatrixDotVectorInternal(wf_t_, false, true, u, v);
251 }
#define ASSERT_HOST(x)
Definition: errcode.h:84

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