Skip to main content

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    // The encoder ranks its fp16-weight repack (`encoder_fp16.onnx`, #374 —
41    // the same graph with the weights stored as fp16 and cast back to fp32
42    // at load, ~half the download, fp32 compute) ahead of the fp32 file
43    // unless `DOCLING_RS_FP32` opts out; an explicit override wins.
44    let enc = docling_core::env::nonempty("DOCLING_TABLEFORMER_ENCODER").unwrap_or_else(|| {
45        let candidates: &[&str] = if crate::prefer_fp32() {
46            &[".models/tableformer/encoder.onnx"]
47        } else {
48            &[
49                ".models/tableformer/encoder_fp16.onnx",
50                ".models/tableformer/encoder.onnx",
51            ]
52        };
53        candidates
54            .iter()
55            .map(|p| crate::resolve_asset(p))
56            .find(|p| std::path::Path::new(p).exists())
57            .unwrap_or_else(|| crate::resolve_asset(".models/tableformer/encoder.onnx"))
58    });
59    let dec = docling_core::env::nonempty("DOCLING_TABLEFORMER_DECODER").unwrap_or_else(|| {
60        let candidates: &[&str] = if crate::prefer_fp32() {
61            &[
62                ".models/tableformer/decoder_kv.onnx",
63                ".models/tableformer/decoder.onnx",
64            ]
65        } else {
66            &[
67                ".models/tableformer/decoder_kv_int8.onnx",
68                ".models/tableformer/decoder_kv.onnx",
69                ".models/tableformer/decoder_int8.onnx",
70                ".models/tableformer/decoder.onnx",
71            ]
72        };
73        candidates
74            .iter()
75            .map(|p| crate::resolve_asset(p))
76            .find(|p| std::path::Path::new(p).exists())
77            .unwrap_or_else(|| ".models/tableformer/decoder.onnx".to_string())
78    });
79    let bbx = docling_core::env::nonempty("DOCLING_TABLEFORMER_BBOX")
80        .unwrap_or_else(|| crate::resolve_asset(".models/tableformer/bbox.onnx"));
81    (enc, dec, bbx)
82}
83
84pub struct TableFormer {
85    encoder: Session,
86    decoder: Session,
87    bbox: Session,
88    /// Which decoder graph flavour is loaded, detected from the session's
89    /// input names (so an explicit `DOCLING_TABLEFORMER_DECODER` override
90    /// works with any of them).
91    style: DecoderStyle,
92    /// The `KvHoisted` decoder's `tag` input has a symbolic batch axis (the
93    /// dynamic-batch `decoder_kv.onnx` export): a page's tables decode
94    /// together, one step for all of them — see [`Self::predict_tables_on`].
95    /// The older fixed-`[1,1]` export decodes the tables one after another.
96    batched: bool,
97}
98
99/// The three decoder-graph generations the loop supports.
100#[derive(Clone, Copy, PartialEq, Eq)]
101enum DecoderStyle {
102    /// `decoder.onnx`: layer-output cache; feeds the full `tags` prefix and a
103    /// single `cache` every step.
104    Legacy,
105    /// The pre-#97 `decoder_kv.onnx`: one tag per step, `cache_k`/`cache_v`,
106    /// with the stacked `cross_k`/`cross_v` re-split inside every step.
107    KvStacked,
108    /// The #97 `decoder_kv.onnx`: one tag per step, and the constant cross
109    /// tensors arrive as 2×`N_LAYERS` per-layer inputs (`cross_kt_i` already
110    /// transposed for q·Kᵀ, `cross_v_i`), computed once per table by the
111    /// encoder — the step graph does no work proportional to their size.
112    KvHoisted,
113}
114
115/// KV-cache geometry fixed by the `decoder_kv.onnx` export
116/// (`[N_LAYERS, 1, KV_HEADS, past, KV_HEAD_DIM]`, `KV_HEADS × KV_HEAD_DIM = EMBED_DIM`).
117const KV_HEADS: usize = 8;
118const KV_HEAD_DIM: usize = 64;
119
120/// The autoregressive decode state: `a` is the legacy layer-output cache, or
121/// `cache_k` for the KV graph; `b` is `cache_v` (KV graph only). `None` = first
122/// step (the zero-`past` empties are allocated per table by [`TableFormer::empty_cache`]).
123#[derive(Default)]
124struct DecodeCache {
125    a: Option<DynValue>,
126    b: Option<DynValue>,
127}
128
129/// Zero-`past` first-step cache tensors: `(cache, None)` for the legacy graph,
130/// `(cache_k, Some(cache_v))` for the KV graph.
131type EmptyCache = (Tensor<f32>, Option<Tensor<f32>>);
132
133/// Encoder outputs that drive the cached decode loop: the per-layer cross-attention
134/// K/V (projected from the image memory once, constant across decode steps) and
135/// `enc_out` for the bbox decoder. Kept as owned `ort` values so each decode step
136/// (and the bbox run) borrows them directly — no per-step extract/copy/re-wrap.
137struct EncodeOut {
138    /// Stacked `[N_LAYERS,1,H,S,hd]` cross K/V — the `Legacy`/`KvStacked`
139    /// decoders' inputs. `None` for `KvHoisted`, which reads the per-layer
140    /// tensors instead: the stacked pair is 2×9.6 MB per table, and a page's
141    /// tables are now all held encoded at once for the batched loop.
142    ck: Option<DynValue>,
143    cv: Option<DynValue>,
144    eo: DynValue,
145    /// `KvHoisted` only: per-layer `[cross_kt_0..N, cross_v_0..N]`, index-aligned
146    /// with the decoder's input names, borrowed by every decode step.
147    per_layer: Vec<(String, DynValue)>,
148}
149
150impl TableFormer {
151    /// Load the exported encoder/decoder/bbox ONNX graphs (env overrides, else
152    /// `.models/tableformer/{encoder,decoder,bbox}.onnx`). Returns `None` if any is
153    /// absent, so the pipeline falls back to geometric reconstruction.
154    pub fn load() -> Option<Self> {
155        Self::load_with(crate::intra_threads())
156    }
157
158    /// Like [`load`](Self::load) but with an explicit intra-op thread count, so a
159    /// parallel page-worker pool can run each table model on fewer threads (the
160    /// throughput comes from running pages concurrently, not from one fat model).
161    ///
162    /// See [`resolved_paths`] for the encoder/decoder/bbox file selection.
163    pub fn load_with(intra: usize) -> Option<Self> {
164        // (resolution shared with the model inventory — see resolved_paths)
165        let (enc, dec, bbx) = resolved_paths();
166        if crate::timing::enabled() {
167            eprintln!("docling-pdf: tableformer decoder: {dec}");
168        }
169        if [&enc, &dec, &bbx]
170            .iter()
171            .any(|p| !std::path::Path::new(p).exists())
172        {
173            // The geometric fallback is a supported, intentional configuration
174            // (docling has no ML table-structure equivalent baked in either), so
175            // this stays a single quiet stderr note rather than an error — but it
176            // fires every process (not per-worker) so a CWD-relative default that
177            // silently misses its files (a very easy mistake for anything not run
178            // from the repo root, e.g. an embedding app) is at least visible once.
179            warn_missing_once(&enc, &dec, &bbx);
180            return None;
181        }
182        // The decoder's KV-cache grows by one entry every autoregressive step, so
183        // its input shapes differ on every `run()` call. ONNX Runtime's memory
184        // pattern optimizer assumes stable shapes to plan buffer reuse; disabling
185        // it for this session avoids repeatedly re-validating/re-touching that
186        // plan (and the external-weights file) on each step. The bbox head has
187        // the same problem one level up: its `tag_h` input is `[ncells, 512]`
188        // and every table has a different cell count, so with the pattern
189        // planner on each run re-plans — and on this graph the plan is *worse*
190        // than none: 290 ms vs 54 ms for a 100-cell table, 560 vs 94 ms for
191        // 200 cells (ORT 1.22, 4 threads). It was 0.26 s per table on the
192        // corpus, more than the encoder.
193        //
194        // The decoder runs on ONE intra-op thread. A step is 49 small GEMMs
195        // over a single token — it streams the layer weights, it does not
196        // compute — so extra threads only add synchronisation: measured 4.1 ms
197        // per step on 1 thread vs 5.5 on 4 (7.1 vs 4.9 once the cache is 100+
198        // long). In the pool it also stops a table decode from taking all the
199        // cores away from the other workers' layout inference. And a
200        // single-thread session has a fixed reduction order, so table
201        // structure no longer varies run-to-run on near-tie tokens the way
202        // multi-threaded float sums let it (the conformance scripts pin one
203        // thread for exactly that reason; the default now matches them). The
204        // encoder keeps the shared budget: one 448×448 CNN + transformer pass
205        // per table, 680 ms single-threaded vs 165 on four.
206        let build = |path: &str, mem_pattern: bool, threads: usize| -> Result<Session, String> {
207            let builder = Session::builder()
208                .map_err(|e| e.to_string())?
209                .with_intra_threads(threads)
210                .map_err(|e| e.to_string())?
211                .with_memory_pattern(mem_pattern)
212                .map_err(|e| e.to_string())?;
213            let variant = if mem_pattern {
214                "mem_pattern"
215            } else {
216                "no_mem_pattern"
217            };
218            docling_onnx::commit(docling_onnx::apply(builder)?, path, variant)
219                .map_err(|e| format!("tableformer load {path}: {e}"))
220        };
221        match (
222            build(&enc, true, intra),
223            build(&dec, false, 1),
224            build(&bbx, false, intra),
225        ) {
226            (Ok(encoder), Ok(decoder), Ok(bbox)) => {
227                let has = |n: &str| decoder.inputs().iter().any(|i| i.name() == n);
228                let style = if has("cross_kt_0") {
229                    DecoderStyle::KvHoisted
230                } else if has("cache_k") {
231                    DecoderStyle::KvStacked
232                } else {
233                    DecoderStyle::Legacy
234                };
235                if style == DecoderStyle::KvHoisted
236                    && !encoder.outputs().iter().any(|o| o.name() == "cross_kt_0")
237                {
238                    eprintln!(
239                        "docling-pdf: tableformer decoder needs per-layer cross tensors \
240                         (cross_kt_*) the encoder doesn't emit — re-download or re-export \
241                         the model set (scripts/install/export_tableformer.py); \
242                         falling back to geometric tables"
243                    );
244                    return None;
245                }
246                // Dynamic batch axis on `tag` ⇒ the export batches decode
247                // steps across tables (ort reports a symbolic dim as -1).
248                let batched = style == DecoderStyle::KvHoisted
249                    && decoder.inputs().iter().any(|i| {
250                        i.name() == "tag"
251                            && matches!(i.dtype(), ort::value::ValueType::Tensor { shape, .. }
252                                if shape.first().is_some_and(|d| *d < 0))
253                    });
254                if crate::timing::enabled() && batched {
255                    eprintln!("docling-pdf: tableformer decoder batches a page's tables per step");
256                }
257                Some(Self {
258                    encoder,
259                    decoder,
260                    bbox,
261                    style,
262                    batched,
263                })
264            }
265            _ => None,
266        }
267    }
268
269    /// Run the image encoder and capture what the cached decoder loop needs: each
270    /// decoder layer's cross-attention K/V (projected from the image memory once,
271    /// shape `[N_LAYERS,1,H,S,head_dim]`) and `enc_out` for the bbox decoder.
272    fn encode(&mut self, img: &RgbImage) -> Result<EncodeOut, String> {
273        let input = crate::timing::timed("tf.preprocess", || preprocess(img))?;
274        let mut enc_out = crate::timing::timed("tf.encoder", || {
275            self.encoder
276                .run(ort::inputs!["image" => input])
277                .map_err(|e| format!("tableformer: encode: {e}"))
278        })?;
279        let mut per_layer = Vec::new();
280        if self.style == DecoderStyle::KvHoisted {
281            for prefix in ["cross_kt_", "cross_v_"] {
282                for i in 0.. {
283                    let name = format!("{prefix}{i}");
284                    match enc_out.remove(&name) {
285                        Some(v) => per_layer.push((name, v)),
286                        None => break,
287                    }
288                }
289            }
290            if per_layer.is_empty() {
291                return Err("tableformer: encoder emitted no cross_kt_* outputs".into());
292            }
293        }
294        let mut grab = |name: &str| -> Result<DynValue, String> {
295            enc_out
296                .remove(name)
297                .ok_or_else(|| format!("tableformer: encoder output {name} missing"))
298        };
299        let hoisted = self.style == DecoderStyle::KvHoisted;
300        Ok(EncodeOut {
301            ck: if hoisted {
302                None
303            } else {
304                Some(grab("cross_k")?)
305            },
306            cv: if hoisted {
307                None
308            } else {
309                Some(grab("cross_v")?)
310            },
311            eo: grab("enc_out")?,
312            per_layer,
313        })
314    }
315
316    /// One doubly-cached decode step: feed the current `tags`, the constant cross
317    /// K/V, and the growing self-attention `cache`; return the raw argmax tag and
318    /// the last token's hidden state, advancing the cache. The cache stays an owned
319    /// `ort` value — the previous step's `out_cache` output is fed back directly,
320    /// never extracted or copied (it grows every step, so per-step copies were
321    /// O(steps²) float traffic). `empty_cache` is the zero-`past` value used on the
322    /// first step (ort's array constructors reject a 0-length dim, so it is
323    /// allocated through the session allocator by the caller).
324    fn decode_step(
325        &mut self,
326        tags: &[i64],
327        enc: &EncodeOut,
328        cache: &mut DecodeCache,
329        empty: &EmptyCache,
330    ) -> Result<(i64, Vec<f32>), String> {
331        crate::timing::timed("tf.decode_step", || {
332            self.decode_step_inner(tags, enc, cache, empty)
333        })
334    }
335
336    fn decode_step_inner(
337        &mut self,
338        tags: &[i64],
339        enc: &EncodeOut,
340        cache: &mut DecodeCache,
341        empty: &EmptyCache,
342    ) -> Result<(i64, Vec<f32>), String> {
343        if self.style == DecoderStyle::KvHoisted {
344            // #97 graph: one tag; the constant per-layer cross tensors are
345            // borrowed views — the step pays nothing proportional to them.
346            let last = *tags.last().expect("decode starts from <start>");
347            let (raws, hidden) = self.step_kv_hoisted(&[last], &enc.per_layer, cache, empty)?;
348            return Ok((raws[0], hidden));
349        }
350        let (ck, cv) = match (enc.ck.as_ref(), enc.cv.as_ref()) {
351            (Some(k), Some(v)) => (k, v),
352            _ => return Err("tableformer: stacked cross K/V missing".into()),
353        };
354        let mut dout = match self.style {
355            DecoderStyle::KvHoisted => unreachable!("handled above"),
356            DecoderStyle::KvStacked => {
357                // Pre-#97 KV graph: feed only the newly emitted tag; the projected
358                // K/V for the whole prefix live in cache_k/cache_v and are fed
359                // back as-is.
360                let last = *tags.last().expect("decode starts from <start>");
361                let tag_t = Tensor::from_array(([1usize, 1usize], vec![last]))
362                    .map_err(|e| format!("tableformer: tag: {e}"))?;
363                match (cache.a.as_ref(), cache.b.as_ref()) {
364                    (Some(k), Some(v)) => self.decoder.run(ort::inputs![
365                        "tag" => tag_t, "cross_k" => ck, "cross_v" => cv,
366                        "cache_k" => k, "cache_v" => v]),
367                    _ => self.decoder.run(ort::inputs![
368                        "tag" => tag_t, "cross_k" => ck, "cross_v" => cv,
369                        "cache_k" => &empty.0,
370                        "cache_v" => empty.1.as_ref().expect("kv empty cache has both halves")]),
371                }
372            }
373            DecoderStyle::Legacy => {
374                let tags_t = Tensor::from_array(([tags.len(), 1usize], tags.to_vec()))
375                    .map_err(|e| format!("tableformer: tags: {e}"))?;
376                match cache.a.as_ref() {
377                    None => self.decoder.run(ort::inputs![
378                        "tags" => tags_t, "cross_k" => ck, "cross_v" => cv,
379                        "cache" => &empty.0]),
380                    Some(c) => self.decoder.run(ort::inputs![
381                        "tags" => tags_t, "cross_k" => ck, "cross_v" => cv,
382                        "cache" => c]),
383                }
384            }
385        }
386        .map_err(|e| format!("tableformer: decode: {e}"))?;
387        let (_, logits) = dout["logits"]
388            .try_extract_tensor::<f32>()
389            .map_err(|e| format!("tableformer: logits: {e}"))?;
390        let raw = argmax(logits) as i64;
391        let (_, hidden) = dout["hidden"]
392            .try_extract_tensor::<f32>()
393            .map_err(|e| format!("tableformer: hidden: {e}"))?;
394        let hidden = hidden.to_vec();
395        if self.style != DecoderStyle::Legacy {
396            cache.a = Some(
397                dout.remove("out_cache_k")
398                    .ok_or_else(|| "tableformer: out_cache_k missing".to_string())?,
399            );
400            cache.b = Some(
401                dout.remove("out_cache_v")
402                    .ok_or_else(|| "tableformer: out_cache_v missing".to_string())?,
403            );
404        } else {
405            cache.a = Some(
406                dout.remove("out_cache")
407                    .ok_or_else(|| "tableformer: decoder output out_cache missing".to_string())?,
408            );
409        }
410        Ok((raw, hidden))
411    }
412
413    /// One `KvHoisted` step over `tags.len()` rows — one table per row. `tags`
414    /// holds each row's last emitted tag, `per_layer` the cross tensors with a
415    /// matching leading batch axis (the encoder's own `[1,…]` outputs for a
416    /// single table, or [`Self::batch_cross`]'s concatenation), and the cache
417    /// grows `[N_LAYERS, rows, H, past, hd]` in lockstep. Returns each row's raw
418    /// argmax tag and the `[rows, EMBED_DIM]` hidden states, flattened.
419    fn step_kv_hoisted(
420        &mut self,
421        tags: &[i64],
422        per_layer: &[(String, DynValue)],
423        cache: &mut DecodeCache,
424        empty: &EmptyCache,
425    ) -> Result<(Vec<i64>, Vec<f32>), String> {
426        let rows = tags.len();
427        let tag_t = Tensor::from_array(([rows, 1usize], tags.to_vec()))
428            .map_err(|e| format!("tableformer: tag: {e}"))?;
429        let mut inputs: Vec<(
430            std::borrow::Cow<'_, str>,
431            ort::session::SessionInputValue<'_>,
432        )> = Vec::with_capacity(3 + per_layer.len());
433        inputs.push(("tag".into(), tag_t.into()));
434        match (cache.a.as_ref(), cache.b.as_ref()) {
435            (Some(k), Some(v)) => {
436                inputs.push(("cache_k".into(), k.into()));
437                inputs.push(("cache_v".into(), v.into()));
438            }
439            _ => {
440                inputs.push(("cache_k".into(), (&empty.0).into()));
441                inputs.push((
442                    "cache_v".into(),
443                    empty
444                        .1
445                        .as_ref()
446                        .expect("kv empty cache has both halves")
447                        .into(),
448                ));
449            }
450        }
451        for (name, v) in per_layer {
452            inputs.push((name.as_str().into(), v.into()));
453        }
454        let mut dout = self
455            .decoder
456            .run(inputs)
457            .map_err(|e| format!("tableformer: decode: {e}"))?;
458        let (_, logits) = dout["logits"]
459            .try_extract_tensor::<f32>()
460            .map_err(|e| format!("tableformer: logits: {e}"))?;
461        let vocab = logits.len() / rows;
462        let raws: Vec<i64> = logits
463            .chunks_exact(vocab)
464            .map(|row| argmax(row) as i64)
465            .collect();
466        let (_, hidden) = dout["hidden"]
467            .try_extract_tensor::<f32>()
468            .map_err(|e| format!("tableformer: hidden: {e}"))?;
469        let hidden = hidden.to_vec();
470        cache.a = Some(
471            dout.remove("out_cache_k")
472                .ok_or_else(|| "tableformer: out_cache_k missing".to_string())?,
473        );
474        cache.b = Some(
475            dout.remove("out_cache_v")
476                .ok_or_else(|| "tableformer: out_cache_v missing".to_string())?,
477        );
478        Ok((raws, hidden))
479    }
480
481    /// Stack the per-layer cross tensors of several encoded tables along the
482    /// batch axis (`[1,H,hd,S]` × B → `[B,H,hd,S]`, same for `cross_v`), index-
483    /// aligned with the decoder's input names. One copy per page — ~20 MB per
484    /// table, nothing next to the decode steps it lets the tables share.
485    fn batch_cross(encs: &[EncodeOut]) -> Result<Vec<(String, DynValue)>, String> {
486        let b = encs.len();
487        let mut out = Vec::with_capacity(encs[0].per_layer.len());
488        for j in 0..encs[0].per_layer.len() {
489            let name = encs[0].per_layer[j].0.clone();
490            let mut data: Vec<f32> = Vec::new();
491            let mut dims = [b, 0, 0, 0];
492            for enc in encs {
493                let (shape, v) = enc.per_layer[j]
494                    .1
495                    .try_extract_tensor::<f32>()
496                    .map_err(|e| format!("tableformer: {name}: {e}"))?;
497                if shape.len() != 4 || shape[0] != 1 {
498                    return Err(format!("tableformer: {name}: unexpected shape {shape:?}"));
499                }
500                dims[1..].copy_from_slice(&[
501                    shape[1] as usize,
502                    shape[2] as usize,
503                    shape[3] as usize,
504                ]);
505                data.reserve(v.len() * b);
506                data.extend_from_slice(v);
507            }
508            let t = Tensor::from_array((dims, data))
509                .map_err(|e| format!("tableformer: {name}: {e}"))?;
510            out.push((name, t.into_dyn()));
511        }
512        Ok(out)
513    }
514
515    /// Decode `encs.len()` tables in lockstep: every step runs the decoder once
516    /// over all of them (a step is 49 weight-streaming GEMMs over one token per
517    /// row — B rows cost about what one does). The caches start empty for
518    /// every row and grow together, so nothing is ever padded or masked; a
519    /// table that emits `<end>` simply keeps its row (fed `END`, output
520    /// ignored) until the last one finishes. Row b of every op is exactly the
521    /// single-table computation, so each table's tokens and hidden states are
522    /// bit-identical to decoding it alone (asserted by the export script's
523    /// batching gate; the corpus snapshots pin it end-to-end).
524    fn decode_batch(&mut self, encs: &[EncodeOut]) -> Result<Vec<BboxBook>, String> {
525        let b = encs.len();
526        let cross = Self::batch_cross(encs)?;
527        let mut books: Vec<BboxBook> = (0..b).map(|_| BboxBook::new()).collect();
528        let mut active = vec![true; b];
529        let mut last = vec![START; b];
530        let mut cache = DecodeCache::default();
531        let empty = self.empty_cache(b)?;
532        crate::timing::timed("tf.decode_loop", || -> Result<(), String> {
533            // Each active table's `otsl` grows by one per step, so a shared
534            // step counter is the per-table `otsl.len() < MAX_STEPS` bound.
535            for _ in 0..MAX_STEPS {
536                if !active.iter().any(|a| *a) {
537                    break;
538                }
539                let (raws, hidden) = crate::timing::timed("tf.decode_step", || {
540                    self.step_kv_hoisted(&last, &cross, &mut cache, &empty)
541                })?;
542                for t in 0..b {
543                    if !active[t] {
544                        continue;
545                    }
546                    let h = &hidden[t * EMBED_DIM..(t + 1) * EMBED_DIM];
547                    if books[t].step(raws[t], h) {
548                        last[t] = *books[t].tags.last().expect("step pushed a tag");
549                    } else {
550                        active[t] = false;
551                        last[t] = END;
552                    }
553                }
554            }
555            Ok(())
556        })?;
557        Ok(books)
558    }
559
560    /// The zero-`past` first-step cache(s) for `rows` tables, allocated through
561    /// the session allocator (ort's array constructors reject a 0-length dim;
562    /// the C API does allow it).
563    fn empty_cache(&self, rows: usize) -> Result<EmptyCache, String> {
564        let alloc = self.decoder.allocator();
565        if self.style != DecoderStyle::Legacy {
566            let mk = || {
567                Tensor::<f32>::new(alloc, [N_LAYERS, rows, KV_HEADS, 0usize, KV_HEAD_DIM])
568                    .map_err(|e| format!("tableformer: empty kv cache: {e}"))
569            };
570            Ok((mk()?, Some(mk()?)))
571        } else {
572            let c = Tensor::<f32>::new(alloc, [N_LAYERS, 0usize, 1, EMBED_DIM])
573                .map_err(|e| format!("tableformer: empty cache: {e}"))?;
574            Ok((c, None))
575        }
576    }
577
578    /// Predict the OTSL structure-token sequence for a table-region image.
579    pub fn predict_otsl(&mut self, img: &RgbImage) -> Result<Vec<i64>, String> {
580        let enc = self.encode(img)?;
581        // Structure corrections live in tf_core::correct (shared with the wasm
582        // path); docling's line_num is never incremented, so xcel→lcel fires on
583        // every row.
584        let mut tags: Vec<i64> = vec![START];
585        let mut out: Vec<i64> = Vec::new();
586        let mut prev_ucel = false;
587        let mut cache = DecodeCache::default();
588        let empty = self.empty_cache(1)?;
589        while out.len() < MAX_STEPS {
590            let (raw, _hidden) = self.decode_step(&tags, &enc, &mut cache, &empty)?;
591            let tag = correct(raw, prev_ucel);
592            if tag == END {
593                break;
594            }
595            out.push(tag);
596            tags.push(tag);
597            prev_ucel = tag == UCEL;
598        }
599        Ok(out)
600    }
601
602    /// Full structure prediction: OTSL grid cells with per-cell boxes (in the 448
603    /// image, normalized cxcywh). Collects per-cell decoder hidden states using
604    /// docling's exact bbox bookkeeping (skip-after-row-break, first-lcel of a
605    /// horizontal span), runs the bbox decoder, merges span boxes, then lays the
606    /// cells onto the OTSL grid with row/col spans.
607    pub fn predict_table_structure(&mut self, img: &RgbImage) -> Result<Vec<TableCell>, String> {
608        let enc = self.encode(img)?;
609
610        // The autoregressive loop's bbox bookkeeping lives in tf_core::BboxBook
611        // (shared with the wasm path); this loop only steps the decoder.
612        let mut book = BboxBook::new();
613        let mut cache = DecodeCache::default();
614        let empty = self.empty_cache(1)?;
615        crate::timing::timed("tf.decode_loop", || -> Result<(), String> {
616            while book.otsl.len() < MAX_STEPS {
617                let (raw, hidden) = self.decode_step(&book.tags, &enc, &mut cache, &empty)?;
618                if !book.step(raw, &hidden) {
619                    break;
620                }
621            }
622            Ok(())
623        })?;
624        self.finish_table(book, &enc.eo)
625    }
626
627    /// The bbox stage after a table's decode loop: run the bbox decoder over
628    /// the collected per-cell hidden states, merge span boxes, lay the cells
629    /// onto the OTSL grid.
630    fn finish_table(
631        &mut self,
632        mut book: BboxBook,
633        eo: &DynValue,
634    ) -> Result<Vec<TableCell>, String> {
635        if book.n == 0 {
636            return Ok(Vec::new());
637        }
638        let tag_h = Tensor::from_array(([book.n, EMBED_DIM], std::mem::take(&mut book.hiddens)))
639            .map_err(|e| format!("tableformer: tag_h: {e}"))?;
640        let bout = crate::timing::timed("tf.bbox", || {
641            self.bbox
642                .run(ort::inputs!["enc_out" => eo, "tag_h" => tag_h])
643                .map_err(|e| format!("tableformer: bbox: {e}"))
644        })?;
645        let (_, raw) = bout["boxes"]
646            .try_extract_tensor::<f32>()
647            .map_err(|e| format!("tableformer: boxes: {e}"))?;
648        let boxes: Vec<[f32; 4]> = raw
649            .chunks_exact(4)
650            .map(|c| [c[0], c[1], c[2], c[3]])
651            .collect();
652        // Per-cell class logits [n, 3] → argmax (docling's `outputs_class`).
653        let (_, craw) = bout["classes"]
654            .try_extract_tensor::<f32>()
655            .map_err(|e| format!("tableformer: classes: {e}"))?;
656        let classes: Vec<i64> = craw.chunks_exact(3).map(|c| argmax(c) as i64).collect();
657        let (merged, merged_classes) = merge_spans(&boxes, &classes, &book.merge);
658        Ok(build_table_cells(&book.otsl, &merged, &merged_classes))
659    }
660
661    /// Predict a table region's Markdown grid: crop the region (docling's
662    /// page→1024px box-average then bbox crop), run the structure model, then
663    /// match the page's word cells into the predicted cells with docling's
664    /// matching post-processor ([`crate::tf_match`]) and expand spans into a
665    /// dense `rows × cols` grid. `region` is `(l, t, r, b)` in page points
666    /// (top-left). Returns `None` if no structure is predicted.
667    pub fn predict_table_rows(
668        &mut self,
669        page_image: &RgbImage,
670        region: [f32; 4],
671        words: &[TextCell],
672    ) -> Option<crate::tf_core::TableGrid> {
673        let page1024 = Self::page_1024(page_image);
674        self.predict_table_rows_on(page_image.height(), &page1024, region, words)
675    }
676
677    /// The page rendered at 1024 px height (cv2.INTER_AREA), the frame every
678    /// table crop of that page is cut from. Computed once per page by the
679    /// pipeline and shared across its tables — the resample is a full-page
680    /// f64 box filter, 110–170 ms on the corpus pages, and it used to run
681    /// again for every table on the page.
682    pub fn page_1024(page_image: &RgbImage) -> RgbImage {
683        let sf = 1024.0 / page_image.height() as f32;
684        let pw = (page_image.width() as f32 * sf) as u32;
685        crate::timing::timed("tableformer.inter_area", || {
686            crate::resample::inter_area(page_image, pw, 1024)
687        })
688    }
689
690    /// [`predict_table_rows`](Self::predict_table_rows) with the page's
691    /// 1024-px frame already built ([`page_1024`](Self::page_1024));
692    /// `page_h` is the source page image's pixel height.
693    pub fn predict_table_rows_on(
694        &mut self,
695        page_h: u32,
696        page1024: &RgbImage,
697        region: [f32; 4],
698        words: &[TextCell],
699    ) -> Option<crate::tf_core::TableGrid> {
700        let crop = Self::crop_region(page_h, page1024, region)?;
701        let cells = crate::timing::timed("tableformer.structure", || {
702            self.predict_table_structure(&crop)
703        })
704        .ok()?;
705        if cells.is_empty() {
706            return None;
707        }
708        // The ort-free tail (word matching + grid assembly) is shared with the
709        // browser path in tf_core.
710        crate::tf_core::table_rows(&cells, region, words)
711    }
712
713    /// Every table of a page at once: [`predict_table_rows_on`](Self::predict_table_rows_on)
714    /// per region, except that with the dynamic-batch decoder the tables'
715    /// decode steps are shared — each table is encoded on its own, then one
716    /// decode loop steps all of them together ([`Self::decode_batch`]), then
717    /// each runs its own bbox head. Per table the result is bit-identical to
718    /// the one-at-a-time path; a page with a single table takes exactly that
719    /// path. Should the batched run fail (an ort error), the tables are
720    /// retried one by one so a page never loses all of its tables to one
721    /// shared step.
722    pub fn predict_tables_on(
723        &mut self,
724        page_h: u32,
725        page1024: &RgbImage,
726        regions: &[[f32; 4]],
727        words: &[TextCell],
728    ) -> Vec<Option<crate::tf_core::TableGrid>> {
729        let mut out: Vec<Option<crate::tf_core::TableGrid>> = vec![None; regions.len()];
730        let crops: Vec<(usize, RgbImage)> = regions
731            .iter()
732            .enumerate()
733            .filter_map(|(i, r)| Self::crop_region(page_h, page1024, *r).map(|c| (i, c)))
734            .collect();
735        if self.batched && crops.len() > 1 {
736            let batched = crate::timing::timed("tableformer.structure", || {
737                self.predict_structures_batched(crops.iter().map(|(_, c)| c))
738            });
739            match batched {
740                Ok(cells) => {
741                    for ((i, _), cells) in crops.iter().zip(cells) {
742                        if !cells.is_empty() {
743                            out[*i] = crate::tf_core::table_rows(&cells, regions[*i], words);
744                        }
745                    }
746                    return out;
747                }
748                Err(e) => docling_core::debug_log!(
749                    "docling-pdf: tableformer batched decode failed ({e}); decoding tables one by one"
750                ),
751            }
752        }
753        for (i, crop) in &crops {
754            let cells = crate::timing::timed("tableformer.structure", || {
755                self.predict_table_structure(crop)
756            });
757            if let Ok(cells) = cells {
758                if !cells.is_empty() {
759                    out[*i] = crate::tf_core::table_rows(&cells, regions[*i], words);
760                }
761            }
762        }
763        out
764    }
765
766    /// [`predict_table_structure`](Self::predict_table_structure) for several
767    /// crops with the decode steps shared across them.
768    fn predict_structures_batched<'a>(
769        &mut self,
770        crops: impl Iterator<Item = &'a RgbImage>,
771    ) -> Result<Vec<Vec<TableCell>>, String> {
772        let mut encs = Vec::new();
773        for crop in crops {
774            encs.push(self.encode(crop)?);
775        }
776        let books = self.decode_batch(&encs)?;
777        books
778            .into_iter()
779            .zip(&encs)
780            .map(|(book, enc)| self.finish_table(book, &enc.eo))
781            .collect()
782    }
783
784    /// Crop the table bbox out of the 1024px frame. docling's coordinate
785    /// chain, rounding included: the cluster bbox is rounded to integer page
786    /// points *first* (`round(cluster.bbox.l) * scale`, banker's rounding),
787    /// scaled by 2 (its table-structure page scale), then by `1024 / <2x
788    /// page-image height>`, and the crop indices round again. Rounding after
789    /// scaling instead shifts some crops by a pixel — enough to change
790    /// TableFormer's cell boxes on tall tables (redp5110's TOC). `None` for a
791    /// region that collapses to an empty crop.
792    fn crop_region(page_h: u32, page1024: &RgbImage, region: [f32; 4]) -> Option<RgbImage> {
793        let k = 2.0 * 1024.0 / page_h as f64;
794        let px = |v: f32| (v as f64).round_ties_even() * k;
795        let x = (px(region[0]).round_ties_even()).max(0.0) as u32;
796        let y = (px(region[1]).round_ties_even()).max(0.0) as u32;
797        let x2 = (px(region[2]).round_ties_even() as u32).min(page1024.width());
798        let y2 = (px(region[3]).round_ties_even() as u32).min(page1024.height());
799        if x2 <= x || y2 <= y {
800            return None;
801        }
802        Some(image::imageops::crop_imm(page1024, x, y, x2 - x, y2 - y).to_image())
803    }
804}
805
806/// Note once per process that TableFormer's ONNX graphs weren't found, so tables
807/// fall back to geometric reconstruction. The default paths are relative
808/// (`.models/tableformer/*.onnx`), which only resolves when the process's current
809/// directory happens to be the repo root — a very easy miss for anything else
810/// (an embedding app, a binding invoked from a different working directory, …),
811/// and previously failed with no signal at all.
812fn warn_missing_once(enc: &str, dec: &str, bbx: &str) {
813    static WARNED: std::sync::Once = std::sync::Once::new();
814    WARNED.call_once(|| {
815        eprintln!(
816            "docling.rs: TableFormer models not found (checked {enc}, {dec}, {bbx}); \
817             tables will use geometric reconstruction instead of ML table-structure \
818             recognition. Set DOCLING_TABLEFORMER_ENCODER / DOCLING_TABLEFORMER_DECODER \
819             / DOCLING_TABLEFORMER_BBOX to enable it (see README.md)."
820        );
821    });
822}
823
824/// docling's preprocessing: bilinear (cv2.INTER_LINEAR) resize the crop to 448²,
825/// normalize `(x/255 − mean)/std`, laid out as (C, W, H) — docling transposes
826/// (2,1,0), so width is the major spatial axis. The page→1024px box-average
827/// (cv2.INTER_AREA) is the caller's job.
828fn preprocess(img: &RgbImage) -> Result<Tensor<f32>, String> {
829    Tensor::from_array(([1usize, 3, SIDE, SIDE], preprocess_input(img)))
830        .map_err(|e| format!("tableformer: input: {e}"))
831}