Skip to content

measured · · 11 min

What memory costs in an OCR service

An OCR service went from 828 MiB to 541 MiB in Python and to 127–153 MiB in Rust, with every answer unchanged. Two allocator settings worth half a gigabyte, two shortcuts that saved memory and broke the readings, four trade-offs I measured and rejected, the floor that is left, and the CI gate that keeps it there.

Part 5 of the series Porting an OCR service to Rust without changing an answer.

The OCR service's answers were fixed before I touched its memory: every line of text, every box and every score had to stay equal, byte for byte. So every MiB I took out had to come out without moving a pixel. That rules out most of the easy wins, and it makes the question sharper: what does memory actually cost here, and what does it buy?

The short version: the contract check's peak went from 828 MiB to 541 MiB in Python, then to 127–153 MiB in Rust on arm64. Two glibc settings did more than anything clever. Two shortcuts that would have saved real memory changed what the service read, and were rejected. In Rust, three changes saved memory for too much time and bigger tiles saved none; all four were rejected. One, smaller tiles, was kept.

The check every number comes from

Memory numbers are only comparable if they come from the same test. Every peak in this post is from check/check.sh, run 1: the service, hardened (read-only, no capabilities, non-root, 1 GiB, 2 CPUs), reads full-size pages one at a time, then four at once. The number is the container's cgroup memory peak.

terminal
peak=$(( $("$DOCKER" exec "$NAME" /opt/ocrblaze/ocrblaze --memory-peak) / 1048576 ))
if [ "$peak" -gt "$max" ]; then
  echo "FAIL memory peak (cgroup) $peak MiB, over $max"; exit 1
fi

Two things to know about that number. It counts the page cache too: on a cold start, 30–45 MiB of library and model files are cached and charged to the container, so the same build moves by that much between runs. And it is not the process's own peak. For that the binary has --bench, which prints the process peak per page. Where I quote both, I say which.

The Python measurements and the arm64 Rust ones are from a 2-CPU arm64 Linux VM on a Mac. The CI ones are from amd64 runners. I do not compare across the two without saying so.

Python: two settings worth half a gigabyte

The first Python version peaked at 828 MiB on the check, and over 1 GB under a burst. Idle, after a burst, it sat at 590–752 MiB. Two causes, two settings.

ONNX Runtime's memory pattern. With it on, ONNX Runtime plans its tensors on the first run for a given input size and keeps that plan. The second page of the same size peaked about 140 MiB higher than the first. The check now reads a full-size page twice on purpose, to catch that. Turned off, the second page costs what the first does. The CPU arena is off too: turning it on cost another 80–140 MiB.

glibc's arenas. The server ran each request on its own thread, and glibc gave each thread its own heap. A detector run frees hundreds of MiB of tensors, and glibc kept them in that thread's heap instead of returning them. Three environment variables fixed it, and the Rust image still sets them:

terminal
# glibc malloc: two arenas, blocks of 4 MB or more mapped on their own (back to the
# kernel when freed), the heap trimmed above 32 MB.
ENV MALLOC_ARENA_MAX=2 MALLOC_MMAP_THRESHOLD_=4194304 MALLOC_TRIM_THRESHOLD_=33554432
Python serviceBeforeAfter
One page, first of its size602 MiB500–530 MiB
Later pages of the same size716–810 MiB500–530 MiB
4 pages and 4 crops at once1,047–1,215 MiB528–560 MiB
Idle after the bursts590–752 MiB128–181 MiB
Contract check, cgroup peak828 MiB541 MiB

Peak under load went from about 1.1 GB to about 0.55 GB. Not one answer changed: these settings decide where freed memory goes, not what the models compute.

Where the other 541 MiB sat

After that fix the peak split roughly in two. The process with both models loaded was about 125 MiB. The detector's tensors at full resolution were about 330–380 MiB.

That second part is the detector's shape. Its largest feature maps are at a quarter of the page's scale, and on a 2000 px page it holds four of them, 64 MiB each, at once. The recogniser is small next to it. So the detector was where the memory was, and every shortcut I tried went after it.

Shortcuts that broke the answers

figure 1 · what the shortcuts cost
  • 960 px cap · passport MRZ fields read right71%

    100% at full resolution · the line marks the full resolution

  • 960 px cap · PAN-card fields read right50%

    even a 1280 px cap still split text

  • INT8 detector · lines identical to the full model8 of 10

    and boxes moved by up to 6 px · the line marks the full model

Both shortcuts saved real memory, and both changed what the service read. A passport's machine-readable zone at 71% is a form a person has to correct; a box that moves by 6 px is a different crop. Toggle between the two sides of the trade.

A 960 px cap on the detector's input. The very first version of the service shipped with it, and I removed it 26 minutes later. It made 2000 px pages 35–45% faster and brought the peak to 300–380 MiB. It also dropped passport machine-readable-zone fields from 100% read right to 71%, and PAN-card fields to 50%. Small text lost letters: a name lost its final letter, a Devanagari name its final vowel sign, and passport dates split. A 1280 px cap still split text. For a service whose job is reading identity documents, that is not a trade.

An INT8 detector (static quantisation, QDQ). 560 MiB down to 407. Boxes moved by up to 6 px, and 2 of 10 lines read differently. A box that moves is a different crop, and a different crop is a different reading downstream.

The detector in overlapping strips. This one looked safe: the detector is mostly convolutions, and convolutions are local. But four of its layers are squeeze-excitation blocks, which take a mean of each channel over the whole page. A strip's mean is not the page's mean, and 2–3% of text pixels flipped. Running strips only for the local front of the model would have saved an estimated 60 MiB, while the neck, the middle of the model, still needed about 256 MiB at full size. Part 2 is how the Rust version does tile the detector, without flipping a pixel.

Rust: start from the same settings

The first Rust cut used the same models on the same ONNX Runtime 1.31.1, with the settings that had worked in Python carried over: memory pattern off, CPU arena off, the same three glibc variables.

terminal
Session::builder(env)?
    .with_optimization_level(GraphOptimizationLevel::All)?
    .with_memory_pattern(false)?
    .with_execution_providers([ort::ep::CPU::default().with_arena_allocator(false).build()])?
    .commit_from_file(path)

That version peaked at 198–226 MiB on the arm64 check, and 223 MiB on its first amd64 CI run: under half of Python. A memory pass on the morning of 5 December then took the process peak from 160–212 to 87–116 MiB; the unique dimension names and the recogniser's column groups below were part of it. This is what keeps the peak down today.

One thread pool. Twelve model sessions (the eleven detector pieces and the recogniser) share one global ONNX Runtime thread pool, instead of one pool each.

The detector in 11 pieces. Cut by tensor name, run in tiles of 384 px, with each whole-page mean summed in exactly the order ONNX Runtime does it. Instead of four 64 MiB maps at once, it keeps one 17 MB map at quarter scale, one 4 MB map at an eighth, and a 6 MB band. On arm64 the output is bit for bit the whole model's.

Unique dimension names. The pieces first shared their NCHW dimension names, which told ONNX Runtime that a map at an eighth of the page and a map at a quarter had one size, and it reused buffers across them. Each tensor in each piece now has its own names.

The recogniser in column groups. The recogniser reads lines in batches of six, padded to the widest line in the batch. Six ordinary lines are cheap; six lines padded to one very wide line are not. The batch still sets the padding, because the padding is part of the answer, but it now runs in groups of at most 2,400 columns, about 20 MiB of tensors:

terminal
// RapidOCR's batch sets the padding (bw); the model never mixes lines, so the batch
// runs in groups of at most REC_COLS columns: six ordinary lines at once (speed),
// wide ones fewer at a time (memory grows with columns)
let per = (REC_COLS / bw).clamp(1, REC_BATCH);

Give memory back. After loading, the binary tells the kernel it will not read the model files again (posix_fadvise(DONTNEED)), so their pages can leave the page cache the container is charged for. After each request it calls malloc_trim(0).

Rust serviceBefore the passAfter
Process peak, 2000 px pages (--bench)160–212 MiB87–116 MiB
Contract check, arm64198–226 MiB127–153 MiB (README) / 135–164 MiB (runbook)
Memory after the check63 MiB

The two arm64 ranges after the pass come from two sources that measured the same day and do not quite agree. I give both. Either way it is about a quarter of Python's 541.

Trade-offs I measured and rejected

Memory is never free, so I timed every one of these.

figure 2 · memory against page time
-40-200+20+401×1.25×1.5×1.75×2×page time against beforeMiB of peak savedtiles of 384, not 512 · keptown allocator · noone line per run · nommap at 128 KiB · noto -178 MiBbigger tiles · no

tiles of 384, not 512 · kept

Detector tiles of 384 px instead of 512: about 14 MiB lower peak for about 5% more time per page. Kept: the default on arm64.

Not plotted: turning the thread pool's spinning off was slower, and I kept no memory number for it.

Every memory trade-off I measured in the Rust service. Up is MiB of peak saved, right is how much slower a page got. Only the point near the top-left corner was worth it. Select a point (Tab, then Enter) to read what it was.
TriedMemoryTimeKept?
Tiles of 384 px instead of 512about 14 MiB lessabout 5% moreyes
Own ONNX Runtime allocator, every block of 256 KiB or more mapped on its own28 MiB lessabout 35% slowerno
glibc mmap threshold at 128 KiB7 MiB lesspage time doubledno
One recogniser line per run20 MiB less1.7× slowerno
Bigger detector tiles, 768–2048 px184–365 MiB against 187no fasterno
Thread pool spinning offnot recordedslowerno

The pattern: memory saved by allocating differently cost time on every page, while memory saved by holding less at once (smaller tiles) cost about 5%. I did not profile why the allocator changes were so slow; the likely cause is many more map and unmap calls for the short-lived tensors every page makes.

The floor

What is left on arm64 is mostly things that have to exist: the ONNX Runtime library, the model weights (11 detector pieces, 4.8 MB together on disk, and a 7.9 MB recogniser), the page itself, and the detector maps the model needs at once. The process peak is 87–116 MiB on a 2000 px page. The check's cgroup peak adds the page cache on top, which is why I never saw it under 100 MiB.

x86_64 is another story. There the tiles are not bit-exact, because ONNX Runtime sums the page means in its blocked layout, so ocrblaze runs the whole detector by default, about 250 MiB more on a 2000 px page. On GitHub's amd64 runner that check peaks at 420 MiB: 78% of the Python number, not a quarter. Part 2 has why.

Holding the line in CI

A memory number you measure once is a memory number you lose. The check runs in CI on every change, and a gate fails the build if the peak goes over it:

  • Python era: 700 MiB, against peaks of 565–599 MiB on the platform's amd64 CI runner.
  • Rust, the platform's image: 300 MiB, against 113–162 MiB.
  • ocrblaze's own image: 300 MiB on arm64, 500 MiB on x86_64, where 420 was measured with the whole detector.
figure 3 · contract-check peak on every CI run
0200400600MiBgate 700gate 30056559957859822323911316211-08 → 12-01python12-04 → 12-05rust
python, 4 runs
565 · 599 · 578 · 598
rust, first cut
223 · 239
rust, tiles of 384, 14 runs
146 · 131 · 124 · 137 · 141 · 129 · 133 · 113 · 113 · 130 · 137 · 159 · 126 · 162
The same check on the same amd64 CI runner, run by run. Python sat at 565–599 MiB under a 700 MiB gate. The first Rust runs were 223 and 239 MiB; after the memory pass, 113–162 MiB under a 300 MiB gate. This image pins 384 px tiles; ocrblaze's own x86 image runs the whole detector and is gated at 500 MiB instead.

The first two Rust runs, 223 and 239 MiB, are the version before the memory pass. The fourteen after it sit between 113 and 162 MiB, a spread of 49 MiB on one unchanged check. The page cache alone can account for 30–45 MiB of it on a cold start; with those files already cached, the check has peaked at 116 MiB.

That noise is one reason the gate keeps its headroom. A gate inside the noise fails at random, and a gate that fails at random gets turned off.

The gate is also not the only thing that fails the check, and in the Rust era it went red twice for reasons that had nothing to do with memory: model files that only root could read, and a cancelled run that left its port taken. Both fixed the same day.

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

  • Measure memory before the first line of code. The Python fix was two environment variables and half a gigabyte. They would have been there from day one if I had run a burst test before shipping instead of after.
  • Put the second page in the test. The memory-pattern cost only shows on the second page of the same size. One page per test would never have found it.
  • Production memory is not measured yet. Production still runs the Python image; every Rust number here is from a VM or a CI runner. The first production peak is the number I am waiting for.
  • The gate could be tighter with a warm cache. Dropping the page cache before the check, or reading the process peak instead of the cgroup one, would remove most of the 30–45 MiB of noise and let the gate sit closer to the real peak. I have not done it.
  • Image size is not measured. One binary and a few libraries should be much smaller than 20 Python wheels, but I have no number for either image, so I am not giving one.

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