docling_pdf/tableformer.rs
1//! TableFormer: table-structure recovery via docling-ibm-models, exported to
2//! ONNX by `scripts/install/export_tableformer.py`. The image encoder + tag-transformer
3//! encoder run once to a memory tensor; the decoder is then stepped
4//! autoregressively to emit an OTSL structure-token sequence (the same model
5//! docling runs). See docs/PDF_CONFORMANCE.md.
6
7use crate::pdfium_backend::TextCell;
8// The ONNX-free half (preprocessing, structure corrections, bbox bookkeeping,
9// span merge, OTSL→grid) lives in tf_core so the browser build (#157 stage 3)
10// runs the same logic; this file owns the three `ort` sessions and the
11// owned-value KV-cache fast path.
12use crate::tf_core::{
13 argmax, build_table_cells, correct, merge_spans, preprocess_input, BboxBook, TableCell, END,
14 MAX_STEPS, START, UCEL,
15};
16use image::RgbImage;
17use ort::session::Session;
18use ort::value::{DynValue, Tensor};
19
20const SIDE: usize = crate::tf_core::SIDE as usize;
21const EMBED_DIM: usize = crate::tf_core::EMBED_DIM;
22/// Decoder geometry, fixed by the exported TableModel04_rs graph: the cached
23/// decoder threads a `[N_LAYERS, past, 1, EMBED_DIM]` per-layer state cache.
24const N_LAYERS: usize = 6;
25
26/// Resolve the encoder / decoder / bbox files exactly as [`TableFormer::load`]
27/// will (shared with `model_inventory`, so diagnostics can never drift from
28/// what actually loads). Explicit `DOCLING_TABLEFORMER_*` overrides win; the
29/// decoder otherwise picks by preference — INT8 variants first unless
30/// `DOCLING_RS_FP32` opts out, and within a precision the true-KV-cache
31/// export (`decoder_kv*`, one token per step, O(past) step cost) ranks ahead
32/// of the legacy layer-output-cache graph it matches byte-for-byte (91/91
33/// snapshot corpus exact with either; the KV graph re-measured ~13–17% faster
34/// warm, so speed wins the default and the legacy file stays as the smaller
35/// fallback). `decoder_kv` ranks ABOVE `decoder_int8`: the #97 hoisted fp32
36/// KV graph is faster than the quantized legacy graph on every machine
37/// measured, and it is byte-exact (its own int8 variant is not produced — see
38/// quantize_models.py).
39pub fn resolved_paths() -> (String, String, String) {
40 let enc = docling_core::env::nonempty("DOCLING_TABLEFORMER_ENCODER")
41 .unwrap_or_else(|| crate::resolve_asset(".models/tableformer/encoder.onnx"));
42 let dec = docling_core::env::nonempty("DOCLING_TABLEFORMER_DECODER").unwrap_or_else(|| {
43 let candidates: &[&str] = if crate::prefer_fp32() {
44 &[
45 ".models/tableformer/decoder_kv.onnx",
46 ".models/tableformer/decoder.onnx",
47 ]
48 } else {
49 &[
50 ".models/tableformer/decoder_kv_int8.onnx",
51 ".models/tableformer/decoder_kv.onnx",
52 ".models/tableformer/decoder_int8.onnx",
53 ".models/tableformer/decoder.onnx",
54 ]
55 };
56 candidates
57 .iter()
58 .map(|p| crate::resolve_asset(p))
59 .find(|p| std::path::Path::new(p).exists())
60 .unwrap_or_else(|| ".models/tableformer/decoder.onnx".to_string())
61 });
62 let bbx = docling_core::env::nonempty("DOCLING_TABLEFORMER_BBOX")
63 .unwrap_or_else(|| crate::resolve_asset(".models/tableformer/bbox.onnx"));
64 (enc, dec, bbx)
65}
66
67pub struct TableFormer {
68 encoder: Session,
69 decoder: Session,
70 bbox: Session,
71 /// Which decoder graph flavour is loaded, detected from the session's
72 /// input names (so an explicit `DOCLING_TABLEFORMER_DECODER` override
73 /// works with any of them).
74 style: DecoderStyle,
75}
76
77/// The three decoder-graph generations the loop supports.
78#[derive(Clone, Copy, PartialEq, Eq)]
79enum DecoderStyle {
80 /// `decoder.onnx`: layer-output cache; feeds the full `tags` prefix and a
81 /// single `cache` every step.
82 Legacy,
83 /// The pre-#97 `decoder_kv.onnx`: one tag per step, `cache_k`/`cache_v`,
84 /// with the stacked `cross_k`/`cross_v` re-split inside every step.
85 KvStacked,
86 /// The #97 `decoder_kv.onnx`: one tag per step, and the constant cross
87 /// tensors arrive as 2×`N_LAYERS` per-layer inputs (`cross_kt_i` already
88 /// transposed for q·Kᵀ, `cross_v_i`), computed once per table by the
89 /// encoder — the step graph does no work proportional to their size.
90 KvHoisted,
91}
92
93/// KV-cache geometry fixed by the `decoder_kv.onnx` export
94/// (`[N_LAYERS, 1, KV_HEADS, past, KV_HEAD_DIM]`, `KV_HEADS × KV_HEAD_DIM = EMBED_DIM`).
95const KV_HEADS: usize = 8;
96const KV_HEAD_DIM: usize = 64;
97
98/// The autoregressive decode state: `a` is the legacy layer-output cache, or
99/// `cache_k` for the KV graph; `b` is `cache_v` (KV graph only). `None` = first
100/// step (the zero-`past` empties are allocated per table by [`TableFormer::empty_cache`]).
101#[derive(Default)]
102struct DecodeCache {
103 a: Option<DynValue>,
104 b: Option<DynValue>,
105}
106
107/// Zero-`past` first-step cache tensors: `(cache, None)` for the legacy graph,
108/// `(cache_k, Some(cache_v))` for the KV graph.
109type EmptyCache = (Tensor<f32>, Option<Tensor<f32>>);
110
111/// Encoder outputs that drive the cached decode loop: the per-layer cross-attention
112/// K/V (projected from the image memory once, constant across decode steps) and
113/// `enc_out` for the bbox decoder. Kept as owned `ort` values so each decode step
114/// (and the bbox run) borrows them directly — no per-step extract/copy/re-wrap.
115struct EncodeOut {
116 ck: DynValue,
117 cv: DynValue,
118 eo: DynValue,
119 /// `KvHoisted` only: per-layer `[cross_kt_0..N, cross_v_0..N]`, index-aligned
120 /// with the decoder's input names, borrowed by every decode step.
121 per_layer: Vec<(String, DynValue)>,
122}
123
124impl TableFormer {
125 /// Load the exported encoder/decoder/bbox ONNX graphs (env overrides, else
126 /// `.models/tableformer/{encoder,decoder,bbox}.onnx`). Returns `None` if any is
127 /// absent, so the pipeline falls back to geometric reconstruction.
128 pub fn load() -> Option<Self> {
129 Self::load_with(crate::intra_threads())
130 }
131
132 /// Like [`load`](Self::load) but with an explicit intra-op thread count, so a
133 /// parallel page-worker pool can run each table model on fewer threads (the
134 /// throughput comes from running pages concurrently, not from one fat model).
135 ///
136 /// See [`resolved_paths`] for the encoder/decoder/bbox file selection.
137 pub fn load_with(intra: usize) -> Option<Self> {
138 // (resolution shared with the model inventory — see resolved_paths)
139 let (enc, dec, bbx) = resolved_paths();
140 if crate::timing::enabled() {
141 eprintln!("docling-pdf: tableformer decoder: {dec}");
142 }
143 if [&enc, &dec, &bbx]
144 .iter()
145 .any(|p| !std::path::Path::new(p).exists())
146 {
147 // The geometric fallback is a supported, intentional configuration
148 // (docling has no ML table-structure equivalent baked in either), so
149 // this stays a single quiet stderr note rather than an error — but it
150 // fires every process (not per-worker) so a CWD-relative default that
151 // silently misses its files (a very easy mistake for anything not run
152 // from the repo root, e.g. an embedding app) is at least visible once.
153 warn_missing_once(&enc, &dec, &bbx);
154 return None;
155 }
156 // The decoder's KV-cache grows by one entry every autoregressive step, so
157 // its input shapes differ on every `run()` call. ONNX Runtime's memory
158 // pattern optimizer assumes stable shapes to plan buffer reuse; disabling
159 // it for this session avoids repeatedly re-validating/re-touching that
160 // plan (and the external-weights file) on each step.
161 let build = |path: &str, mem_pattern: bool| -> Result<Session, String> {
162 let builder = Session::builder()
163 .map_err(|e| e.to_string())?
164 .with_intra_threads(intra)
165 .map_err(|e| e.to_string())?
166 .with_memory_pattern(mem_pattern)
167 .map_err(|e| e.to_string())?;
168 let variant = if mem_pattern {
169 "mem_pattern"
170 } else {
171 "no_mem_pattern"
172 };
173 docling_onnx::commit(docling_onnx::apply(builder)?, path, variant)
174 .map_err(|e| format!("tableformer load {path}: {e}"))
175 };
176 match (build(&enc, true), build(&dec, false), build(&bbx, true)) {
177 (Ok(encoder), Ok(decoder), Ok(bbox)) => {
178 let has = |n: &str| decoder.inputs().iter().any(|i| i.name() == n);
179 let style = if has("cross_kt_0") {
180 DecoderStyle::KvHoisted
181 } else if has("cache_k") {
182 DecoderStyle::KvStacked
183 } else {
184 DecoderStyle::Legacy
185 };
186 if style == DecoderStyle::KvHoisted
187 && !encoder.outputs().iter().any(|o| o.name() == "cross_kt_0")
188 {
189 eprintln!(
190 "docling-pdf: tableformer decoder needs per-layer cross tensors \
191 (cross_kt_*) the encoder doesn't emit — re-download or re-export \
192 the model set (scripts/install/export_tableformer.py); \
193 falling back to geometric tables"
194 );
195 return None;
196 }
197 Some(Self {
198 encoder,
199 decoder,
200 bbox,
201 style,
202 })
203 }
204 _ => None,
205 }
206 }
207
208 /// Run the image encoder and capture what the cached decoder loop needs: each
209 /// decoder layer's cross-attention K/V (projected from the image memory once,
210 /// shape `[N_LAYERS,1,H,S,head_dim]`) and `enc_out` for the bbox decoder.
211 fn encode(&mut self, img: &RgbImage) -> Result<EncodeOut, String> {
212 let input = preprocess(img)?;
213 let mut enc_out = self
214 .encoder
215 .run(ort::inputs!["image" => input])
216 .map_err(|e| format!("tableformer: encode: {e}"))?;
217 let mut per_layer = Vec::new();
218 if self.style == DecoderStyle::KvHoisted {
219 for prefix in ["cross_kt_", "cross_v_"] {
220 for i in 0.. {
221 let name = format!("{prefix}{i}");
222 match enc_out.remove(&name) {
223 Some(v) => per_layer.push((name, v)),
224 None => break,
225 }
226 }
227 }
228 if per_layer.is_empty() {
229 return Err("tableformer: encoder emitted no cross_kt_* outputs".into());
230 }
231 }
232 let mut grab = |name: &str| -> Result<DynValue, String> {
233 enc_out
234 .remove(name)
235 .ok_or_else(|| format!("tableformer: encoder output {name} missing"))
236 };
237 Ok(EncodeOut {
238 ck: grab("cross_k")?,
239 cv: grab("cross_v")?,
240 eo: grab("enc_out")?,
241 per_layer,
242 })
243 }
244
245 /// One doubly-cached decode step: feed the current `tags`, the constant cross
246 /// K/V, and the growing self-attention `cache`; return the raw argmax tag and
247 /// the last token's hidden state, advancing the cache. The cache stays an owned
248 /// `ort` value — the previous step's `out_cache` output is fed back directly,
249 /// never extracted or copied (it grows every step, so per-step copies were
250 /// O(steps²) float traffic). `empty_cache` is the zero-`past` value used on the
251 /// first step (ort's array constructors reject a 0-length dim, so it is
252 /// allocated through the session allocator by the caller).
253 fn decode_step(
254 &mut self,
255 tags: &[i64],
256 enc: &EncodeOut,
257 cache: &mut DecodeCache,
258 empty: &EmptyCache,
259 ) -> Result<(i64, Vec<f32>), String> {
260 crate::timing::timed("tf.decode_step", || {
261 self.decode_step_inner(tags, enc, cache, empty)
262 })
263 }
264
265 fn decode_step_inner(
266 &mut self,
267 tags: &[i64],
268 enc: &EncodeOut,
269 cache: &mut DecodeCache,
270 empty: &EmptyCache,
271 ) -> Result<(i64, Vec<f32>), String> {
272 let mut dout = match self.style {
273 DecoderStyle::KvHoisted => {
274 // #97 graph: one tag; the constant per-layer cross tensors are
275 // borrowed views — the step pays nothing proportional to them.
276 let last = *tags.last().expect("decode starts from <start>");
277 let tag_t = Tensor::from_array(([1usize, 1usize], vec![last]))
278 .map_err(|e| format!("tableformer: tag: {e}"))?;
279 let mut inputs: Vec<(
280 std::borrow::Cow<'_, str>,
281 ort::session::SessionInputValue<'_>,
282 )> = Vec::with_capacity(3 + enc.per_layer.len());
283 inputs.push(("tag".into(), tag_t.into()));
284 match (cache.a.as_ref(), cache.b.as_ref()) {
285 (Some(k), Some(v)) => {
286 inputs.push(("cache_k".into(), k.into()));
287 inputs.push(("cache_v".into(), v.into()));
288 }
289 _ => {
290 inputs.push(("cache_k".into(), (&empty.0).into()));
291 inputs.push((
292 "cache_v".into(),
293 empty
294 .1
295 .as_ref()
296 .expect("kv empty cache has both halves")
297 .into(),
298 ));
299 }
300 }
301 for (name, v) in &enc.per_layer {
302 inputs.push((name.as_str().into(), v.into()));
303 }
304 self.decoder.run(inputs)
305 }
306 DecoderStyle::KvStacked => {
307 // Pre-#97 KV graph: feed only the newly emitted tag; the projected
308 // K/V for the whole prefix live in cache_k/cache_v and are fed
309 // back as-is.
310 let last = *tags.last().expect("decode starts from <start>");
311 let tag_t = Tensor::from_array(([1usize, 1usize], vec![last]))
312 .map_err(|e| format!("tableformer: tag: {e}"))?;
313 match (cache.a.as_ref(), cache.b.as_ref()) {
314 (Some(k), Some(v)) => self.decoder.run(ort::inputs![
315 "tag" => tag_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
316 "cache_k" => k, "cache_v" => v]),
317 _ => self.decoder.run(ort::inputs![
318 "tag" => tag_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
319 "cache_k" => &empty.0,
320 "cache_v" => empty.1.as_ref().expect("kv empty cache has both halves")]),
321 }
322 }
323 DecoderStyle::Legacy => {
324 let tags_t = Tensor::from_array(([tags.len(), 1usize], tags.to_vec()))
325 .map_err(|e| format!("tableformer: tags: {e}"))?;
326 match cache.a.as_ref() {
327 None => self.decoder.run(ort::inputs![
328 "tags" => tags_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
329 "cache" => &empty.0]),
330 Some(c) => self.decoder.run(ort::inputs![
331 "tags" => tags_t, "cross_k" => &enc.ck, "cross_v" => &enc.cv,
332 "cache" => c]),
333 }
334 }
335 }
336 .map_err(|e| format!("tableformer: decode: {e}"))?;
337 let (_, logits) = dout["logits"]
338 .try_extract_tensor::<f32>()
339 .map_err(|e| format!("tableformer: logits: {e}"))?;
340 let raw = argmax(logits) as i64;
341 let (_, hidden) = dout["hidden"]
342 .try_extract_tensor::<f32>()
343 .map_err(|e| format!("tableformer: hidden: {e}"))?;
344 let hidden = hidden.to_vec();
345 if self.style != DecoderStyle::Legacy {
346 cache.a = Some(
347 dout.remove("out_cache_k")
348 .ok_or_else(|| "tableformer: out_cache_k missing".to_string())?,
349 );
350 cache.b = Some(
351 dout.remove("out_cache_v")
352 .ok_or_else(|| "tableformer: out_cache_v missing".to_string())?,
353 );
354 } else {
355 cache.a = Some(
356 dout.remove("out_cache")
357 .ok_or_else(|| "tableformer: decoder output out_cache missing".to_string())?,
358 );
359 }
360 Ok((raw, hidden))
361 }
362
363 /// The zero-`past` first-step cache(s), allocated through the session
364 /// allocator (ort's array constructors reject a 0-length dim; the C API does
365 /// allow it).
366 fn empty_cache(&self) -> Result<EmptyCache, String> {
367 let alloc = self.decoder.allocator();
368 if self.style != DecoderStyle::Legacy {
369 let mk = || {
370 Tensor::<f32>::new(alloc, [N_LAYERS, 1, KV_HEADS, 0usize, KV_HEAD_DIM])
371 .map_err(|e| format!("tableformer: empty kv cache: {e}"))
372 };
373 Ok((mk()?, Some(mk()?)))
374 } else {
375 let c = Tensor::<f32>::new(alloc, [N_LAYERS, 0usize, 1, EMBED_DIM])
376 .map_err(|e| format!("tableformer: empty cache: {e}"))?;
377 Ok((c, None))
378 }
379 }
380
381 /// Predict the OTSL structure-token sequence for a table-region image.
382 pub fn predict_otsl(&mut self, img: &RgbImage) -> Result<Vec<i64>, String> {
383 let enc = self.encode(img)?;
384 // Structure corrections live in tf_core::correct (shared with the wasm
385 // path); docling's line_num is never incremented, so xcel→lcel fires on
386 // every row.
387 let mut tags: Vec<i64> = vec![START];
388 let mut out: Vec<i64> = Vec::new();
389 let mut prev_ucel = false;
390 let mut cache = DecodeCache::default();
391 let empty = self.empty_cache()?;
392 while out.len() < MAX_STEPS {
393 let (raw, _hidden) = self.decode_step(&tags, &enc, &mut cache, &empty)?;
394 let tag = correct(raw, prev_ucel);
395 if tag == END {
396 break;
397 }
398 out.push(tag);
399 tags.push(tag);
400 prev_ucel = tag == UCEL;
401 }
402 Ok(out)
403 }
404
405 /// Full structure prediction: OTSL grid cells with per-cell boxes (in the 448
406 /// image, normalized cxcywh). Collects per-cell decoder hidden states using
407 /// docling's exact bbox bookkeeping (skip-after-row-break, first-lcel of a
408 /// horizontal span), runs the bbox decoder, merges span boxes, then lays the
409 /// cells onto the OTSL grid with row/col spans.
410 pub fn predict_table_structure(&mut self, img: &RgbImage) -> Result<Vec<TableCell>, String> {
411 let enc = self.encode(img)?;
412
413 // The autoregressive loop's bbox bookkeeping lives in tf_core::BboxBook
414 // (shared with the wasm path); this loop only steps the decoder.
415 let mut book = BboxBook::new();
416 let mut cache = DecodeCache::default();
417 let empty = self.empty_cache()?;
418 while book.otsl.len() < MAX_STEPS {
419 let (raw, hidden) = self.decode_step(&book.tags, &enc, &mut cache, &empty)?;
420 if !book.step(raw, &hidden) {
421 break;
422 }
423 }
424 if book.n == 0 {
425 return Ok(Vec::new());
426 }
427 let tag_h = Tensor::from_array(([book.n, EMBED_DIM], std::mem::take(&mut book.hiddens)))
428 .map_err(|e| format!("tableformer: tag_h: {e}"))?;
429 let bout = self
430 .bbox
431 .run(ort::inputs!["enc_out" => &enc.eo, "tag_h" => tag_h])
432 .map_err(|e| format!("tableformer: bbox: {e}"))?;
433 let (_, raw) = bout["boxes"]
434 .try_extract_tensor::<f32>()
435 .map_err(|e| format!("tableformer: boxes: {e}"))?;
436 let boxes: Vec<[f32; 4]> = raw
437 .chunks_exact(4)
438 .map(|c| [c[0], c[1], c[2], c[3]])
439 .collect();
440 // Per-cell class logits [n, 3] → argmax (docling's `outputs_class`).
441 let (_, craw) = bout["classes"]
442 .try_extract_tensor::<f32>()
443 .map_err(|e| format!("tableformer: classes: {e}"))?;
444 let classes: Vec<i64> = craw.chunks_exact(3).map(|c| argmax(c) as i64).collect();
445 let (merged, merged_classes) = merge_spans(&boxes, &classes, &book.merge);
446 Ok(build_table_cells(&book.otsl, &merged, &merged_classes))
447 }
448
449 /// Predict a table region's Markdown grid: crop the region (docling's
450 /// page→1024px box-average then bbox crop), run the structure model, then
451 /// match the page's word cells into the predicted cells with docling's
452 /// matching post-processor ([`crate::tf_match`]) and expand spans into a
453 /// dense `rows × cols` grid. `region` is `(l, t, r, b)` in page points
454 /// (top-left). Returns `None` if no structure is predicted.
455 pub fn predict_table_rows(
456 &mut self,
457 page_image: &RgbImage,
458 region: [f32; 4],
459 words: &[TextCell],
460 ) -> Option<crate::tf_core::TableGrid> {
461 // page → 1024px height (cv2.INTER_AREA), then crop the table bbox.
462 // docling's coordinate chain, rounding included: the cluster bbox is
463 // rounded to integer page points *first* (`round(cluster.bbox.l) *
464 // scale`, banker's rounding), scaled by 2 (its table-structure page
465 // scale), then by `1024 / <2x page-image height>`, and the crop indices
466 // round again. Rounding after scaling instead shifts some crops by a
467 // pixel — enough to change TableFormer's cell boxes on tall tables
468 // (redp5110's TOC).
469 let sf = 1024.0 / page_image.height() as f32;
470 let pw = (page_image.width() as f32 * sf) as u32;
471 let page1024 = crate::timing::timed("tableformer.inter_area", || {
472 crate::resample::inter_area(page_image, pw, 1024)
473 });
474 let k = 2.0 * 1024.0 / page_image.height() as f64;
475 let px = |v: f32| (v as f64).round_ties_even() * k;
476 let x = (px(region[0]).round_ties_even()).max(0.0) as u32;
477 let y = (px(region[1]).round_ties_even()).max(0.0) as u32;
478 let x2 = (px(region[2]).round_ties_even() as u32).min(page1024.width());
479 let y2 = (px(region[3]).round_ties_even() as u32).min(page1024.height());
480 if x2 <= x || y2 <= y {
481 return None;
482 }
483 let crop = image::imageops::crop_imm(&page1024, x, y, x2 - x, y2 - y).to_image();
484 let cells = crate::timing::timed("tableformer.structure", || {
485 self.predict_table_structure(&crop)
486 })
487 .ok()?;
488 if cells.is_empty() {
489 return None;
490 }
491 // The ort-free tail (word matching + grid assembly) is shared with the
492 // browser path in tf_core.
493 crate::tf_core::table_rows(&cells, region, words)
494 }
495}
496
497/// Note once per process that TableFormer's ONNX graphs weren't found, so tables
498/// fall back to geometric reconstruction. The default paths are relative
499/// (`.models/tableformer/*.onnx`), which only resolves when the process's current
500/// directory happens to be the repo root — a very easy miss for anything else
501/// (an embedding app, a binding invoked from a different working directory, …),
502/// and previously failed with no signal at all.
503fn warn_missing_once(enc: &str, dec: &str, bbx: &str) {
504 static WARNED: std::sync::Once = std::sync::Once::new();
505 WARNED.call_once(|| {
506 eprintln!(
507 "docling.rs: TableFormer models not found (checked {enc}, {dec}, {bbx}); \
508 tables will use geometric reconstruction instead of ML table-structure \
509 recognition. Set DOCLING_TABLEFORMER_ENCODER / DOCLING_TABLEFORMER_DECODER \
510 / DOCLING_TABLEFORMER_BBOX to enable it (see README.md)."
511 );
512 });
513}
514
515/// docling's preprocessing: bilinear (cv2.INTER_LINEAR) resize the crop to 448²,
516/// normalize `(x/255 − mean)/std`, laid out as (C, W, H) — docling transposes
517/// (2,1,0), so width is the major spatial axis. The page→1024px box-average
518/// (cv2.INTER_AREA) is the caller's job.
519fn preprocess(img: &RgbImage) -> Result<Tensor<f32>, String> {
520 Tensor::from_array(([1usize, 3, SIDE, SIDE], preprocess_input(img)))
521 .map_err(|e| format!("tableformer: input: {e}"))
522}