LlamaIndex released OCRia-nano-1 for CPU document parsing. I wanted to start with a smaller question: if I give its detector and Latin recognizer a receipt, can C-Kernel-Engine (CKE) turn those same weights into C and read the same text as ONNX Runtime? I made two images with a known answer, ran both engines on a Ryzen workstation and a ThinkStation P3, and checked the steps between the image and the final text.

Run this with CKE

The whole architecture, before we zoom in

OCRia-nano-1 is a pipeline, not a single vision encoder connected to a language-model decoder. A PDF may already contain usable text. LiteParse keeps that text and its positions, and asks the OCR models to read what is missing. Then a separate model, LayoutNet, works out which pieces belong to the same table, row, column, cell or block. Those boundaries explain where the full parser does more than our CKE demo.

Clickable architecture from native PDF and image OCR branches through LayoutNet to document output.
Explore OCRia layer by layer. Open Detector, Script router, CTC recognizers, or LayoutNet; inspect the leaf tiles for tensor and stored weight shapes.
Full pipeline: native PDF text, selective OCR, merge, LayoutNet and document output.
Full pipeline: native PDF text, selective OCR, merge, LayoutNet and document output.

I counted operators in the published v1.0.0 ONNX files and inferred shapes for a 512 × 512 page and a 32 × 512 line. The counts below refer to individual exported convolution operators, not to a common transformer depth. The technical report describes the models, the training data and the full-page comparison.

Where the 8.1 million parameters go
StageArchitectureIn the CKE demo?
DetectorAbout 82K parameters; 40 Conv ops across an encoder, feature pyramid and heatmap headYes, generated C
Geometry bridge and routerHost crops and straightens lines; about 39K parameters in the router, with 15 Conv ops and two linear headsAxis-aligned crops in the demo host; no learned router
Four recognizersAbout 0.80M Latin, 0.97M World, 0.71M RTL, 1.27M CJK; 29 Conv ops in Latin, World and RTL, 30 in CJK in these exportsLatin only, generated C; host assembles text
LayoutNet4.27M parameters; four Conv ops in the image branch and a six-layer, width-256 transformer over text unitsNo

1. Detector: a CNN encoder and a feature-pyramid neck

Detector encoder, feature pyramid, stem skip, and half-resolution text-line heatmap.
Detector encoder, feature pyramid, stem skip, and half-resolution text-line heatmap.

The detector reduces RGB to one channel with a weighted sum. A 3 × 3 stem goes to half resolution. Ten depthwise-separable blocks follow, split 2 / 3 / 3 / 2 across strides 4, 8, 16 and 32. The first convolution in a block mixes nearby pixels within a channel; a 1 × 1 then mixes channels. Going down the pyramid, the widths are 24, 48, 96 and 128 channels. The coarser maps have room to capture more of a line.

The neck uses 1 × 1 lateral projections to make the levels 32 channels wide. It upsamples deeper features and adds them to finer ones. Four smoothing branches produce 16 channels each; resizing and concatenating them at stride 4 gives 64 channels. The fused map is squeezed to 12 channels, upsampled and added to a projection of the stride-2 stem. Another depthwise/pointwise pair and the last 1 × 1 produce one score per spatial position. Sigmoid turns that into a 256 × 256 heatmap for our 512-pixel-square example. It marks the centers of text lines, not characters.

2. The bridge and decoder: turn a line into a sequence

The first bridge is geometry, not attention. LiteParse thresholds the heatmap, grows the line cores into rotated quadrilaterals and straightens the crops. Its router has a stem and seven depthwise/pointwise blocks; mean and max pooling across the resulting sequence form a 192-wide vector. Two GEMMs score four script families and two orientations. LiteParse uses page votes and can override them for a line or rerun a recognizer when confidence is poor. In our CKE test, the Python host makes axis-aligned crops and sends all of them to Latin.

Latin encoder, height squeeze, three sequence mixers, and 792-logit CTC head.
Latin encoder, height squeeze, three sequence mixers, and 792-logit CTC head.

The Latin recognizer’s image encoder has a 3 × 3 stem plus nine depthwise/pointwise blocks. Five blocks have residual adds. Several reduce height without reducing width, because horizontal position is the order in which you read. A 32 × 512 grayscale crop becomes [1, 192, 1, 128]. Squeezing the height dimension is the second bridge: the recognizer now sees 128 sequence positions with 192 features each.

Three residual mixers then apply a depthwise Conv1D of width nine, followed by 1 × 1 projections that expand 192 to 384 and project back to 192. That is how the head sees nearby letters without self-attention or a KV cache. The final 1 × 1 gives 792 logits per position: 791 characters plus blank. The export returns the best class ID and its confidence at every position. The host collapses repeats, drops blanks and maps IDs to characters. This is greedy CTC decoding, not a language model generating one token at a time.

3. LayoutNet: read relationships, not pixels as characters

LayoutNet text and image inputs, six transformer layers, and structure prediction heads.
LayoutNet text and image inputs, six transformer layers, and structure prediction heads.

LayoutNet takes text units with boxes and features such as text shape and alignment, including eight LiteParse grid signals. In parallel, four strided convolutions turn a grayscale page into an image feature grid. The model samples that grid at unit boxes and uses two late cross-attention steps to read image patches. The six pre-norm transformer layers process the text units. Its outputs are node flags, pairwise links and scores for 13 layout classes. LiteParse then clusters the links into tables and blocks and writes the document. That last part can distinguish two columns even when every word is already correct. Our stocktake example shows why the simpler CKE host can’t make that claim.

Compared with the original Transformer, the recognizable pieces are scaled dot-product attention, a dense feed-forward network, and residuals. In this export, each text unit is 256 wide. All six layers use ordinary multi-head attention: four Q, four K, and four V heads, each 64 wide. The QKV matrix is [256, 768] in ONNX MatMul order; the ReLU feed-forward matrices are [256, 512] and [512, 256]. LayerNorm is applied before the two branches. L04 and L05 add four-head cross-attention with queries from text units and keys and values from image patches. This encoder scores relationships; it has no masked, autoregressive text decoder.

What LlamaIndex changed, and what CKE added

The ingredients have a history: the detector follows the DBNet family, the line-detection and recognition split follows patterns popularized by PP-OCR, and CTC predates both. The release doesn’t claim a new convolution or attention primitive. LlamaIndex’s contribution is how it sized and trained the pieces, then connected them: it combined teacher labels from OCRia-1 with PDF text, synthetic scripts and agreement checks, trained with scan distortions, and used LiteParse’s existing geometry as an input to a joint layout and table model. The small detector and Latin byte quantization are CPU trade-offs within that design.

From exported operators to checked CKE calls
Model operationWhat CKE added or reused
Detector convolutions, resize and fuseReused grouped FP32 convolution and add; mapped nearest 2×, concat and sigmoid. The later channel-contiguous path uses image_conv_hwc_f32, image_nearest2x_hwc_f32 and image_concat_hwc_f32.
Latin Q/DQ convolution and residualsThe byte circuit keeps activations in UINT8 using affine_spatial_u8_i8_u8, affine_pointwise_u8_i8_u8 and affine_add_u8. VNNI is a CPU-specific dot-product implementation, not a change to OCRia’s layers.
Best class and confidencectc_top1_confidence_f32 finds the winning class and its confidence. CTC string assembly stays in the host.
LayoutNet and script routingNot part of this generated bundle or its latency and correctness comparison.

The implementation trail links the first generated detector, byte-activation work and detector layout work. Those are changes in how CKE executes the pinned weights, separate from LlamaIndex training the model.

What the V8 circuit actually stitches together

The detector and line recognizer use operations you’ll also find in many vision encoders: spatial convolution, depthwise convolution, 1 × 1 channel mixing, activation functions, and residual adds. That gave us kernels and compiler machinery to reuse. The work was to describe this model’s particular connections and layouts, pack the weights, and preserve the numerical behavior of its quantized edges and character head.

V8 build and runtime graph, with detailed detector, Latin CNN, residual edges, and CTC readout.
Explore the generated V8 circuit. Open the Latin entry and inspect B6 to follow both inputs to the add.

For the optimized 512-pixel build, the importers produce two bounded_graph circuits. Each schedules its own block once per invocation: once for the detector image and once per recognizer crop. circuit.json names the operations, intermediate tensors and weight references. layout.json assigns aligned locations in the arena. call.json resolves those names and the kernel map into the C function and ordered arguments. generated.c calls those functions at the assigned offsets and checks their return status. The host links the two passes by cropping between them; they aren’t one fused graph.

Here’s one actual residual. B3 feeds a depthwise operation, B4, then a pointwise operation, B5. B6 reads both B5 and B3, so it matters that the circuit names the earlier buffer instead of assuming every op reads only the immediately preceding output. In this build the add processes 131,072 byte elements, or 2,048 positions × 64 channels. The two inputs have different scales and zero points; the ratios in the circuit convert them into the same output quantization.

circuit.json · B6 template operationJSON
{
  "id": "b6",
  "op": "affine_add_u8_checked",
  "kernel": "affine_add_u8",
  "graph_slots": {
    "inputs": {
      "left": "b5",
      "right": "b3"
    },
    "outputs": {
      "output": "b6"
    }
  },
  "params": {
    "N": 131072,
    "left_ratio": 1.9726697206497192,
    "right_ratio": 0.2368163913488388,
    "call_constants": {
      "n": 131072,
      "left_zero": 126,
      "right_zero": 0,
      "output_zero": 0
    }
  }
}
See the resolved ABI and emitted Ccall.json · B6 resolved callJSON
{
  "template_op_id": "b6",
  "function": "affine_add_u8",
  "call_abi": {
    "version": 1,
    "owner": "kernel_map",
    "kernel_id": "affine_add_u8",
    "source_file": "affine_add_u8.json"
  },
  "args": [
    {
      "name": "left",
      "source": "activation:left",
      "expr": "(const uint8_t*)(model->bump + A_B5)",
      "buffer_ref": "b5"
    },
    {
      "name": "right",
      "source": "activation:right",
      "expr": "(const uint8_t*)(model->bump + A_B3)",
      "buffer_ref": "b3"
    },
    {
      "name": "output",
      "source": "output:output",
      "expr": "(uint8_t*)(model->bump + A_B6)",
      "buffer_ref": "b6"
    },
    {
      "name": "n",
      "source": "runtime:n",
      "expr": "131072"
    },
    {
      "name": "left_ratio",
      "source": "param:left_ratio",
      "expr": "1.9726697206497192"
    },
    {
      "name": "right_ratio",
      "source": "param:right_ratio",
      "expr": "0.2368163913488388"
    },
    {
      "name": "left_zero",
      "source": "runtime:left_zero",
      "expr": "126"
    },
    {
      "name": "right_zero",
      "source": "runtime:right_zero",
      "expr": "0"
    },
    {
      "name": "output_zero",
      "source": "runtime:output_zero",
      "expr": "0"
    }
  ]
}
generated.c · emitted B6 callC
    status = affine_add_u8((const uint8_t*)(model->bump + A_B5), (const uint8_t*)(model->bump + A_B3), (uint8_t*)(model->bump + A_B6), 131072, 1.9726697206497192, 0.2368163913488388, 126, 0, 0);
    if (status != 0) return status;

The detector build resolves 71 calls, including 40 calls to the channel-contiguous FP32 convolution provider. The weighted RGB reduction even reuses audio_conv2d_whc_grouped_f32: its name comes from another use, but the operation is a grouped convolution. The Latin byte build resolves 43 calls, including 29 spatial or pointwise convolutions, 11 byte residual adds, and the input quantization, score dequantization, and CTC top-1 calls. That’s why the port is mostly about getting the graph right, with targeted kernel work where the existing calls don’t fit. See the Latin importer and checked compiler for the actual machinery.

How it learns to spell without a language model

Take a crop labeled BOOK. During training the label is the whole string. Nobody needs to mark which pixel column contains each letter. The CNN reduces the crop to a strip of feature vectors in reading order. In the 32 × 512 Latin example it has 128 positions, each with 192 features. A learned 1 × 1 projection scores all 792 classes at each position. It doesn’t take the previous printed character as an input. Nearby features still help: each position can see a neighborhood through the CNN and the three width mixers.

Three possible alignments over six positions
Path (underscore = blank)After CTC collapse
B B O _ O KBOOK
_ B O _ O KBOOK
B O O _ K KBOK

During CTC training, softmax gives a distribution over characters and blank at each position. A path’s probability is the product of the probabilities of its chosen labels. CTC sums that product over all paths that collapse to the target string, using dynamic programming instead of enumerating them. The loss is the negative log of the sum. Backpropagation adjusts the score head and CNN filters using the likelihood of the whole line, not a handpicked alignment. A blank between two O events lets both survive; two adjacent O events collapse to one.

At inference, this export uses the simpler greedy route: take the highest-scoring class at each position, then collapse and look up the IDs in the shipped charset. The full line is scored in a forward pass, with no text tokenizer feeding back a prompt and no language model to correct a misspelling. The best single alignment is not always the most probable string across all alignments. That’s why greedy decode can be wrong even when the box is right.

LlamaIndex’s training appendix describes 32-pixel-high labeled crops with perspective, skew, blur, compression and other augmentations. The labels combine sources such as PDF text, synthetic renderings, existing annotations, and teacher transcriptions. The teacher can help supply labels without running at inference. And the recognizer reads grayscale: it uses glyph contrast and shape, not color categories. LayoutNet’s separate attention has a different job: organizing the recognized text on the page.

Why the full parser gets its CPU numbers

Some of the gain is work it avoids. Usable PDF text doesn’t have to be read from a raster image; mixed pages can mask text they already have. The authors report using 250 DPI rather than 300 DPI, which means about 31% fewer pixels at the same page size. On the Latin model alone, static INT8 went from 3.4 to 1.5 ms per line versus the authors’ FP32 variant, while HierText character error rose from 0.132 to 0.137. The larger gains in table and layout scores come from LayoutNet, not from a faster detector.

LlamaIndex report, Tables 5–7: accuracy and throughput measure different workloads
ConfigurationParseBench-2Pages/s, 16 vCPUs
LiteParse with Tesseract48.714.2
Indra 1.1.255.129.6
Marker 2.2.0, fast52.524.7
LiteParse with PP-OCRv6 tiny + LayoutNet58.914.7
LiteParse with PP-OCRv6 small + LayoutNet59.95.7
OCRia OCR only, no LayoutNet51.237.2
Full OCRia-nano-159.227.8

Throughput came from 300 ParseBench-1 pages, with 16 single-core workers across five hosts. The paper reports 426 ms mean on one core for the full pipeline; removing LayoutNet reduced that to 325 ms. Indra was slightly faster in pages per second. PP-OCRv6 small scored a little higher in the same LiteParse pipeline, but took longer, and the report notes that its RapidOCR HTTP path adds some request overhead. Those are system-level measurements, not claims that one convolution kernel is faster. Our CKE versus ONNX Runtime measurements use just the same detector and Latin recognizer on both sides, not PDF pages and not LayoutNet.

Run OCRia with CKE

Start with the same 512 × 512 receipt used in this article. You need a Linux C toolchain, Python with venv, and curl. These commands pin both the CKE revision and the three OCRia files. Run the commands from a fresh working directory.

Build OCRia and read the sampleBash
git clone --filter=blob:none https://github.com/C-Kernel-Engine/C-Kernel-Engine.git
cd C-Kernel-Engine
git checkout --detach bebf5cd21
python3 -m venv .venv
source .venv/bin/activate
python -m pip install numpy pillow scipy jsonschema 'onnx==1.21.0'

mkdir -p ocria-assets
for file in det.onnx rec_latin.onnx rec_latin.charset.json; do
  curl -fL --retry 2 \
    "https://huggingface.co/llamaindex/OCRia-nano-1/resolve/v1.0.0/$file" \
    -o "ocria-assets/$file"
done
curl -fL 'https://www.antsand.com/uploads/b2124321cd9c9709061d9d1c112bc604/c0a1327deb336b71147f315322d88646image.png' -o market-receipt.png

runner=version/v8/scripts/run_ocria_generated_v8.py
python "$runner" build ocria-assets ocria-512 --target-isa portable
python "$runner" run ocria-512 market-receipt.png --threads 4 --repeats 1

Look for native.text in the result: it starts with MAPLE MARKET and ends with TOTAL 8.40. ONNX is used to read the model files at build time; you don’t need to install ONNX Runtime to run this lane. To compare engines, install onnxruntime==1.31.1 and add --oracle ocria-assets to the run command. This portable build is a starting point, not the optimized build timed above.

To try your own picture, start with an upright Latin PNG or JPEG and correct its orientation before uploading. This bundle expects the detector input to resolve to 512 × 512; for a different shape, follow the runner’s resize rule or prepare a new bundle with build --width W --height H. The runner scales the longest edge down to at most 768 pixels, then rounds both edges to multiples of 32.

Send image bytes over HTTP

CKE’s OCRia runner takes a local file today. The example below puts a small, loopback-only server in front of it: the client sends bytes, the server writes them to a temporary file, and the runner returns text. The server never opens a client-supplied path. This is a local example, not a shipped CKE endpoint or a hardened upload service.

Show ocria-local.pyocria-local.pyPython
"""Local OCRia upload demo. Run from the root of the pinned CKE checkout."""
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
import json
import subprocess
import sys
from tempfile import TemporaryDirectory


class Upload(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path != '/ocr':
            return self.send_error(404)
        media = {'image/png': '.png', 'image/jpeg': '.jpg'}
        suffix = media.get(self.headers.get_content_type())
        if suffix is None:
            return self.send_error(415, 'Expected image/png or image/jpeg')
        length = self.headers.get('Content-Length', '')
        if not length.isascii() or not length.isdecimal() or len(length) > 8:
            return self.send_error(411, 'Content-Length required')
        size = int(length)
        if not 0 < size <= 8 * 1024 * 1024:
            return self.send_error(413, 'Image exceeds the upload limit')
        self.connection.settimeout(15)
        try:
            body = self.rfile.read(size)
        except TimeoutError:
            return self.send_error(408)
        if len(body) != size:
            return self.send_error(400, 'Incomplete image')
        with TemporaryDirectory() as folder:
            image = Path(folder) / ('input' + suffix)
            image.write_bytes(body)
            try:
                run = subprocess.run(
                    [sys.executable, 'version/v8/scripts/run_ocria_generated_v8.py',
                     'run', sys.argv[1], str(image), '--threads', '4', '--repeats', '1'],
                    capture_output=True, check=True, text=True, timeout=60,
                )
                text = json.loads(run.stdout)['native']['text']
            except subprocess.TimeoutExpired:
                return self.send_error(504, 'OCR timed out')
            except subprocess.CalledProcessError:
                return self.send_error(422, 'Could not read the image with this bundle')
        payload = json.dumps({'text': text}).encode()
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)


if __name__ == '__main__':
    if len(sys.argv) != 2 or not (Path(sys.argv[1]) / 'ocria.json').is_file():
        raise SystemExit('Usage: python ocria-local.py PATH_TO_BUNDLE')
    with HTTPServer(('127.0.0.1', 8091), Upload) as server:
        print('Listening on http://127.0.0.1:8091/ocr', flush=True)
        server.serve_forever()
Start the server and upload a receiptBash
# Save the example as ocria-local.py in the CKE checkout.
.venv/bin/python ocria-local.py ocria-512

# In a second terminal in the same checkout:
curl -fsS -H 'Content-Type: image/png' \
  --data-binary @market-receipt.png http://127.0.0.1:8091/ocr

Use image/jpeg for a JPEG. The local example processes one upload at a time and loads the bundle for each request. It returns {"text":"..."}; its timing is not the warm benchmark above.

The detector and Latin recognizer already compile to native shared objects. A C application can link the generated library, load the matching weights.bin into a 64-byte-aligned arena, and fill the input ports using the offsets and sizes in ocria.json. For the detector the generated entry is int ck_ocria_detector(void *arena, size_t bytes). I linked a plain C executable against it and got a byte-for-byte match with the Python-hosted detector’s heatmap from the same prepared receipt tensor. That executable did not link Python or ONNX Runtime.

The portable detector I built above is 38.7 KiB for the shared object, plus 321.6 KiB of packed detector weights and the layout files. Those are file sizes, not working memory, and they don’t include the Latin recognizer. The tested library is a Linux x86-64 ELF using glibc; portable selects a kernel path, not a binary format that also runs on Arm, macOS, or Windows.

I’m providing the build recipe rather than a bare binary download. The library, weights and layout form a matched bundle, and building locally avoids a glibc or CPU mismatch. It also keeps the model files with the publisher’s license and distribution terms; CKE’s licensing status is documented separately.

After the quickstart builds ocria-512, put these two short files in the CKE checkout. The shell script uses the Python environment once to prepare a normalized FP32 tensor, check the bundle, and capture a reference heatmap. It then links the detector and runs the C executable.

Show probe-detector.cprobe-detector.cC
#define _POSIX_C_SOURCE 200112L
#include <stdio.h>
#include <stdlib.h>

int ck_ocria_detector(void *arena, size_t bytes);

static int read_exact(const char *path, void *dst, size_t size)
{
    FILE *file = fopen(path, "rb");
    if (!file) return 0;
    int ok = fread(dst, 1, size, file) == size && fgetc(file) == EOF && !ferror(file);
    fclose(file);
    return ok;
}

int main(int argc, char **argv)
{
    void *allocation;
    if (argc != 3 || posix_memalign(&allocation, 64, ARENA)) return 1;
    unsigned char *arena = allocation;
    for (size_t i = 0; i < ARENA; ++i) arena[i] = 0;
    if (!read_exact(argv[1], arena + WEIGHTS, WEIGHT_BYTES) ||
        !read_exact(argv[2], arena + PIXELS, PIXEL_BYTES)) {
        free(arena);
        return 2;
    }
    int status = ck_ocria_detector(arena, ARENA);
    if (!status) {
        const float *heat = (const float *)(arena + HEAT);
        if (fwrite(heat, 1, HEAT_BYTES, stdout) != HEAT_BYTES) status = 3;
    }
    free(arena);
    return status != 0;
}
Show run-detector-probe.shrun-detector-probe.shBash
#!/usr/bin/env bash
set -euo pipefail

# Run in the pinned CKE checkout, next to probe-detector.c.
if [[ $# -ne 3 ]]; then
  printf 'Usage: bash run-detector-probe.sh BUNDLE IMAGE NEW_OUTPUT_DIR\n' >&2
  exit 2
fi
bundle=$(realpath -- "$1")
image=$(realpath -- "$2")
out=$3
mkdir -- "$out"
out=$(realpath -- "$out")
export CK_NUM_THREADS=1 CK_THREADPOOL_CAPACITY=1

flags=$(.venv/bin/python - "$bundle" "$image" "$out" <<'PY'
import json
import math
import sys
from pathlib import Path

import numpy as np
from PIL import Image, ImageOps
from version.v8.scripts.run_ocria_generated_v8 import NativeStage

bundle, image, out = map(Path, sys.argv[1:])
spec = json.loads((bundle / "ocria.json").read_text())
det = spec["detector"]
ports = det["ports"]
heat = ports[spec["heat"]]
pixels = ports["pixels"]
stage = NativeStage(bundle / "detector", det, "ck_ocria_detector", {
    "pixels": ((1, 3, None, None), "fp32"),
    spec["heat"]: ((1, 1, None, None), "fp32"),
})
with Image.open(image) as source:
    rgb = ImageOps.exif_transpose(source).convert("RGB")
    if rgb.size != tuple(reversed(pixels["shape"][2:])):
        raise SystemExit("Use an image matching the detector's width and height.")
    tensor = np.ascontiguousarray(
        (np.asarray(rgb, dtype=np.float32) / 127.5 - 1).transpose(2, 0, 1)[None]
    )
tensor.tofile(out / "pixels.f32")
reference, = stage.run(tensor)
reference.tofile(out / "reference.f32")
layout = {
    "ARENA": det["arena_bytes"], "WEIGHTS": det["weights_offset"],
    "WEIGHT_BYTES": det["weights_bytes"], "PIXELS": pixels["offset"],
    "PIXEL_BYTES": 4 * math.prod(pixels["shape"]), "HEAT": heat["offset"],
    "HEAT_BYTES": 4 * math.prod(heat["shape"]),
}
for name, value in layout.items():
    print(f"-D{name}={value}")
PY
)
mapfile -t defines <<< "$flags"
cc -std=c11 -O2 -Wall -Wextra -Werror "${defines[@]}" \
  probe-detector.c "$bundle/detector/generated.so" -o "$out/probe-detector"
"$out/probe-detector" "$bundle/detector/weights.bin" "$out/pixels.f32" > "$out/heat.f32"
cmp "$out/reference.f32" "$out/heat.f32"
printf 'Detector heatmaps match byte for byte.\n'
Build and run the native detector probeBash
bash run-detector-probe.sh ocria-512 market-receipt.png detector-check
# Expected: Detector heatmaps match byte for byte.

# Run the compiled probe again without invoking Python:
CK_NUM_THREADS=1 CK_THREADPOOL_CAPACITY=1 \
  ./detector-check/probe-detector ocria-512/detector/weights.bin \
  detector-check/pixels.f32 > detector-check/heat-again.f32
cmp detector-check/reference.f32 detector-check/heat-again.f32

Use a fresh output directory for the first command and keep the shared object at its build location for this probe. heat-again.f32 is the detector’s raw heatmap, not text. Only use the probe with the trusted bundle and tensor you prepared for it; it is not an input-validation layer for external uploads.

That test starts with a normalized tensor, not a JPEG. The full photo-to-text app still needs to decode the image, find and resize crops, turn the Latin IDs into characters, assemble reading order, and handle uploads if it serves HTTP. Those steps live in the Python host today. A small native adapter that owns that pipeline, takes image bytes and returns text would be a useful next step. The library and metadata are a matched build, not a stable general-purpose OCR ABI. ONNX Runtime has a C API too; the Python harness used for the comparison isn’t a requirement of ONNX Runtime itself.

Where OCR sits in the document parser

The LlamaIndex technical report describes an 8.1-million-parameter family of models. In LiteParse, a PDF can already have selectable text. Where the page needs OCR, a small detector finds text regions. A router identifies the script and line orientation, and picks a recognizer: Latin, CJK, RTL or World. LayoutNet uses spatial information to recover document structure. Those last steps are how you get something more useful than a pile of strings, such as a table whose entries stay with the right columns.

Three rows show full document parsing, the publisher’s OCR branch, and the narrower generated CKE image path.
Explore the full workflow and CKE’s two generated stages.

For this run, the input is an upright 512 by 512 image in a PNG. The test harness in Python decodes it with Pillow, handles orientation metadata, and normalizes its RGB values. CKE produces a heatmap. The host finds connected regions above 0.55, keeps components with a mean score of at least 0.60, maps their padded boxes back to the image, and resizes each crop to 32 pixels high in grayscale. The boxes here are axis-aligned. The publisher’s pipeline can handle rotated quadrilaterals. After CKE runs the Latin recognizer on each crop, the host assembles reading order from box positions.

Three ways OCR can fail: missed region, misread crop, or incorrect line order.
A text box tells you where the detector looked. It doesn’t tell you whether the decoder or reading order got it right.

What the kernels compute

The detector maps RGB pixels to a heatmap; the recognizer maps a grayscale crop through affine convolution and CTC to text.
Follow the tensors from pixels to characters.

Detector: find the text before reading it

The roughly 82,000-parameter detector uses a DBNet-style architecture. Each pixel channel starts as a float, p / 127.5 − 1. A convolution moves a small learned filter over an image; at each position it multiplies the filter by the input patch and sums. In a depthwise convolution each channel gets its own spatial filter. A pointwise convolution then mixes the channels at that position with a 1 by 1 filter:

dc,h,w=∑i,jKc,i,jxc,h+i,w+j,yo,h,w=bo+∑cPo,cdc,h,w.

The first sum combines nearby pixels; the second combines features. I’ve left padding and stride out of the equation to show the two sums. The detector upsamples and concatenates features at different resolutions, then applies the sigmoid 1 / (1 + exp(−z)) to turn each final score into a value between zero and one. This is the heatmap the host reads. It still contains no letters.

Recognizer: a sequence of character scores, one column at a time

The Latin model has about 0.8 million parameters and 792 output classes: 791 characters plus a CTC blank. The recognizer takes one crop and returns a sequence of score columns. On this path there is one time position for every four input pixels across the padded crop. The smallest safe bucket is picked from widths 160, 224, 320 and 512. A bucket has to preserve context on the right of the last time position we actually read; simply rounding up to the next width can change the last few scores.

The byte-activation build keeps values in an unsigned-byte representation through the recognizer backbone. For a real input value x, scale Sₓ and zero point zₓ, the encoder rounds, shifts and clamps. For the signed-weight pointwise path, each output channel has a weight scale. The dot product uses integer accumulation, with bias in accumulator units, then converts into the output scale and zero point:

qi=clip[0,255](round⁡(xi/Sx)+zx)
ac=bc+∑i(qi−zx)wc,i,qc′=clip[0,255](round⁡(acSxSw,c/Sy)+zy).

On the P3, AVX-VNNI has an instruction, vpdpbusd, that groups unsigned-byte by signed-byte products into 32-bit sums. The detector uses its own FP32 path. Separating those two paths matters when you build for a particular CPU.

At the CTC head, pick the largest score at each time position. You don’t need to compute softmax to pick the maximum, but the checked head also returns a softmax confidence for that winning class. Collapse adjacent repeated IDs first, then discard the blanks. B O O blank O K becomes BOOK: the first pair of O scores collapses, and the blank preserves the second O in the word. The model computes the columns together; it doesn’t need to feed each output character back into the model to generate the next one.

Two images and what both engines read

I typeset these images so I could compare the results against the text used to make them. They’re synthetic: no purchase details or customer records. Both engines returned these exact strings on both machines. They matched all six expected lines in each image after normalizing spaces between words. The output is text, so the columns in the original image need not survive.

Market receipt

Synthetic Maple Market receipt with oats, apples, tax and a total.
Original 512 by 512 test input.
MAPLE MARKET
DATE 2026-11-29
OATS 4.25
APPLES 3.75
TAX 0.40
TOTAL 8.40

Workshop invoice

Synthetic invoice 1042 with parts, labour and a total.
Original 512 by 512 test input.
WORKSHOP INVOICE
INVOICE 1042
DATE 2026-11-30
PARTS 12.00
LABOUR 18.00
TOTAL 30.00

We also checked inside the pipeline. The largest absolute heatmap difference was below 0.000001 on both images. Crop boxes and the CTC IDs used to assemble text matched exactly. Both engines agreeing is useful for checking the port; it doesn’t guarantee either engine is right. A separate retained CKE receipt fixture has a small extra fragment that both engines read. Two clean examples don’t tell us how often errors show up on curled receipts, glare, or more complicated layouts.

The gallery has 15 synthetic inputs: receipts, forms, a parts label, a landscape delivery slip, a narrow repair ticket, and a two-column stocktake sheet. Some look like camera photos; others isolate tilt, glare, small type, or reading order. Several use the same underlying form so I can see what changes when I turn it.

Inputs come in portrait, landscape, and square, from 320 × 448 up to a long 750 × 1800 ticket. The host shrinks the longest side to at most 768 pixels before rounding to the detector grid. It crops the text from the original image.

Fifteen inputs: eleven exact pages, one reading-order change, two text errors, and one rejection.
The 15 gallery inputs in table order. The two benchmark images and the ImageGen receipt are separate.

How to read the overlays: green outlines are actual CKE crop boxes associated with an exact line; orange outlines are actual crop boxes where the text differs; blue outlines are unmatched detections. Purple dashed lines show expected regions with no matched crop, or reference regions on a rejected image. Open an example to see the original image, the recognized text, and the mismatches. A green outline checks the text assigned to the line, not whether the crop geometry is perfect.

“Exact lines” compares the text of each expected line to the boxes assigned by overlap, after collapsing repeated whitespace. Page character error rate (CER) counts substitutions, insertions and deletions in the assembled page text, divided by the number of expected characters. It also catches reading-order mistakes. These are exploratory medians of five warm runs per engine on four Ryzen cores, using the same host and input for both engines. Rejected inputs have no CER or timing in the table. Keep the isolated Ryzen and P3 comparison below separate.

What it read well: Eleven inputs matched the expected page text. That includes the square cafe slip, the landscape delivery confirmation, the narrow repair ticket and this particular faint-print fixture. Both engines produced identical boxes, character IDs and text on all 14 accepted inputs.

Where it lost text: The 3° tilt variant got six of eleven lines, including a misread request ID, and the 9° variant got none exactly. Both engines hit the host’s region limit on the sideways form. Rotating that image upright restored all eleven lines.

Where it changed the order: On the stocktake sheet, all ten text regions matched. The host read across rows, alternating between columns, while the reference reads all of Aisle A before Aisle B. It’s a useful example of why I check the assembled output in addition to the boxes.

One more receipt, this time from an image generator

I asked ImageGen for a phone-style photo of a fictional receipt with seven lines, then checked what it actually printed before running OCR. Both engines read all seven lines exactly, including the order number, date and total, and their crop boxes and character IDs matched. The boxes below come from CKE, unlike the illustrative boxes on the cover. This is one extra demo outside the scored gallery.

Image-generated Harbor Supply receipt7/7
Original · 1086 × 1448
Original: Image-generated Harbor Supply receipt
Detection overlay
Detection overlay: Image-generated Harbor Supply receipt
OCR output
HARBOR SUPPLY
ORDER 3182
DATE 2026-11-30
TAPE 4.50
CLIPS 2.75
TAX 0.36
TOTAL 7.61

Would I use this for my own receipts and forms?

I’d try it as a local inbox that drafts text and fields for review. I’d keep the original image, correct its orientation first, and add deskew or perspective correction before treating it as an everyday camera workflow. I’d validate amounts and dates, keep the text next to its crop, and send rejected images or questionable fields to a review queue. For a receipt, subtotal plus tax matching the total is a useful check, but it can’t prove the merchant, date, or every item was read correctly.

I wouldn’t use this experiment to post expenses or fill downstream records without review. The next test I’d run is a set of real receipts and forms that I’m allowed to use, including curled paper, tiny print, deeper shadows, and layouts we didn’t design ourselves. I’d track exact totals, dates and IDs, how often the pipeline asks for review, and how long it takes to fix an output. That tells me whether it saves time in my workflow.

CKE and ONNX Runtime on the same CPUs

CKE reads the ONNX weights at build time and runs generated C; the reference opens the same original weights with ONNX Runtime.
Compare what runs in the two processes.

I pinned the publisher’s v1.0.0 model files and CKE commit bebf5cd21. The ONNX Runtime side used 1.31.1 and the CPU Execution Provider. Each timed process ran one engine with the same host image and crop policy, affinity, and a one- or four-worker budget on distinct physical cores. On the P3 I used P-cores. The table is the median of nine warm measured repeats per image. It includes PNG decoding, preprocessing, detection, crops, recognition and text assembly. It excludes session creation, model load and compilation.

Warm image-to-text latency, median milliseconds
CPU and CKE buildCoresInputCKEORTCKE / ORT
AMD Ryzen 9 9950X3D
avx512_vnni
1Market receipt14.6610.771.36×
AMD Ryzen 9 9950X3D
avx512_vnni
1Workshop invoice15.3011.061.38×
AMD Ryzen 9 9950X3D
avx512_vnni
4Market receipt10.477.501.40×
AMD Ryzen 9 9950X3D
avx512_vnni
4Workshop invoice10.977.501.46×
Intel Core i7-14700T (P3)
avx_vnni
1Market receipt35.8423.091.55×
Intel Core i7-14700T (P3)
avx_vnni
1Workshop invoice37.7723.811.59×
Intel Core i7-14700T (P3)
avx_vnni
4Market receipt26.0516.451.58×
Intel Core i7-14700T (P3)
avx_vnni
4Workshop invoice27.0117.081.58×

ONNX Runtime was faster on both machines, by a factor of about 1.36–1.46 on Ryzen and 1.55–1.59 on the P3 when you divide CKE latency by ORT latency. On the P3 I also tested a plain avx2_fma build. CKE took 245–300 ms on four cores, versus 26–27 ms with avx_vnni. The plain build led important byte operations down a scalar path. Those dry numbers are a good reason to record the build target alongside the CPU. The same model and the same text output can give you very different timings.

The comparable result is engine latency within each machine. These are different machines and build targets. This is also a warm microbenchmark on two pictures. It doesn’t cover cold start, throughput on a queue of pages, server tail latency, multilingual accuracy or the runtime of the full publisher parser.

The OCRia work in the PR history below went from a saved reference run to the first CPU-specific optimizations over two days. ONNX Runtime has had years of CPU optimization, and it was still faster here. For the next round I’d profile detector and recognizer separately, change one thing at a time, and check parity again before reporting a speedup. That’s how we’ll find out where CKE can close the gap and which particular shapes or CPUs might favor generated C.

What CKE adds when ONNX Runtime already works

ONNX Runtime is a good first choice if you want to run the available exports today. CKE answers a different deployment question: can we turn the two learned graphs into checked, model-specific C entry points, and see which operations and layouts are responsible for their cost? The runner reads and checks the pinned ONNX assets at build time. CKE plans tensor storage, binds supported kernel shapes and targets, and builds shared libraries. The native-only timing process didn’t import ONNX or ONNX Runtime. The host code still does image I/O, crop geometry and result assembly.

Reusing the compiler and its kernel contracts gave us a place to start with a non-LLM model. We still had to map the detector’s image-plane operations, the recognizer’s quantized operators, and the CTC output. The compiler leaves behind the circuit, lowered calls and memory layout, so I can see which kernel an operation became, where its output goes, and what changes when I try a different layout. That gives us something to inspect between the original model and the final latency number.

OCRia gave us our first retained ONNX Runtime reference for this OCR path. It gives CKE another independent engine to test against, alongside PyTorch and llama.cpp on other models. Here I can swap in a new detector layout or byte kernel and compare the same heatmap, boxes and character IDs with ONNX Runtime before I look at speed. ONNX Runtime is a test reference for the generated path, not a dependency of it.

What actually goes on the device?

Both are practical choices. ONNX Runtime is a general engine, but it already supports reduced-operator builds and mobile deployment. With CKE the deployment starts from the other direction: generate C for a known circuit, then build it with the kernel sources that circuit calls and the runtime support it needs. A C toolchain makes that a useful starting point for an embedded Linux board or a phone. The actual target still needs compatible kernels, enough memory, and a host to feed the model. An x86 VNNI build won’t run on an Arm phone, and I haven’t tested this bundle on one.

The footprint numbers tell two different stories. The five generated shared objects in the benchmark, one detector and four recognizer widths, total about 198–201 KiB across the two builds. That’s code alone. The packed weights take another 3.51 MiB in this bundle because the recognizer weights are packaged separately for each width. The FP32 detector also sets aside about 76 MiB of workspace at 512 by 512, before you count the Python image harness. A small shared library isn’t the same thing as a small application.

For a fixed device I’d first see whether one crop width suffices, then measure the trade-off between duplicated weights, speed, and workspace. I’d compare the complete package and peak RAM against a reduced ONNX Runtime build on that same device. CKE gives us a way to trim around a particular model; this benchmark doesn’t establish which complete deployment is smaller.

CKE / OCRia

The pull requests behind this port

In PR-number order, including the topic branches. Some landed together on main; the commit link is the PR merge recorded by GitHub.

  1. PR #1296
    Kept a repeatable ONNX Runtime baseline and published its scope and results.
    Reference · d57e88c1e
  2. PR #1297
    Replaced 40 detector convolutions with CKE calls while the rest of the graph still ran under ONNX Runtime.
    Hybrid · 2f3b2bff9
  3. PR #1298
    Ran the Latin image-to-text pipeline with CKE convolutions and measured it against the reference.
    Hybrid · 0a4d77bf9
  4. PR #1302
    Generated the detector and connected the generated Latin path. Added checked image resize, sigmoid, affine Q/DQ and CTC operations.
    Generated C · 644961052
  5. PR #1303
    Tiled checked grouped convolution and vectorized activations.
    Performance · b45171237
  6. PR #1305
    Lowered Latin recognition to generated C and compared the resulting OCR path against ONNX Runtime.
    Generated C · feb39ad54
  7. PR #1306
    Vectorized quantize and dequantize operations and replayed them against ONNX.
    Performance · 2ded01c54
  8. PR #1309
    Matched physical cores and reported actual utilization rather than inferring it from the thread count.
    Measurement · 2bc6a5a53
  9. PR #1311
    Packed signed weights for the Latin pointwise convolution.
    Performance · df1513986
  10. PR #1313
    Kept activations in UINT8 between spatial, pointwise and residual operations, instead of crossing into float at each step.
    Performance · ea4171eec
  11. PR #1314
    Specialized detector rows and protected the recognizer’s valid CTC region when choosing a narrower crop width.
    Performance · 9cf3e4703
  12. PR #1316
    Ran the detector in channel-contiguous layout with matching convolution, resize and concatenation operations.
    Performance · fd4df8abc
  13. PR #1317
    Added Intel AVX-VNNI byte dot products for the OCR recognizer.
    Performance · 1efa26a33
  14. PR #1318
    Specialized the full-width HWC convolution interior, where the image boundary checks are unnecessary.
    Performance · 8d4f9a8ad

What I’d test next

I’d add receipts shot at an angle, faint print, and multi-column invoices, then track character errors and whether the important fields were read correctly. I’d test CKE’s host crop policy against the publisher’s own geometry separately from the kernel benchmark. That would tell us whether to put the next round of work into the detector and recognizer, or into the steps that get the right crop and layout in the first place.

Start with the CKE getting-started docs, the pinned vision evidence and the release license. The November CKE review puts this next to Unlimited-OCR and the other model work from the month. For the launch context, see the MarkTechPost write-up.