Visual Text Compression in Document AI: Token Budgets, Accuracy Trade-offs, and Engineering Practice
This article breaks down visual text compression in document AI, where document images are treated as visually encoded long-text carriers and the goal is to carry as much text and layout information as possible with as few visual tokens as possible. It explains the encoder-decoder split behind the approach, the measured relationship between compression ratio and recognition accuracy, learnable dynamic token reallocation strategies, five configuration tiers and how to route between them, and the throughput, output-format, and observability practices needed for batch production. Readers will also find the known capability boundaries, common misconceptions, and a decoupled cloud architecture pattern for running this kind of pipeline.
1. Background: Why Compression Matters for Document Recognition
Traditional document recognition pipelines split the problem in two stages: layout analysis first, text recognition second, with rules or post-processing stitching the structure back together. On professional documents with multi-column layouts, mixed text and graphics, or dense tables, this chain tends to fail in a specific way: it recognizes text but not layout. The characters are correct, but the reading order is scrambled, tables are flattened into a string of characters, and the association between captions and body text is lost.
A newer line of thinking treats the document image as a long-text carrier that has been visually encoded, and re-examines the vision encoder from a large language model’s perspective. The goal on the visual side is no longer just turning pixels into features, but carrying as complete text and layout information as possible with as few visual tokens as possible. This is the visual-text compression boundary problem: given a token budget, how much recognition accuracy can be preserved; and conversely, given an accuracy target, how low can the token budget be pushed.
The value of this perspective lies in the cost structure. Document processing is a high-frequency, long-tail, batch workload. Once per-page cost is multiplied across millions of pages, the number of visual tokens directly determines compute spend. Compression ratio therefore stops being an academic metric and becomes an engineering metric you can account for.
2. Core Architecture: Dividing Labor Between Encoder and Decoder
These approaches generally adopt a layered structure of a strong encoder plus a small decoder. A typical form: the encoder renders the image into a compact visual representation, the decoder only handles autoregressive text generation, and total parameter count is kept at a relatively small scale (for example, around 3B, with the decoding branch built as a sparsely activated MoE with low activation volume). The rationale for this split:
- The output space of document recognition is relatively closed, with a limited character set and limited layout templates, so an oversized decoder is unnecessary;
- The encoder sets the information ceiling, so shifting the parameter budget toward the encoding side is equivalent to raising information density per token;
- Sparse activation keeps average activated parameters low in batch scenarios, with clear throughput gains.
Early-generation designs commonly combined a segmentation-style vision backbone with a semantic vision backbone on the encoding side, and used a projection module to align visual features to the language model’s embedding space. The segmentation branch is good at separating text blocks and graphic regions from the background; the semantic branch is good at identifying “what this is.” The two are complementary, letting the model extract text while retaining spatial layout cues from the original image, which supports downstream structured output.
3. The Quantified Relationship Between Compression Ratio and Accuracy
The curve engineers care about most is compression ratio versus accuracy. Using the magnitudes commonly discussed in public sources as a reference: at roughly 10x lossless compression, recognition accuracy can hold at a high level (around 97%); raising the compression ratio to about 20x drops accuracy to roughly sixty percent. This curve yields two direct conclusions:
- Within 10x is the “safe to rely on” range, suitable for completeness-sensitive scenarios such as archiving, retrieval, and knowledge base ingestion;
- The 20x range is only suitable for coarse filtering, table-of-contents extraction, keyword location, and other error-tolerant tasks, and should not be used directly as a final structured data source.
It is worth stressing that the denominator of compression ratio is the number of visual tokens while the numerator is the equivalent amount of text information, and the “equivalence relationship” varies widely by document type: pure text pages have large compression headroom, while table and formula pages have little. Production environments must therefore measure in buckets by document type rather than doing capacity planning off a single global average.
4. Dynamic Token Budgets: From Fixed Resolution to Learnable Reallocation
The pain point of fixed-resolution encoding is one-size-fits-all: simple pages waste tokens, complex pages run short. The second generation shifts to a learnable dynamic reallocation mechanism, with two typical approaches:
- Causal stream queries: a set of learnable query vectors scans image segments in causal order, dynamically deciding which segments deserve more tokens and concentrating the budget on information-dense regions;
- Mixed sizes with dynamic cropping: for very large, complex documents, use stitched non-uniform resolutions, then locate text blocks with bounding box detection and encode each cropped block separately.
The token input range typically spans a few hundred to just over a thousand tokens (for example, 256 to 1120), which means the same model can be tuned continuously between saving compute and preserving accuracy. The practical recommendation is to make the token budget a configuration item bound to a business SLA:
# Illustrative configuration, not a specific product interfaceocr_pipeline:doc_class: mixed_layout # plain text / table / mixed text and graphicsvisual_token_budget: 800 # value within the 256 ~ 1120 rangecrop_strategy: bbox_dynamic # full page / fixed grid / dynamic bbox croppingoutput_format: markdownfallback:if_confidence_below: 0.75then: raise_budget_to 1120
This two-stage strategy of running at a low budget first and raising the budget only when confidence is insufficient is usually cheaper than a uniform high budget, and the tail distribution is more controllable.
5. Selection Logic for the Five Configurations
The point of tiered configuration is to turn model capability into adjustable levels, commonly divided into five tiers: extra small, small, medium, large, and extra large. Selection should not look at memory alone, but at document shape:
- Extra small / small tiers: suited to mobile devices, edge boxes, and single-column plain text receipts, targeting millisecond-level response;
- Medium tier: the workhorse for general office documents, balancing tables and multi-column layouts;
- Large and extra large tiers: aimed at large-format, multi-column, mixed text-and-graphic professional documents, using mixed sizes and dedicated cropping modes, trading throughput for layout fidelity.
A practical decision rule: run everything through the small tier first, then route samples with low layout confidence, high table proportion, or very large page counts (such as cross-page large tables) to the large tier, forming tiered routing rather than running everything at a high tier.
6. Engineering in Production: Batch, Format, and Throughput
Document recognition in production is usually a batch job, with three concerns: throughput, observability, and output usability.
On throughput, the magnitude mentioned in public discussion is that a single high-end accelerator card can process more than two hundred thousand pages per day. The assumptions behind such a number are typically short outputs, a moderate token budget, and high-concurrency batching. Switching to the extra large tier or a high token budget significantly reduces throughput, so capacity planning must leave headroom.
On output, uniformly producing structured markup (such as Markdown) significantly lowers downstream cost: it can be ingested directly, split into knowledge chunks, and preserve heading hierarchy and table structure. Three things are worth completing in post-processing: reading order correction, table structure validation, and cross-page paragraph merging.
On observability, collect at least four metrics: average visual tokens, compression ratio distribution, confidence distribution, and manual review rate. Without these four metrics, no cost-reduction conclusion can be verified.
# Illustrative batch skeleton, not a specific product interfacedef run_batch(pages, budget=800, batch_size=16):results = []for chunk in batched(pages, batch_size):for r in ocr(chunk, visual_token_budget=budget,output="markdown", return_layout=True):if r.confidence < 0.75:r = ocr([r.page], visual_token_budget=1120,output="markdown", return_layout=True)[0]results.append(r)return results
7. Capability Boundaries and Common Misconceptions
First, compression is not lossless. Errors at high compression ratios concentrate on small font sizes, low contrast, complex tables, and handwriting, which call for image pre-processing (denoising, deskewing, binarization) rather than simply adding tokens.
Second, layout retention is not layout reconstruction. What the model outputs is a sequence with structural cues; the final reading order and table reconstruction still require rule-based or post-processing validation.
Third, benchmark scores cannot be extrapolated directly. An improvement on a public benchmark (for example, one generation gaining about 3.7 percentage points over the previous one on a document understanding benchmark, reaching above ninety percent) indicates a trend, but layout distributions in real business vary enormously, so you must build your own evaluation set.
Fourth, do not treat the visual token budget as the only knob. Image resolution, cropping strategy, and decode length limits all affect final quality and need to be tuned jointly.
8. Connecting to a Cloud Architecture
To deploy this kind of capability on Baidu AI Cloud, the recommended decoupled design is: object storage holds original and derived images, a message queue handles peak shaving and retries, a container platform runs stateless inference services and scales elastically on queue depth, and logging plus monitoring and alerting handle continuous observation of token consumption, timeout rate, and confidence distribution. Keeping model inputs and outputs as a file-based contract makes it easier to migrate and canary between tiers.
Overall, the engineering essence of visual-text compression is converting recognition accuracy into an adjustable token budget curve, then using tiered routing and post-processing to keep errors within a range the business can accept. Mastering this curve is what makes reproducible decisions possible across cost, throughput, and quality.
