Optical Context Compression for Long-Document Recognition
Self-attention cost grows roughly with the square of sequence length, so turning long documents into character-level text tokens makes the prefill stage slow and expensive. This article explains an alternative: treat the page layout itself as information and use a vision encoder to compress a high-resolution page into a small set of visual tokens, which a language model then reconstructs into text, tables, and formulas in reading order. It covers why images work as a first compression stage, how to split the system into a high-compression encoder and a lightweight decoder, how to evaluate accuracy against token budgets and task types, where capabilities end, and how to control cost in production document pipelines.
Long text is not something you can digest simply by “adding a little more context window.” Self-attention compute and memory grow roughly with the square of sequence length. Once a ten-thousand-word paper, a contract bundle, or a scanned meeting record is cut into discrete text tokens by character, the prefill stage becomes both slow and costly. If optical character recognition is treated only as “first turn the image into characters, then stuff the characters into a language model,” the long-document problem is merely deferred, not compressed. A denser idea is to treat the page layout as an already-arranged information carrier: use a vision encoder to compress a high-resolution page into very few visual tokens, then let a language model rebuild the text, tables, and formulas in reading order. This is optical context compression: compression happens before language decoding begins, rather than as trimming applied to an already-inflated text sequence.
Why images suit first-stage compression better than plain text
A single page of layout carries glyph shapes, font sizes, column order, table rules, formula structure, and caption positions all at once. If you run traditional recognition first and then serialize, these two-dimensional relationships are often flattened into a one-dimensional string, and you then need extra markup to restore columns and tables. Encoding the rendered page directly keeps local strokes and global layout in the same set of features. Experimentally, the question people care about is not “can images replace text,” but how well character-level or layout-level fidelity holds under a given visual token budget. The compression ratio can be read as “equivalent text token count / visual token count.” The tighter the budget, the sooner dropped characters, column cross-talk, and formula structure errors tend to appear, rather than everything degrading uniformly by “a little worse.” The value of optical compression therefore lies in a controllable accuracy-cost curve, not in pushing the compression factor ever higher.
Splitting the system in two: high-compression visual encoding and lightweight language reconstruction
A deployable system usually divides into an encoder and a decoder, passing only compact visual tokens between them.
The vision encoder must see strokes clearly while avoiding sending every image patch into the downstream model. A common design is “local first, then downsample, then global”: window attention or convolution extracts strokes and lines at high resolution; a large-stride convolution or pooling in the middle compresses thousands of patch features down to hundreds; global attention fuses column and heading semantics only over the already-shortened sequence. This way activation memory is spent mainly on local windows, not on dense full-page attention. Multi-resolution matters just as much: ordinary body text can use a fixed side length, while dense tables, two-column papers, or ultra-wide drawings use tiled stitching, increasing tokens dynamically with content complexity rather than applying the same maximum resolution to every page.
On the language side, you need not call up a full large-parameter model just to “read characters.” A mixture-of-experts decoder activates only a subset of experts, which suits mapping visual tokens back to text in reading order while retaining some layout-markup ability, such as table cells, heading levels, and linearized formulas. When active parameters are far smaller than total parameters, throughput keeps up with batching more easily. One point to stress: expert routing improves decoding efficiency but cannot make up for stroke information the encoder already discarded. When the compression ratio is too high, the decoder will only fabricate plausible-looking sentences more confidently.
The illustrative data flow can be written as the pseudocode below. It describes responsibility boundaries, not any one vendor’s interface:
page = render_or_scan(document, dpi, color_mode)tokens = vision_encoder(page, token_budget, window_then_global=True)text, layout = moe_decoder(tokens, task="transcribe_and_structure")score = evaluate(text, layout, reference)
Read accuracy, token budget, and task type together
Do not summarize all capability with a single “recognition rate.” Pure printed body text often keeps a very high character fidelity under moderate compression; once you hit handwritten annotations, low-contrast scans, complex tables, chemical structural formulas, or geometric figures, the same token budget fails on structure first. Evaluation should report at least these separately: character or word errors, whether reading order crosses columns, table cell alignment, whether formulas can be reparsed, and whether charts are ignored, described, or transcribed incorrectly. When comparing approaches, you must align visual token count or equivalent compute. Beating a “pipeline with an order of magnitude more tokens” using very few visual tokens is only meaningful on the same document set under the same post-processing constraints; otherwise it just reflects a different task definition.
In industry you also have to watch the tail pages. High mean accuracy does not mean stamped pages, tables spanning pages, and mixed-language layouts are stable. The compression strategy should adapt per page: lower tokens for simple layouts, higher resolution or tiling when dense table rules or small fonts are detected. On failure, fall back to higher resolution or traditional line-by-line recognition rather than forcing low-budget results into the downstream knowledge base.
Capability boundaries beyond “reading characters”
Optical compression pipelines are often used at the same time for layout parsing: turning charts into structured descriptions, formulas into computable linear forms, and simple geometric figures into retained annotation relationships. These abilities depend on whether the training data includes the corresponding supervision; they do not arise automatically just because the encoder downsamples. General visual question answering and reference grounding can also hang off the same visual tokens, but that is an extra task head or instruction and cannot be extrapolated from OCR metrics. Before launch, validate with a separate set to avoid “can read body text” being advertised as “can understand every figure.”
Multilingual support is likewise a data problem. Scripts with large glyph differences, right-to-left writing direction, and mixed Chinese-English on the same page all change how fine the local window needs to look. The list of supported languages should be based on the actual evaluation set, not on the fact that some script appeared in the training corpus.
Controlling cost in engineering deployment
For a batch document factory, the bottleneck is usually disk, rendering, and GPU memory, not the decoder’s parameter slogan. In practice you can converge in the following order:
- Put originals in object storage and slice work by page or document with a message queue, retrying failed pages individually to avoid rerunning a whole bundle.
- Make render resolution and color mode a policy rather than hard-coded; grayscale body text need not go through three-channel high resolution.
- Keep the vision encoder’s shapes fixed where possible for batching, and reserve dynamic high resolution for hard pages flagged by a detector.
- Cap the maximum visual tokens per page, and log the compression ratio, confidence, and manual spot-check results so you can trace which budget tier starts becoming unacceptable.
- Output both plain text and lightweight structure (headings, tables, reading order) so downstream retrieval and QA do not consume only an unstructured string.
- Monitor queue latency, per-page time, peak memory, and the manual revision rate; the revision rate tells you more about whether compression is too aggressive than an offline benchmark does.
In the cloud, these capabilities can all land on general-purpose object storage, queues, GPU inference, and monitoring and alerting. If you use a platform such as Baidu AI Cloud, design OCR or document parsing as a replaceable inference workload: keep input/output formats, retries, and auditing under your own pipeline’s control, and do not tie business correctness to a fixed compression ratio or a fixed resolution.
When to adopt it, and when not to
Optical compression fits when the page is the primary form of information, the text is very long, the layout itself carries structure, and you can accept tuning accuracy against a token budget. It does not fit when the content is already clean electronic text, when you need pixel-level forensics, or when regulations require retaining the original, non-reconstructable character stream. For the latter, optical compression can at most serve as an index and preview; it cannot replace the original file.
In one line: the key to reading long documents with few tokens is not the metaphor of “drawing characters into an image,” but local vision, intermediate downsampling, and controlled decoding working together to turn a two-dimensional layout into a budgetable sequence, with task-split evaluation and hard-page fallback guarding the accuracy floor. Selecting and stress-testing against this framework gets you closer to a deployable document-understanding system than chasing a single model’s marketing metrics.
