Skip to content

shipped · · 11 min

Cutting a text detector into eleven pieces without changing a pixel

The whole-page text detector held four 64 MiB feature maps at once. Running it in strips changed 2–3% of the text pixels, because four squeeze-excitation layers average the whole page. How ocrblaze cuts PP-OCRv5's detector into eleven ONNX pieces by tensor name, sums each page mean in the exact lane order ONNX Runtime uses on arm64, and gets a probability map that is bit for bit the whole model's. And why x86 still runs the whole model.

This is part 2 of the ocrblaze series. The OCR service reads receipts and identity documents for an HR and attendance platform. Its text detector looks at the whole page at once, and on a 2000 px page that whole-page view is most of the memory: the model holds four 64 MiB feature maps at quarter scale at the same time. The obvious fix, cutting the page into strips, changes the answers.

This post is how ocrblaze runs the same detector in eleven pieces, on tiles and bands, and still produces the whole model's probability map bit for bit on arm64. On x86 it does not, and the post ends with why.

Where the memory was

The service reproduces RapidOCR 3.10 with PaddleOCR's PP-OCRv5 mobile models. The detector takes the page at full size: RapidOCR's setting only scales a page up if its short side is under 64 px, and the service caps the long side at 2000 px. On the Python service, measured on its contract check (full-size pages, alone and four at once), the peak was 541 MiB. Of a single page's peak, the process and both models were about 125 MiB; the detector's tensors at full resolution were about 330–380 MiB.

The detector is a DB-style network: a backbone that shrinks the page to 1/4, 1/8, 1/16 and 1/32 scale, a neck that brings those back together at 1/4, and a head that turns them into a probability per pixel. At 1/4 scale a 2000 px page is a 500 px-wide map, and several of those maps have 96 channels. The comment at the top of src/tiled.rs is the whole problem in one line: the whole model peaked at four 64 MiB tensors at 1/4 scale at once.

Why strips change the answer

Most of the network only looks at nearby pixels. A convolution needs a few pixels of border around a tile, and with that border the tile's output equals the whole page's output for that area. If that were all, tiling would be easy.

It is not all. PP-OCRv5 mobile has four squeeze-excitation (SE) layers. Each takes the average of a channel over the whole page, runs it through a tiny network, and multiplies the whole channel by the result. That average is global. A strip has its own average, so a strip scales every channel by a slightly different number than the whole page would.

I tried strips first, on the Python service, before any Rust existed. The detector step used about 35% less memory, and 2–3% of the text pixels flipped: pixels that were text became background, or the reverse. Readings changed. A second try ran only the local front of the network in strips and the rest whole; that saved an estimated 60 MiB, because the neck still needed about 256 MiB at full size. Neither was kept.

The rule for the port was "equal bytes, not a tolerance", so 2–3% was not a number to tune. It meant the split had to keep every page mean exact.

Cutting the graph by tensor name

The detector is an ONNX graph. ONNX's Extractor can cut a subgraph out of a model given the names of the tensors that go in and the tensors that come out. So the split is a table of names:

terminal
PIECES = {
    "s1": (["x"], ["c2", "a8"]),
    "s2": (["a8"], ["c3", "out4", "p5", "p4"]),
    "t3": (["c3"], ["conv_3"]),
    "se3": (["pool_3"], ["hs_3"]),
    # ... 7 more
    "tc": (["conv_b", "hs_b", "p5", "p4", "x3", "hs_x3"], ["prob"]),
}

build/split_det.py runs at image build time. It checks that each piece pulls in nothing from the page beyond its declared inputs, writes it, and compares its SHA-256 with a pinned value, so a change in the onnx package cannot quietly produce different pieces.

The cut points follow the SE layers. Everything between two SE layers is local, so it can run on tiles or bands. Each SE layer gets two pieces of its own: one that computes the channel it averages (run band by band, so the mean can be summed as it goes), and one that turns the mean into the scale.

figure 1 · the detector in eleven pieces
page tiles
1/8 scale
1/4 scale
piece
det_s1.onnx · 105,653 bytes
in → out
page tile (3 channels) → c2 (12 ch @ 1/4), a8 (96 ch @ 1/8)
how it runs
tiles of 384 px with a 32 px halo
why
Only local operations, so a tile with enough border around it gives exactly the whole page's values.
onepage mean

0 px differ, at tiles of 384, 512 and 256

Bands of full rows, each channel's mean summed in exactly the lane order MLAS uses on arm64. On the 896 × 1312 specimen page the map is bit for bit the whole model's, and 216 / 216 end-to-end answers match.

Pick a piece to see what goes in, what comes out and how it runs. Then switch how the page is split: only bands of full rows, with the page means summed in the CPU's own order, give the whole model's map, and only on arm64.

The pieces fall into three groups:

GroupPiecesHow they run
Page tiless1384 px tiles with a 32 px halo; outputs at 1/4 (12 channels) and 1/8 (96 channels)
1/8 scales2, t3, se3, u3, sex3s2 once on the whole page; t3 and u3 in bands of 32 rows; x3 (24 channels, 4 MB) kept whole
1/4 scaleta, sea, tb, sebw, tcta in bands (conv A, 96 channels, never stored); tb and tc in 64 px tiles with a halo of 8; conv B (24 channels, 17 MB) kept whole

Two of the four SE layers pool maps small enough to keep: x3 at 1/8 scale and conv B at 1/4 scale with 24 channels. For those the service keeps the map and lets ONNX Runtime's own pooling take the mean (sex3, sebw), which is exact by definition. The other two average big maps (conv A has 96 channels at 1/4 scale), and those maps never exist whole. Their means have to be summed by hand.

The eleven files together are 4,787,627 bytes, against 4,766,440 for the whole model. Most of the weights sit in s2.

Summing a mean the way ONNX Runtime does

"The mean of a channel" sounds like one number. In float32 it is one number per order of addition. To match the whole model bit for bit, the bands have to add the values in exactly the order ONNX Runtime's CPU kernel library, MLAS, adds them inside GlobalAveragePool.

MLAS reads the channel as one flat array, row after row. It keeps four float32 lanes and adds value i into lane i mod 4. When the lanes are full it adds them together, then adds the last n mod 4 values one at a time, then divides by n. The step that differs by CPU is how the four lanes are combined: (l0 + l1) + (l2 + l3) on arm64 NEON, (l0 + l2) + (l1 + l3) elsewhere.

terminal
fn get(&self) -> f32 {
    let l = self.lanes;
    let mut r =
        if cfg!(target_arch = "aarch64") { (l[0] + l[1]) + (l[2] + l[3]) } else { (l[0] + l[2]) + (l[1] + l[3]) };
    for &x in &self.tail {
        r += x;
    }
    r / self.n as f32
}

The bands are what make this possible. A band of 32 full rows is a contiguous run of the flattened channel, so if the bands are fed in order and the lane index is a running count across bands, every value lands in the same lane it would in the whole-page run. Tiles would break that: a tile is a set of short row pieces, and the order would be wrong. That is why the SE inputs run in bands and the rest runs in tiles.

The figure below runs the same arithmetic on a made-up plane of float32 values, in both lane orders. It is computed in your browser, not drawn.

figure 2 · one page mean, two lane orders

plane 3 · 25 × 41 = 1,025 values · value 1,025 of 1,025

  1. lane 0 · values 0, 4, 8 …

    594.0964

  2. lane 1 · values 1, 5, 9 …

    490.509

  3. lane 2 · values 2, 6, 10 …

    450.82288

  4. lane 3 · values 3, 7, 11 …

    516.7526

Tail: 1 value (-0.88359094) added after the lanes are combined.

arm64 (NEON)

(l0 + l1) + (l2 + l3) + tail

sum 2051.2974

mean 2.0012658

x86_64

(l0 + l2) + (l1 + l3) + tail

sum 2051.297

mean 2.0012655

Plane 3: the two means differ in the last digits (marked). A squeeze-excitation layer multiplies a whole channel by a scale computed from this mean.

Play it: 1,025 float32 values go round-robin into four lanes, exactly as MLAS reads a flattened plane. Then the lanes are added in arm64's order and in x86's order. Same values, same lanes, different last digits. 'Another plane' draws new values: often the two agree, sometimes they do not, and the tiled detector has to match the CPU it runs on every time.

A difference in the seventh digit of a mean looks harmless. It is not, here: the mean becomes a scale, the scale multiplies a whole channel, and the detector's output goes through a threshold. A pixel near the threshold moves to the other side. Then a box changes size, the crop changes, and the recogniser reads a different crop.

The bug that was not about numbers

At one point the pieces failed in a way that had nothing to do with rounding. ONNX Runtime plans its memory from the shapes declared in the graph, and the extracted pieces shared symbolic dimension names. A map at 1/8 scale and a map at 1/4 scale had the same names for height and width. That told ONNX Runtime they were the same size, so it reused buffers between them, and the run failed.

The fix is in the split: every input and output of every piece gets its own names.

terminal
for k, v in enumerate(list(sub.graph.input) + list(sub.graph.output)):
    t = v.type.tensor_type
    t.elem_type = onnx.TensorProto.FLOAT
    t.shape.ClearField("dim")
    for d in "NCHW":
        t.shape.dim.add().dim_param = f"{d}{k}"

Choosing the tile size

The first tile is the page-scale tile for s1, with 32 px of halo on each side so the convolutions near the edge see the same pixels they would on the whole page. Its size is a memory and time trade:

TileResult
384 px (default)about 14 MiB under 512, about 5% more time
512 pxpeak 187 MiB in the measurement that compared tiles
768–2048 pxpeak 184–365 MiB, and no faster

Bigger tiles were tried because fewer runs might be faster. They were not: the time is in the model's convolutions either way. 384 stays the default, and OCRBLAZE_DET_TILE changes it. The later pieces at 1/4 scale run on 64 px tiles with a halo of 8, small enough that their tensors stay a quarter of what 512 px tiles would need.

The result on arm64

The tiled part of the parity suite runs the specimen page (896 × 1312) through the pieces and through the whole model, and compares the probability maps bit for bit. On GitHub's arm64 runner (a Neoverse N2) it does that at three tile sizes:

Tile / tail tileIdentical bitsPixels that differ
384 / 64yes0
512 / 128yes0
256 / 32yes0

That is from run 47483257519 and again in the release run 47484109192, where the end-to-end part also gives 216 of 216 answers identical to the Python reference.

Why x86 keeps the whole model

The same run on GitHub's x86 runner said no. With tiles, the map differed from the whole model's in 134,166 pixels, by at most 0.000486, at every tile size. The end-to-end part then gave 213 of 216 identical answers: 3 different (run 47482004454).

On x86, ONNX Runtime does not run these layers in plain NCHW. It converts the maps to its blocked NCHWc layout, where channels are grouped into blocks for the vector unit, and pools them in that layout. The page means come out of a different order of additions, and the bands cannot reproduce that order from outside.

I could have tried to replay the blocked layout too. I did not, for two reasons. The production host is a Neoverse N1 (Graviton2) arm64 machine, where the pieces are exact. And the whole model on x86 costs memory, not correctness. So 0.2.0 made the whole model the default on x86_64 (OCRBLAZE_DET_TILE=0) and kept 384 px tiles on arm64. The image ships the whole detector next to the pieces.

What that costs is visible in the contract check. On arm64, in a 2-CPU Linux VM, the whole service peaks at 127–153 MiB. On GitHub's x86 runner with the whole detector it peaked at 420 MiB. Those are different machines, so read the gap as rough; the README puts the whole detector at about 250 MiB more at a 2000 px page. The Python service peaked at 541 MiB on the same check.

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

  • I would run the tiled part on both CPUs before the first release. 0.1.0 said the pieces were exact, and they were, on the arm64 machine I tested on. The first parity run on an x86 runner found otherwise within the hour. Part 3 is that hour.
  • The split is tied to one model. It is cut by tensor names from PP-OCRv5 mobile. Another detector needs a new table of names and its own parity run.
  • x86 is exact only with the whole model. If memory on x86 ever matters, the next step is reproducing ONNX Runtime's NCHWc pooling order, and proving it the same way.
  • The service that uses ocrblaze sets tiles of 384 everywhere. Production is arm64, where that is exact; an x86 test machine running the same setting is not.
  • Not yet in production. The service runs ocrblaze on staging; production is the next step. And one check is still open: the full parity run on a real Graviton2 host, not just GitHub's runner forced into its kernels.

The memory side of this, what else was tried and what it cost, is part 5. The number side, every other place where the port had to match Python to the last bit, is part 4.

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