Skip to content

shipped · · 14 min

Porting an OCR service to Rust without changing an answer

A receipt and ID-document OCR service peaked at 541 MiB in Python on a small shared host. I ported it to Rust with one rule: every answer equal, byte for byte. It peaks at 127–153 MiB on arm64, reads at the same speed, and gives 216 of 216 identical answers on two CPU architectures. What it took, what it didn't fix, and what is still open.

An HR and attendance platform reads receipts, bills and identity documents with a small OCR service. In Python it peaked at 541 MiB on its own contract check, on a small host it shares with other containers. Every shortcut that would have cut that number also changed what the service read.

So I ported it to Rust, and made one rule first: the Rust service must give the same answers as the Python one, with equal bytes, not a tolerance. Every line of text, every box corner, every score. The result is ocrblaze (Apache-2.0, on crates.io). It peaks at 127–153 MiB on arm64, about a quarter of the Python service, reads a page in the same time, and gives 216 of 216 identical answers on both arm64 and x86_64. Production has not been switched yet. That, and the other honest parts, are below.

This post is the overview. The series after it goes deep on each part:

  1. Porting an OCR service to Rust without changing an answer (this post)
  2. Cutting a detector into eleven pieces
  3. One CPU, one answer
  4. Reproducing Python to the last bit
  5. What memory costs in an OCR service

What the service does

The platform has a scan feature. A person photographs a receipt or a bill, and the platform pulls out the seller, the totals, the VAT and the bill number. HR uploads an identity document, and it reads the passport's machine-readable zone, a PAN card, or a citizenship card, and makes field crops for review with the identifier boxes blacked out. It also reads scanned CVs.

All of that goes through one internal HTTP service with four calls:

RouteAnswer
POST /ocrevery text line on the page: text, four box corners, score
POST /linethe recogniser alone on one box
POST /cropPNG crops of boxes, with areas blacked out on request
POST /rotatethe page turned, as a JPEG

The platform's own parsers sit behind it. They read fields out of the text and use the boxes to find what sits next to what. That matters for everything that follows: the parsers were tuned against this service's exact output.

The models are PaddleOCR's PP-OCRv5 mobile detector and recogniser (Devanagari by default), run through RapidOCR 3.10 on ONNX Runtime. I picked that in October after a short bake-off. A port into the Rails app matched PaddleOCR on 17 of 20 lines; on a tilted, blurred bill the 3 it lost included the PAN and the bill number, because axis-aligned boxes merge tilted lines. PaddleOCR's own Python package read all 20 but took 4.1–5.8 s and about 880 MB, and had no linux-aarch64 wheel after 3.2.2. RapidOCR read all of them in 0.7 s.

The problem: memory on a small shared host

The Python service was 661 lines of server.py on top of a real stack: Python 3.12, RapidOCR 3.10, ONNX Runtime 1.31.1, OpenCV 4.10, numpy 2.3.5, Pillow 13.0.0, shapely and pyclipper. Twenty pinned wheels, about 99 MiB compressed for aarch64.

It runs as a container beside the platform's background jobs on a small shared host, capped at 1 GB with no swap and first in line for the out-of-memory killer, so a spike in OCR can never take the jobs down with it. The production host is a Neoverse N1 (Graviton2) arm64 machine.

The first version peaked at 828 MiB on its contract check. A fix in November, two settings I cover in part 5, brought the peak under load from about 1.1 GB to about 0.55 GB, and the check to 541 MiB. It then ran 11 days on staging with no restart and no out-of-memory kill. Good enough to run, but 541 MiB is a lot of a small host, and the rest of it would not move:

  • the process with both models loaded was about 125 MiB;
  • the detector's tensors at full resolution were about 330–380 MiB. On a 2000 px page the detector holds four 64 MiB feature maps at once.

The obvious ways down changed the answers. Capping the detector's input at 960 px dropped passport machine-readable-zone fields from 100% to 71% read right. An INT8 detector saved 153 MiB and moved boxes by up to 6 px; 2 of 10 lines changed. Running the detector in strips changed 2–3% of text pixels, because the model averages over the whole page. Each of those is a parser bug waiting to happen.

The decision: measure first, then equal bytes

On 4 December I decided to try a Rust port, on one condition: measure first. Port the service, run the same contract check, and keep it only if the numbers say so.

The second rule was the one that shaped the work. The Rust service must give the same bytes as the Python one. Not "close", not "within a tolerance". The reasons were practical:

  • The parsers do not change. If the text, boxes and scores are equal, every parser and every parser test stays valid. Through both services, the platform's parsers read 8 pages (receipts, a passport, PAN cards) into identical fields, with crops pixel-identical, and its parser and crop tests finished 65 runs with 0 failures.
  • A tolerance hides real bugs. A box off by one pixel is either a rounding difference or a broken port. With equal bytes you never have to decide which.
  • It is a sharper test. Exact comparison found per-CPU behaviour in numpy, OpenBLAS and OpenCV that a tolerance would have smoothed over. Parts 3 and 4 are about those.

Two things were not reasons. ONNX Runtime's GitHub repository went private on 17 November. That broke downloads elsewhere in the platform, but nothing in this service ever downloaded from it: Python took ONNX Runtime from PyPI, and the Rust image takes the same libonnxruntime.so.1.31.1 from the hash-pinned PyPI wheel. The motive was memory.

And I did not try to leave ONNX Runtime. A pure-Rust inference engine I was writing separately runs these two models 12–14× slower single-threaded, on an M1. ocrblaze stays on ONNX Runtime through the ort crate, with the same session settings the Python service used.

What ocrblaze is

A library crate, a small HTTP server, and a distroless Docker image for linux/amd64 and linux/arm64. No Python, OpenCV, numpy or Pillow at run time.

terminal
use ocrblaze::{Config, Image, Ocr};

let mut ocr = Ocr::new(Config::new("models"))?;
let page = Image::new(width, height, rgb_bytes).expect("width * height * 3 bytes");
for line in ocr.read(&page)? {
    println!("{} {:.4} {:?}", line.text, line.score, line.bbox);
}

Underneath it reproduces RapidOCR's pipeline step for step. Outside the two models, every step Python did with a library is now Rust code that does what that library does, down to its rounding:

ModuleLinesReproduces
src/cvgeom/clipper.rs2,185Clipper 6.4.2, as pyclipper 1.4 runs it
src/server.rs1,385the old service's HTTP answers, byte for byte
src/decode.rs1,056Pillow's decode, EXIF turn and RGB conversion
src/cvgeom/mod.rs763the detector's post-processing: contours, minAreaRect, Shapely area
src/cvimg.rs532OpenCV 4.10 resize, perspective warp, RapidOCR's crop
src/xss.rs450numpy's x86-simd-sort argsort, lane by lane
src/tiled.rs295the detector in 11 pieces
src/py.rs236Python's round, numpy's round, pairwise mean, argsort

7,628 lines of Rust in all, plus a 168-line C shim. The direct dependencies are ort, miniz_oxide and libc. To decode images exactly as Pillow does, the server loads the very libjpeg-turbo and libwebp builds that Pillow 13.0.0's wheel ships, because different builds of those libraries differ in the last bit.

Where the memory went

figure 1 · memory peak on the same check
  1. 1. Python, first version828 MiB
  2. 2. Python, after the memory fix541 MiB
  3. 3. Rust, first cut198–226 MiB
  4. 4. Rust, after the memory pass127–153 MiB
  5. x86_64, whole detector (different machine)420 MiB

On x86_64, ocrblaze 0.2.0 runs the whole detector, because tiles are not bit-exact there: 420 MiB on GitHub's amd64 runner, 78% of Python's 541, not a quarter.

Each bar is the cgroup memory peak of the same contract check: full-size pages alone, then four at once. The four steps were measured in a 2-CPU arm64 Linux VM. The dashed bar is x86_64 on a GitHub runner, where the detector runs whole: the 'quarter' holds on arm64 only.

Same models, same ONNX Runtime, same check. The first Rust version came in at 198–226 MiB on arm64, before the memory pass. That was already under half.

Most of what came after was the detector. Its four squeeze-excitation layers each take a mean over the whole page, which is why naive strips change answers. I cut the model into 11 pieces by tensor name, run the local parts in tiles of 384 px, and compute each whole-page mean by summing in exactly the order ONNX Runtime's MLAS kernels do. On arm64 the detector's map comes out bit for bit equal to the whole model's. That is part 2.

The rest was smaller things, each measured: the recogniser runs in groups of at most 2,400 columns, model files are dropped from the page cache after load, freed memory is handed back after each request, and some ideas that saved memory were rejected because they cost too much time. That is part 5.

Two caveats belong next to the headline number. First, "a quarter" is arm64 only. On x86_64 the tiles are not bit-exact (ONNX Runtime sums page means in a different layout there), so ocrblaze runs the whole detector by default, and that peaks at 420 MiB on GitHub's amd64 runner: 78% of the Python number, not 25%. Second, the check's cgroup peak counts 30–45 MiB of library and model files cached on a cold start, so it moves between runs. The sources also disagree a little on the arm64 range: the README says 127–153 MiB, the platform's runbook, measured the same day, says 135–164.

Proving it: equal bytes

parity/run.sh runs the Python reference in its own container (RapidOCR 3.10, ONNX Runtime 1.31.1, Pillow 13.0.0, OpenCV 4.10, numpy 2.3.5, all hash-pinned, no network), records what each step returns, and compares the Rust code with it exactly.

terminal
docker build --target models --output type=local,dest=parity/data-linux/models .
parity/run.sh            # or: parity/run.sh e2e decode
figure 2 · the parity suite
  • py

    138,648cases

    Python round, numpy round / mean / argsort, plus isspace over all of Unicode

    ✓ identical

  • cvimg

    29,420cases

    OpenCV resize, perspective transform and warp, RapidOCR's crop

    ✓ exact

  • cvgeom

    34,000cases

    contours, minAreaRect, fillPoly, Shapely area, box scores

    ✓ exact

  • clipper

    8,000offsets

    Clipper 6.4.2 offsets, as pyclipper 1.4 runs them

    ✓ exact

  • detector maps

    2,504synthetic

    plus 51 real maps with 2,119 boxes

    ✓ exact

  • decode

    274files

    same pixels as Pillow, or the same refusal; JPEG same bytes

    ✓ identical

  • end to end

    216/ 216 answers

    40 generated pages, every /ocr, /line, /crop, /rotate, on arm64 and on x86_64

    ✓ identical

  • cpu kernels

    22settings

    60,000 norms and 3,000 argsorts in each forced kernel

    ✓ exact

  • recognisers

    1,421/ 1,421 answers

    11 other official PP-OCRv5 mobile recognisers

    ✓ identical

mismatches allowed: 0 · runners: GitHub arm64 (Neoverse N2) and amd64

Every part of the suite compares the Rust code with the Python reference for equal bytes. Play counts them up; at rest the wall shows the final counts. The cell that matters is the one that is not there: mismatches allowed, zero.

The whole suite takes about an hour and several GB, so it runs by hand before each release, on GitHub's arm64 (Neoverse N2) and amd64 runners. The 0.2.0 run passed every part on both, and the recognisers run gave 1,421 of 1,421 identical answers with the 11 other official PP-OCRv5 mobile recognisers.

It did not pass the first time. The first runs on GitHub's machines failed on an argsort of 27 values, crop sizes off by one in 30 cases on x86 and 19 on arm, three warps, and Clipper offsets (7,851 of 8,000 matched); with tiles on x86, 213 of 216 answers matched end to end. All but the last were CPU-specific choices inside numpy, OpenBLAS or the OpenCV and pyclipper wheels, which the Python service had been making silently all along. The last was ONNX Runtime's own layout on x86, which is why x86 runs the whole detector. Part 3 is about finding and reproducing them, and part 4 about the plain-Python rules (rounding, pairwise sums, ties) that had to be copied before any of that.

Same speed, on purpose

The Rust service is not faster. Page time is the same as Python's within noise.

figure 3 · where one page's second goes
detector
~340 ms · ONNX Runtime
recogniser
~600 ms · ONNX Runtime
everything else
~45 ms · decode, post-processing, crops, JSON: the code I wrote

On 2000 px pages the part outside the models grows to 60–100 ms. Two threads run the models 1.66× faster than one, and that is the lever for speed: more or faster CPUs, not another language.

A 900×1300 receipt takes about a second. The two models take about 940 ms of it, inside ONNX Runtime, in Python and in Rust alike. Rewriting the other ~45 ms in Rust could not make the page meaningfully faster, so it didn't.

That is what the numbers allow. Of about a second for a 900×1300 receipt, the two models take about 940 ms, and both run in the same ONNX Runtime with the same settings in either language. Two threads already run them 1.66× faster than one. Faster pages with the same readings need faster or more CPUs, not a rewrite.

I got this wrong once. On 4 December I compared a Rust timing with a Python timing from a different run and wrote down a speed-up. It was wrong, and I took it back the next morning: measured fairly, the page time is the same within noise. Start-up is the one place Rust is clearly quick: 150–265 ms from launch to ready, models loaded and warmed.

From decision to staging in under a day

When (UTC)What
4 Dec, 20:48First Rust version up for review; its first CI check peaks at 223 MiB
5 Dec, 02:51Memory pass: process peak 160–212 → 87–116 MiB
5 Dec, 04:08ocrblaze public, Apache-2.0
5 Dec, 04:210.1.0 on crates.io
5 Dec, 04:30GitHub release with 14 model files and SHA256SUMS
5 Dec, 04:32–05:20Parity on GitHub's runners finds the per-CPU differences
5 Dec, 05:29Parity passes every part on both runners
5 Dec, 05:460.2.0: exact on every CPU the reference runs on
5 Dec, 06:29The platform switches to ocrblaze on staging
5 Dec, 06:33Staging OCR container restarted on the new image: healthy

The public repository has 15 commits, all on 5 December; it starts from one squashed commit, because the spike and the memory pass happened in the platform's private repository first.

The platform's image now has no Python in it. It runs cargo install ocrblaze at a pinned version from crates.io, fetches the model files from the v0.1.0 release by SHA-256, and takes ONNX Runtime and Pillow's image libraries from PyPI wheels by SHA-256. The change to the platform was +362 and −1,504 lines.

CI was not green on every run, and the red ones were real:

  • ocrblaze's own CI went red several times on rustfmt, once on a link error (unit tests could not link ONNX Runtime statically), and once because the image deleted the whole detector, so the new x86 default could not start.
  • The platform's OCR check went red twice in the Rust era: the model files were saved readable only by root, so the service user could not load them; and a cancelled run left its port taken, which failed the next one.

All of them were fixed the same day. Each was something a green local build would not have shown.

The numbers

Python (RapidOCR 3.10)ocrblaze
Contract-check peak, arm64541 MiB127–153 MiB
Contract-check peak, x86_64565–599 MiB (CI)420 MiB, whole detector
Memory after the check128–181 MiB63 MiB
Page time, 900×1300 receiptthe same, within noiseabout 1 s
Start-up to readynot measured150–265 ms
Answers equal to Python, 40 pagesn/a216 / 216 on each architecture
Service code661 lines + RapidOCR, OpenCV, numpy…7,628 lines of Rust + 168 of C
Runtime packages20 wheels, ~99 MiB compressedone binary, ONNX Runtime, 4 image libraries

The two x86 numbers are from different runners: the Python one from the platform's CI, the ocrblaze one from GitHub's.

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

  • Production is not switched. Staging runs ocrblaze; production still has the Python image. The plan is to switch it with the next promotion. On staging the old image is kept, so going back is one setting and a restart.
  • No real scan on staging yet. The container is healthy and the check passes, but I have not yet watched a real document go through it on staging.
  • The real production CPU has not run parity. OpenBLAS picks its kernel per CPU, and crop sizes depend on it. The cpu part forces the reference into the Neoverse N1 kernel on GitHub's arm runner and matches, but one parity/run.sh e2e on the production host itself is still to do.
  • x86 is not a quarter. It is 420 of 541. And the platform's image pins 384 px tiles on every architecture, which on x86 is not bit-exact (3 of 216 answers differed). Production is arm64, where tiles are exact, so it does not bite today; it would if the service moved to x86.
  • Parity is proven on ONNX Runtime 1.31.1 only. The crate's default download-binaries feature links 1.31.0, which should give the same answers but is not proven.
  • Not measured: the image size of either service, and the Python service's start-up time. I have no number, so I am not giving one.
  • Production memory after the switch will be the number that counts, and I don't have it yet.

If I did it again, I would set up the parity suite on both CPU architectures before writing the first line of Rust, not after the first release. Everything in part 3 was waiting in the reference from the start, and an hour of CI on day one would have found it before 0.1.0 went out instead of after.

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