Document AI OCR: A Practical Guide to Visual Text Compression
This article explains how modern document OCR can be approached as a visual text compression problem, where a vision encoder maps pixels into compact visual tokens and a language model decodes them into text. It covers the encoder-decoder architecture, how to tune the visual token budget, five configuration tiers, structured output and layout preservation, throughput and cost optimization, common failure modes, and a staged rollout strategy for production deployment.
1. Why Document Recognition Is Being Redone Through the Lens of Compression
Traditional document recognition pipelines usually split the task into two stages: layout analysis first, then character recognition, with rules stitching the results back into structured text. This pipeline is fragile on professional documents with multi-column layouts, mixed text and images, and dense tables and formulas. The problem is not recognition accuracy itself, but that intermediate information is repeatedly cropped and layout semantics are largely lost during transfer.
A newer approach that has emerged in the industry over the past two years treats “image to text” as a lossy or controllable compression problem. A high-resolution document image often contains hundreds of thousands of pixels, while the plain text carrying the same semantics may be only a few thousand bytes. If a vision encoder can map pixels into a compact sequence of visual tokens, and a language model then decodes that sequence into text, the compression ratio becomes a quantifiable and tunable core metric. The value of this perspective is that it puts “recognition accuracy” and “token budget” on the same axis, turning engineering choices from experience-based judgment into measurable experiments.
It is worth emphasizing that compression ratio and accuracy are not linearly related. There is usually a clear inflection point: before it, adding visual tokens improves accuracy almost linearly; past it, gains decay quickly while memory and latency costs keep rising. The key to engineering practice is finding the optimum that the business can accept, rather than blindly pursuing the highest configuration.
2. Architecture Breakdown: Dividing Responsibilities Between Encoder and Decoder
These solutions generally adopt a two-stage structure of “vision encoder + lightweight decoder,” with the total parameter count kept at a small scale to enable single-GPU deployment.
The vision encoding side is typically a fusion of two types of components: one excels at pixel-level segmentation and region localization, responsible for splitting a page into semantically coherent segments; the other excels at semantic discrimination and image-text alignment, responsible for assigning high-level representations to those segments. Features from both paths are aligned to the language model’s embedding space through a projection module, forming a unified sequence of visual tokens. The direct benefit is that the model not only “recognizes characters” but also preserves the relative positions of text, tables, and images in the original page, providing a basis for subsequent structured output.
The decoding side mostly uses a sparse-activation mixture-of-experts structure, decoupling total parameters from per-token computation, so the model can still handle long sequences under limited memory. For developers, this means throughput gains come mainly from reduced activated parameters, not from sacrificing context length.
The second-generation approach makes two notable adjustments on top of this: first, it abandons the heavyweight vision backbone and instead uses a lightweight language model as the vision encoder, explicitly preserving layout information while extracting text; second, it introduces a learnable “causal flow query” mechanism that dynamically reorders image segments, allowing the model to consume visual information in reading order rather than a fixed scan order. For complex documents with multiple columns, cross-page content, and interleaved text and images, this dynamic ordering is often more effective than simply increasing resolution.
3. Token Budget: The Core Tuning Knob of the Whole Approach
In practice, the number of visual tokens is the parameter most worth tuning first. Typical ranges span from a little over two hundred to a little over eleven hundred tokens, with different tiers matching different scenarios:
- Low-budget tier (around one to two hundred tokens): suited to well-structured printed text, receipts, and forms; fastest and cheapest;
- Medium-budget tier (around four to five hundred tokens): covers most business documents, balancing tables and paragraph structure;
- High-budget tier (eight hundred tokens and above): aimed at complex layouts and high-density small-font text;
- Mixed-size tier: for oversized pages, combines “global thumbnail + local high resolution” input to avoid blurring small text caused by whole-page downsampling.
A reusable tuning workflow is as follows: first fix the business sample set, scan the token budget tier by tier from low to high, and record the curves of accuracy and per-page latency; find the inflection point where the accuracy gain falls below a set threshold (for example, less than one percentage point gain per doubling of tokens), then round up one tier as the default configuration; finally, for failed samples, judge whether the issue is insufficient resolution or layout complexity, and adjust the size strategy or switch to mixed mode accordingly.
# Illustration: token budget sweep and inflection point selectiondef sweep_token_budget(model, samples, budgets=(256, 400, 600, 800, 1120)):results = []for b in budgets:acc, latency = evaluate(model, samples, visual_tokens=b)results.append((b, acc, latency))print(f"tokens={b:4d} acc={acc:.2%} ms/page={latency:.1f}")# A gain below the threshold is treated as the inflection pointfor (b0, a0, _), (b1, a1, _) in zip(results, results[1:]):if (a1 - a0) < 0.01:return b1, resultsreturn results[-1][0], results
4. Selection Logic for the Five Configuration Tiers
The point of tiered configuration is to let the same model serve very different hardware and scenarios:
- Tiny tier: aimed at on-device or edge equipment, pursuing extremely low latency, suited to single-field extraction and barcode-type documents;
- Small tier: the main tier for everyday office documents, with the best cost-performance ratio;
- Base tier: balances accuracy and throughput, suitable as the service default;
- Large tier: aimed at long documents such as contracts and financial reports, requiring more complete context modeling;
- Gundam tier: uses asymmetric mixed input sizes and a dedicated cropping strategy, optimized for large-format pages with multi-column layouts and mixed text and images.
When selecting, it is recommended to follow the order of “scenario first, then tier”: clarify the document type distribution, per-page character density, and whether tables and formulas are present, then determine the tier accordingly, rather than the reverse of using the highest tier to cover all traffic. The latter significantly raises unit cost and yields almost no accuracy gain on simple documents.
5. Structured Output and Layout Preservation
Outputting plain text only loses the correspondence between heading levels, lists, tables, and figure captions. Viable approaches include: having the model directly generate text with lightweight markup, then parsing it into structured objects in post-processing; routing table regions through a separate structured recognition branch that outputs a row-column matrix; and outputting placeholders and position boxes for image regions to facilitate backfilling.
# Document Title## First-Level SectionBody paragraph...| Column A | Column B | Column C || --- | --- | --- || 1 | 2 | 3 |[Figure 1] Caption text
Engineering practice also needs built-in bounding box detection and dynamic cropping: first locate text blocks, then crop and send them for recognition block by block, avoiding the small-text information loss caused by whole-page scaling. The cropping strategy must be coordinated with the token budget; when there are too many blocks, layout merging should be done first to prevent tokens from being consumed by large blank areas.
6. Performance and Cost: Where Throughput Comes From
For a solution that processes on the order of two hundred thousand pages per day on a single GPU, throughput typically comes from three overlapping factors: a sparse-activation decoder that lowers per-token compute, a controllable number of visual tokens, and batching plus operator fusion that reduce scheduling overhead. To reproduce similar gains in engineering implementation, consider the following directions:
- Batching and dynamic padding: group batches by token-length buckets to reduce wasted computation;
- Precision and memory optimization: use low-precision weights and key-value cache reuse during inference;
- Pipeline parallelism: split PDF parsing, image rendering, recognition, and structured post-processing into independent stages, decoupled with a message queue;
- Elastic scaling: run stateless recognition services on a container platform, auto-scaling based on queue backlog;
- Observability: store original documents in object storage, send task metrics and failed samples to a logging service, and use monitoring and alerting to locate quality regressions.
7. Common Failure Modes and How to Avoid Them
- Blurred small text: caused by whole-page downsampling; switch to mixed sizes or local high-resolution cropping;
- Scrambled reading order: a fixed scan order does not fit multi-column layouts and needs a dynamic reordering mechanism;
- Table misalignment: merged cells are not modeled, so table regions should be handled by a separate branch;
- Long-document truncation: exceeds the context window, requiring segmented recognition and stitching by layout coordinates;
- Hallucinated text: low-confidence regions are forcibly completed, so a confidence threshold and a manual review queue should be introduced.
8. Implementation Recommendations
It is recommended to proceed in three steps: “small-sample baseline + tiered scanning + canary rollout.” First build an evaluation set covering the real document distribution and establish accuracy and latency baselines; then determine the default token budget and tier using the method in Section 3; finally roll out gradually, continuously using failed samples to optimize cropping and post-processing rules. If you are already running on general capabilities such as the container platform, object storage, and logging and monitoring offered by Baidu AI Cloud, you can directly reuse its elastic scaling and observability systems and focus your attention on the model and layout strategy themselves.
