Skip to content

shipped · · 10 min

Reproducing Python to the last bit: round, np.round, a pairwise mean and a JPEG decoder

An OCR service ported from Python to Rust has to give the same scores, the same boxes and the same bytes on the wire. That means Python's round and numpy's round (they differ), numpy's pairwise mean, float32 then float64 in one line of normalisation, argmax's first tie, Pillow's exact libjpeg build, and json.dumps's float format. Each rule, the Rust that reproduces it, and the 138,648 cases that check it.

This is part 4 of the ocrblaze series. ocrblaze reads receipts and identity documents, and it replaces a Python service built on RapidOCR 3.10. The rule for the port was "equal bytes, not a tolerance": every line, box and score the same as the Python reference, and every answer on the wire the same bytes.

The models run on the same ONNX Runtime in both, so the models were never the hard part. The hard part was everything Python does around them: small number rules that nobody wrote down because, in Python, they are just what the language does. This post goes through them in the order a page meets them.

Rounding, three ways

RapidOCR rounds in three places. Box corners are rounded to 0.1 px with round(x, 1). Each character's confidence is rounded with round(v, 5). A line's score is the mean of those, put through np.round(mean, 5) and then round(score, 4).

round and np.round look like the same function. They are not.

  • Python's round(x, n) rounds the exact binary value of x, correctly, with ties to even. 2.675 is stored as 2.67499999999999982236431605997495353221893310546875, so round(2.675, 2) is 2.67.
  • numpy's np.round(x, n) computes rint(x * 10**n) / 10**n. The multiplication rounds first: 2.675 * 100 is exactly 267.5 in float64, rint sends that tie to even, and the answer is 2.68.

So the same number, rounded to the same places, gives 2.67 in Python and 2.68 in numpy. The port needs both, each in the place the reference used it:

terminal
/// Python's round(x, nd): correctly rounded on the exact binary value, ties to even.
pub fn round(x: f64, nd: usize) -> f64 {
    // Rust's fixed-precision formatting is exact and ties to even, like CPython's dtoa mode 3.
    format!("{x:.nd$}").parse().unwrap()
}

/// numpy's ndarray.round(nd) for float64: rint(x * 10**nd) / 10**nd.
pub fn np_round(x: f64, nd: i32) -> f64 {
    let f = 10f64.powi(nd);
    (x * f).round_ties_even() / f
}

The Python version is one line because Rust's format! with a precision already does what CPython does: it formats the exact value and breaks ties to even. Parsing the string back gives the nearest double, which is what CPython returns.

The figure below runs all three roundings, plus JavaScript's toFixed for comparison, on any number you type. It works on the exact binary value with BigInt arithmetic, and every preset was checked against CPython and numpy 2.3.5 before it went in.

figure 1 · three roundings of one number

Any decimal or 1e-7 style number.

stored as

2.67499999999999982236431605997495353221893310546875

numpy's first step, x × 102 in float64 = 267.5

  • Pythonround(x, 2)2.67
  • numpynp.round(x, 2)2.68differs from Python
  • JavaScriptNumber(x.toFixed(2))2.67same as Python
Type a number and a number of places, or pick a preset. The first line is the number the computer actually stores. Python rounds that exact value; numpy multiplies by a power of ten first, which can round once already; toFixed rounds the exact value but sends ties up. The service has to give Python's answer where the reference used round and numpy's where it used np.round.

The last preset is the score path. 0.3002479 rounded once to four places is 0.3002. Rounded to five places by numpy first, it becomes 0.30025, and then Python's round gives 0.3003. RapidOCR rounds twice, so the port rounds twice, in the same order, with the same two functions.

The py part of the parity suite checks these against the reference image: 96,486 round cases and 32,162 np.round cases, drawn to hit the hard spots (float32 confidences, exact binary ties, and box coordinates that sit on a tie).

The mean is not a loop

The score is a mean, and a mean is a sum. numpy does not add an array left to right. np.add.reduce, which np.mean uses, sums with pairwise summation: up to 8 values it loops; up to 128 it keeps eight accumulators and adds them as a fixed tree; above that it splits the array in two (at a multiple of 8) and recurses.

terminal
} else if n <= 128 {
    let mut r = [0f64; 8];
    r.copy_from_slice(&a[..8]);
    let mut i = 8;
    while i < n - n % 8 {
        for j in 0..8 {
            r[j] += a[i + j];
        }
        i += 8;
    }
    let mut res = ((r[0] + r[1]) + (r[2] + r[3])) + ((r[4] + r[5]) + (r[6] + r[7]));
    for v in &a[i..] {
        res += v;
    }
    res
}

The order matters because every addition rounds. For sixteen confidences, accumulator r[j] is a[j] + a[j + 8], not two neighbours, and then the eight are added as a tree. A port that adds left to right often gets a different last bit, and whether that changes the four-place score depends on where the mean falls.

figure 2 · the same sixteen numbers, added in two orders

values a[0] … a[15] · float64 · set 1

  1. a[0]0.73895
  2. a[1]0.30192
  3. a[2]0.66921
  4. a[3]0.98674
  5. a[4]0.97786
  6. a[5]0.49677
  7. a[6]0.72899
  8. a[7]0.80452
  9. a[8]0.59806
  10. a[9]0.99638
  11. a[10]0.61869
  12. a[11]0.64215
  13. a[12]0.39725
  14. a[13]0.58262
  15. a[14]0.47327
  16. a[15]0.40815

left to right · one running total

  1. + a[1]1.04087
  2. + a[2]1.71008
  3. + a[3]2.6968199999999998
  4. + a[4]3.6746799999999995
  5. + a[5]4.171449999999999
  6. + a[6]4.90044
  7. + a[7]5.70496
  8. + a[8]6.30302
  9. + a[9]7.2994
  10. + a[10]7.91809
  11. + a[11]8.56024
  12. + a[12]8.95749
  13. + a[13]9.54011
  14. + a[14]10.01338
  15. + a[15]10.42153

numpy pairwise · a tree

  1. r[j] = a[j] + a[j + 8]1.337011.29831.28791.628891.37510999999999981.079391.202261.2126700000000001
  2. level 2: add neighbours2.635312.91678999999999982.45452.41493
  3. level 3: add neighbours5.5520999999999994.8694299999999995
  4. level 4: add neighbours10.421529999999999
ordersummean (÷ 16)
left to right10.421530.651345625
numpy pairwise10.4215299999999990.6513456249999999

The totals differ in the last digits (marked). A port that adds left to right gets numpy's mean wrong here.

Play it: in each step both methods do the same number of additions (8, 4, 2, 1). Left to right carries one running total; numpy adds a[j] to a[j + 8] in eight accumulators, then adds them as a tree. The values are the same; the rounding after each addition is not. float64 is what RapidOCR's mean runs in; float32 shows the same effect in a shorter type.

The parity suite has 4,000 mean cases, many of them at lengths on the algorithm's edges. All identical.

float32, then float64, in one line

RapidOCR normalises the page for the detector with this line:

terminal
(img.astype(np.float32) * (1 / 255.0) - mean) / std

It reads like one calculation. In numpy it is two types. img.astype(np.float32) times a Python float stays float32: numpy 2 keeps the array's type when a Python scalar meets it. Then mean and std are float64 arrays, so the subtraction and division happen in float64. The result is cast to float32 for the model. The port does exactly that:

terminal
fn det_input(v: u8, c: usize) -> f32 {
    const MEAN: [f64; 3] = [0.485, 0.456, 0.406];
    const STD: [f64; 3] = [0.229, 0.224, 0.225];
    (((v as f32 * (1.0 / 255.0) as f32) as f64 - MEAN[c]) / STD[c]) as f32
}

Doing it all in float32, or all in float64, moves the last bit of some inputs, and the detector's threshold does the rest. The recogniser's normalisation, by contrast, is float32 all the way (v / 255 - 0.5, then / 0.5), because there every operand is float32 or a Python scalar.

The first of equal maxima

The recogniser gives, for each column of a text line, a probability per character. CTC decoding takes the most likely character per column with argmax, drops the blank and repeats, and joins the rest. When two characters tie for the maximum, numpy's argmax returns the first. A max_by in Rust returns the last. The port folds by hand with a strict comparison, so the first one wins:

terminal
let (k, v) = row.iter().enumerate().fold((0, row[0]), |m, (k, &v)| if v > m.1 { (k, v) } else { m });

The character list follows RapidOCR's: index 0 is the blank, then the model's keys file, then a space at the end.

Python's whitespace

RapidOCR drops a line whose text is only whitespace, by Python's str.strip(). Python's idea of whitespace is not Rust's char::is_whitespace: it includes the four ASCII separator controls \x1c to \x1f, for example, and it is checked over every code point in Unicode by the py part. Small, and the kind of thing that turns one line out of thousands into a missing line.

Decoding a JPEG like Pillow does

Before any of this, the page has to be decoded, and decoders differ. Two builds of libjpeg-turbo can produce pixels that differ in the last bit, and the detector reads pixels. The Python service decoded with Pillow 13.0.0, which ships its own libjpeg-turbo and libwebp inside its wheel.

So ocrblaze uses those exact libraries. The image takes Pillow's wheel from PyPI by SHA-256, copies out its libjpeg-turbo, libwebp, libwebpdemux and libsharpyuv, and the service dlopens them through a 168-line C shim. Everything Pillow does in Python or in its own C around those calls is ported: marker and chunk parsing, the checks that decide between "bad image" and "wrong type", PNG inflate (with miniz_oxide) and unfiltering, EXIF orientation, and convert("RGB").

The decode part checks 274 files: each gives identical pixels, or the same refusal with the same status. The JPEG the service writes for /rotate (OpenCV's encoder at quality 92) comes out as the same bytes.

The same bytes on the wire

The old service was Python's http.server writing json.dumps output, and clients already parsed exactly that. The Rust server writes the same status lines, headers and JSON byte for byte. That meant reproducing json.dumps exactly:

  • Separators ", " and ": ", Python's defaults.
  • Strings: Devanagari stays raw UTF-8 in answers (ensure_ascii=False), and is escaped as \uXXXX in log lines, where the service logs ASCII only.
  • Floats as float.__repr__ writes them: the shortest digits that read back as the same double, with an exponent only when there would be four or more zeros between the decimal point and the first digit, or more than 16 digits before the point. 0.0001 stays 0.0001; 0.00001 becomes 1e-05.

The same writer caught a bug in the benchmark flag. --bench printed each line's text with Rust's {:?}, which escapes a Devanagari vowel sign as \u{947}. That is not JSON. It now uses the server's json.dumps writer.

The server part runs the HTTP contract against the server on a mock engine; the reference's 25 lines on the specimen page come out the same. Part 2 of that contract, the byte-for-byte comparison against the old Python service itself, is skipped in the public suite because that service is not public. It was run against it during the port.

One trap in the test harness

The parity data is JSON written by Python and read by the Rust tests. Early on, tests failed by one unit in the last place, and the code was right. serde_json's default float parser is fast and not always exact, so the expected value was off by one ULP. The fix is one feature flag, on the test-only dependency:

terminal
serde_json = { version = "1", features = ["float_roundtrip"] } # parity data only; exact float parsing

When the rule is "equal bits", the harness's own parsing has to be exact too, or it reports differences that are not there.

The count

PartWhat is comparedCasesResult
pyround, np.round, np.mean, np.argsort, str.isspace138,648, plus every code pointidentical
cvimgOpenCV resize, perspective transform and warp, the crop29,420exact
cvgeomcontours, minAreaRect, fillPoly, Shapely area and length34,000exact
Clipperpyclipper's box offsets8,000exact
decodePillow decode, EXIF, RGB; OpenCV JPEG and PNG encode274 filesidentical
e2eevery /ocr, /line, /crop, /rotate answer on 40 pages216identical

Those ran on both of GitHub's runners, x86 and arm64 (run 47484109192). The py part's 138,648 is 96,486 round, 32,162 np.round, 4,000 means and 6,000 argsorts. The argsorts have their own story, because on x86 numpy hands the sort to a SIMD library with its own order of ties. That is in part 3.

What I'd do differently, and what's still open

  • Write the number rules down first. I found most of these by a parity test failing, then reading numpy or CPython to see why. A list of "every place the reference rounds, sums, sorts or formats" made at the start would have been an afternoon and saved several.
  • The reference is pinned, and the proof is only for that pin. numpy 2.3.5, Pillow 13.0.0, OpenCV 4.10, ONNX Runtime 1.31.1. A newer numpy could change a rounding path; the parity suite would show it, but only when someone runs it.
  • ONNX Runtime 1.31.0 is not proven. The crate's default build links 1.31.0; parity was proven on 1.31.1, which the image loads. They are expected to give the same answers.
  • Not faster. None of this made the service faster. The time is in the two models, which run on the same ONNX Runtime as before; the page time is the same as Python's.
  • Not in production yet. The service runs on staging. Production switches after the next promotion.

Working through something like this? I help teams ship AI and cloud systems that hold up, and cost what they should.