Commit 4076ec73 for tesseract
commit 4076ec73d25231be52e00c5f9a78fde2942dcb32
Author: Stefan Weil <sw@weilnetz.de>
Date: Thu Nov 26 14:24:34 2026 +0100
Don't clip the pixels of the image for int models
The pixels of a line image are scaled with estimates for black and white
(lower quartile of the local minima and upper quartile of the local
maxima of the middle row), so that many pixels of the text are darker
than "black" and get values below -1. A network is trained with these
values, but an int model clipped them to the range of an int8 input
(NetworkIO::SetPixel). That caused most of the loss of accuracy of an
int model compared to the float model which it was made from.
An int model now reads the image as float, too, if its first layer with
weights is a fully connected layer (as in networks which start with
a convolution, for example [1,36,0,1 Ct3,3,16 ...]). That layer uses a
float copy of its int weights for the float input and writes an int8
output for the rest of the network as before. Other int models and all
float models are not changed.
Character error rates of a model for historic prints ([1,48,0,1 Ct3,3,16
Mp3,3 Lfys64 Lbx128 Lbx256 O1c571], 644 characters) on three test sets
with 25042, 15667 and 30891 lines:
float model 0.528 % 0.247 % 1.674 %
int model, old code 0.762 % 0.458 % 2.519 %
int model, new code 0.570 % 0.290 % 1.733 %
The models of tessdata_fast gain less on 10178 of these lines:
script/Fraktur 4.72 % -> 4.51 %, deu_latf 5.29 % -> 5.19 %,
script/Latin 9.54 % -> 9.43 %.
The time for the recognition of 400 lines with the int model increased
from 15.9 s to 16.1 s (float model: 35.0 s).
Assisted-by: Claude Fable 5.2 (Anthropic)
Signed-off-by: Stefan Weil <sw@weilnetz.de>
diff --git a/src/lstm/fullyconnected.cpp b/src/lstm/fullyconnected.cpp
index d999f575..b201b25e 100644
--- a/src/lstm/fullyconnected.cpp
+++ b/src/lstm/fullyconnected.cpp
@@ -141,6 +141,12 @@ void FullyConnected::Forward(bool debug, const NetworkIO &input,
int width = input.Width();
if (type_ == NT_SOFTMAX) {
output->ResizeFloat(input, no_);
+ } else if (weights_.is_int_mode() && !input.int_mode()) {
+ // The first layer of an int model gets a float input (see
+ // LSTMRecognizer::RecognizeLine) and switches to int for the rest of
+ // the network.
+ output->ResizeToMap(true, input.stride_map(), no_);
+ weights_.InitFloatFromInt();
} else {
output->Resize(input, no_);
}
@@ -200,7 +206,9 @@ void FullyConnected::SetupForward(const NetworkIO &input, const TransposedArray
// Softmax output is always float, so save the input type.
int_mode_ = input.int_mode();
if (IsTraining()) {
- acts_.Resize(input, no_);
+ // The activations are a copy of the output, which is int for int
+ // weights, also if the input is float (see Forward).
+ acts_.ResizeToMap(input.int_mode() || weights_.is_int_mode(), input.stride_map(), no_);
// Source_ is a transposed copy of input. It isn't needed if provided.
external_source_ = input_transpose;
if (external_source_ == nullptr) {
diff --git a/src/lstm/lstmrecognizer.cpp b/src/lstm/lstmrecognizer.cpp
index 172036ae..defbbe76 100644
--- a/src/lstm/lstmrecognizer.cpp
+++ b/src/lstm/lstmrecognizer.cpp
@@ -31,6 +31,7 @@
#include "lstm.h"
#include "normalis.h"
#include "pageres.h"
+#include "plumbing.h"
#include "ratngs.h"
#include "recodebeam.h"
#include "scrollview.h"
@@ -321,6 +322,49 @@ void LSTMRecognizer::RecognizeLine(const ImageData &image_data,
}
}
+// Helper looks for the first layer with weights below the given network.
+// Returns 1 if it is a fully connected layer, 0 if it is something else
+// and -1 if there is no layer with weights.
+static int FirstWeightsAreFullyConnected(const Network *network) {
+ switch (network->type()) {
+ case NT_INPUT:
+ case NT_CONVOLVE:
+ case NT_MAXPOOL:
+ case NT_RECONFIG:
+ // These layers only copy or rearrange their input.
+ return -1;
+ case NT_SERIES:
+ for (const Network *layer : static_cast<const Plumbing *>(network)->stack()) {
+ int result = FirstWeightsAreFullyConnected(layer);
+ if (result >= 0) {
+ return result;
+ }
+ }
+ return -1;
+ case NT_LOGISTIC:
+ case NT_POSCLIP:
+ case NT_SYMCLIP:
+ case NT_TANH:
+ case NT_RELU:
+ case NT_LINEAR:
+ case NT_SOFTMAX:
+ case NT_SOFTMAX_NO_CTC:
+ return 1;
+ default:
+ return 0;
+ }
+}
+
+// Returns true if the image has to be converted to int8 for the network.
+// The pixel values are scaled with estimates for black and white, so many
+// pixels are outside of the range [-1, 1], and the int8 conversion clips
+// them. A model is trained with the unclipped float values, therefore an
+// int model reads the image as float, too, if its first layer with weights
+// is a fully connected layer, which can use a float input with int weights.
+bool LSTMRecognizer::IntInput() const {
+ return IsIntMode() && FirstWeightsAreFullyConnected(network_) != 1;
+}
+
// Helper computes min and mean best results in the output.
void LSTMRecognizer::OutputStats(const NetworkIO &outputs, float *min_output, float *mean_output,
float *sd) {
@@ -372,7 +416,7 @@ bool LSTMRecognizer::RecognizeLine(const ImageData &image_data,
}
// Reduction factor from image to coords.
*scale_factor = min_width / *scale_factor;
- inputs->set_int_mode(IsIntMode());
+ inputs->set_int_mode(IntInput());
SetRandomSeed();
Input::PreparePixInput(network_->InputShape(), pix, &randomizer_, inputs);
network_->Forward(debug, *inputs, nullptr, &scratch_space_, outputs);
@@ -383,7 +427,7 @@ bool LSTMRecognizer::RecognizeLine(const ImageData &image_data,
if (pos_mean < invert_threshold) {
// Run again inverted and see if it is any better.
NetworkIO inv_inputs, inv_outputs;
- inv_inputs.set_int_mode(IsIntMode());
+ inv_inputs.set_int_mode(IntInput());
SetRandomSeed();
pixInvert(pix, pix);
Input::PreparePixInput(network_->InputShape(), pix, &randomizer_, &inv_inputs);
diff --git a/src/lstm/lstmrecognizer.h b/src/lstm/lstmrecognizer.h
index 15cdc81c..53136f6b 100644
--- a/src/lstm/lstmrecognizer.h
+++ b/src/lstm/lstmrecognizer.h
@@ -87,6 +87,8 @@ public:
bool IsIntMode() const {
return (training_flags_ & TF_INT_MODE) != 0;
}
+ // True if the image has to be converted to int8 for the network.
+ bool IntInput() const;
// True if recoder_ is active to re-encode text to a smaller space.
bool IsRecoding() const {
return (training_flags_ & TF_COMPRESS_UNICHARSET) != 0;
diff --git a/src/lstm/weightmatrix.cpp b/src/lstm/weightmatrix.cpp
index 74647215..b0a30943 100644
--- a/src/lstm/weightmatrix.cpp
+++ b/src/lstm/weightmatrix.cpp
@@ -155,6 +155,7 @@ TransposedArray::~TransposedArray() = default;
int WeightMatrix::InitWeightsFloat(int no, int ni, bool use_adam, float weight_range,
TRand *randomizer) {
int_mode_ = false;
+ float_from_int_ = false;
wf_.Resize(no, ni, 0.0);
if (randomizer != nullptr) {
for (int i = 0; i < no; ++i) {
@@ -206,6 +207,7 @@ int WeightMatrix::RemapOutputs(const std::vector<int> &code_map) {
// Store a multiplicative scale factor (as a TFloat) that will reproduce
// the original value, subject to rounding errors.
void WeightMatrix::ConvertToInt() {
+ float_from_int_ = false;
wi_.ResizeNoInit(wf_.dim1(), wf_.dim2());
scales_.reserve(wi_.dim1());
int dim2 = wi_.dim2();
@@ -303,6 +305,7 @@ bool WeightMatrix::Serialize(bool training, TFile *fp) const {
// Reads from the given file. Returns false in case of error.
bool WeightMatrix::DeSerialize(bool training, TFile *fp) {
+ float_from_int_ = false;
uint8_t mode;
if (!fp->DeSerialize(&mode)) {
return false;
@@ -472,10 +475,34 @@ bool WeightMatrix::DeSerializeOld([[maybe_unused]] bool training,
// implement the bias, but it doesn't actually have it.
// Asserts that the call matches what we have.
void WeightMatrix::MatrixDotVector(const TFloat *u, TFloat *v) const {
- assert(!int_mode_);
+ // In int mode this needs the float copy of the weights, see
+ // InitFloatFromInt.
+ assert(!int_mode_ || float_from_int_);
MatrixDotVectorInternal(wf_, true, false, u, v);
}
+// Makes a float copy of the int weights, so that MatrixDotVector can also be
+// used with a float input. The result is the same as for an int8 input of
+// INT8_MAX * u. Does nothing if the copy exists or if not in int mode.
+void WeightMatrix::InitFloatFromInt() {
+ if (!int_mode_ || float_from_int_) {
+ return;
+ }
+ float_from_int_ = true;
+ int dim1 = wi_.dim1();
+ int dim2 = wi_.dim2();
+ wf_.ResizeNoInit(dim1, dim2);
+ for (int i = 0; i < dim1; ++i) {
+ const int8_t *i_line = wi_[i];
+ TFloat *f_line = wf_[i];
+ // scales_ includes a factor 1 / INT8_MAX for the int8 input.
+ TFloat scale = scales_[i] * INT8_MAX;
+ for (int j = 0; j < dim2; ++j) {
+ f_line[j] = i_line[j] * scale;
+ }
+ }
+}
+
void WeightMatrix::MatrixDotVector(const int8_t *u, TFloat *v) const {
assert(int_mode_);
if (IntSimdMatrix::intSimdMatrix) {
diff --git a/src/lstm/weightmatrix.h b/src/lstm/weightmatrix.h
index 6c5ab236..bb9e1678 100644
--- a/src/lstm/weightmatrix.h
+++ b/src/lstm/weightmatrix.h
@@ -139,8 +139,12 @@ public:
// u is of size W.dim2() - 1 and the output v is of size W.dim1().
// u is imagined to have an extra element at the end with value 1, to
// implement the bias, but it doesn't actually have it.
- // Asserts that the call matches what we have.
+ // Asserts that the call matches what we have. The float version can also
+ // be used in int mode after a call of InitFloatFromInt.
void MatrixDotVector(const TFloat *u, TFloat *v) const;
+ // Makes a float copy of the int weights for MatrixDotVector with a float
+ // input.
+ void InitFloatFromInt();
void MatrixDotVector(const int8_t *u, TFloat *v) const;
// MatrixDotVector for peep weights, MultiplyAccumulate adds the
// component-wise products of *this[0] and v to inout.
@@ -175,6 +179,8 @@ private:
TransposedArray wf_t_;
// Which of wf_ and wi_ are we actually using.
bool int_mode_;
+ // True if wf_ is a float copy of wi_ (see InitFloatFromInt).
+ bool float_from_int_ = false;
// True if we are running adam in this weight matrix.
bool use_adam_;
// If we are using wi_, then scales_ is a factor to restore the row product
diff --git a/unittest/weightmatrix_product_test.cc b/unittest/weightmatrix_product_test.cc
index f0771497..24ad7740 100644
--- a/unittest/weightmatrix_product_test.cc
+++ b/unittest/weightmatrix_product_test.cc
@@ -5,6 +5,8 @@
// against a straightforward calculation with doubles.
// The sizes are chosen to cover all the blocks and the
// remainders of the SIMD implementations.
+// Also tests the product of an int-mode WeightMatrix with a
+// float input.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -16,6 +18,7 @@
#include "include_gunit.h"
#include "helpers.h" // for TRand
+#include "intsimdmatrix.h" // for IntSimdMatrix
#include "params.h" // for ParamUtils, GlobalParams
#include "simddetect.h" // for SIMDDetect
#include "weightmatrix.h" // for WeightMatrix, TransposedArray
@@ -175,6 +178,59 @@ protected:
}
}
+ // Tests the product of int weights with a float input, which is used for
+ // the first layer of an int model, for no outputs and ni inputs.
+ void TestFloatInputForIntWeights(int no, int ni) {
+ WeightMatrix matrix;
+ matrix.InitWeightsFloat(no, ni + 1, false, 1.0f, &randomizer_);
+ matrix.ConvertToInt();
+ matrix.InitFloatFromInt();
+ // The SIMD code for an int8 input reads and writes rounded sizes.
+ int rounded_ni = matrix.RoundInputs(ni + 1);
+ int rounded_no = no;
+ if (IntSimdMatrix::intSimdMatrix) {
+ rounded_no = IntSimdMatrix::intSimdMatrix->RoundOutputs(no);
+ }
+ std::vector<int8_t> int_u(rounded_ni, 0);
+ std::vector<TFloat> u(ni);
+ std::vector<TFloat> twice_u(ni);
+ std::vector<TFloat> zero_u(ni, 0);
+ for (int j = 0; j < ni; ++j) {
+ int_u[j] = static_cast<int8_t>(IntCastRounded(randomizer_.SignedRand(INT8_MAX)));
+ u[j] = static_cast<TFloat>(int_u[j]) / INT8_MAX;
+ twice_u[j] = 2 * u[j];
+ }
+ std::vector<TFloat> int_v(rounded_no);
+ std::vector<TFloat> v(no);
+ std::vector<TFloat> twice_v(no);
+ std::vector<TFloat> zero_v(no);
+ matrix.MatrixDotVector(int_u.data(), int_v.data());
+ matrix.MatrixDotVector(u.data(), v.data());
+ matrix.MatrixDotVector(twice_u.data(), twice_v.data());
+ matrix.MatrixDotVector(zero_u.data(), zero_v.data());
+ // The weights and the inputs are not larger than 1.
+ const double tolerance = kRelativeTolerance * (ni + 1) + kAbsoluteTolerance;
+ for (int i = 0; i < no; ++i) {
+ // The same input as int8 and as float gives the same result.
+ EXPECT_NEAR(int_v[i], v[i], tolerance)
+ << "float input for no=" << no << ", ni=" << ni << ", index=" << i;
+ // A float input is not clipped to the range of an int8 input:
+ // W (2 u) + b = 2 (W u + b) - b.
+ EXPECT_NEAR(2.0 * v[i] - zero_v[i], twice_v[i], 4 * tolerance)
+ << "large float input for no=" << no << ", ni=" << ni << ", index=" << i;
+ }
+ }
+
+ // Tests the product of int weights with a float input for many sizes.
+ void TestAllFloatInputForIntWeights() {
+ const int kSizes[] = {1, 2, 3, 4, 5, 8, 9, 16, 17, 33, 48};
+ for (int no : kSizes) {
+ for (int ni : kSizes) {
+ TestFloatInputForIntWeights(no, ni);
+ }
+ }
+ }
+
// Selects the functions for the dot products like the parameter dotproduct
// or the environment variable DOTPRODUCT do.
static void SelectDotProduct(const char *name) {
@@ -195,6 +251,10 @@ TEST_F(WeightMatrixProductTest, SumOuterTransposed) {
TestAllSumOuter();
}
+TEST_F(WeightMatrixProductTest, FloatInputForIntWeights) {
+ TestAllFloatInputForIntWeights();
+}
+
// The functions for FMA are also tested on a CPU for which other functions
// were selected (AVX512F). This changes the selection for the tests which
// follow.