Skip to main content

fleischwolf_pdf/
tableformer.rs

1//! TableFormer: table-structure recovery via docling-ibm-models, exported to
2//! ONNX by `scripts/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 PDF_CONFORMANCE.md.
6
7use crate::pdfium_backend::TextCell;
8use image::RgbImage;
9use ort::session::Session;
10use ort::value::{Tensor, TensorRef};
11
12const SIDE: u32 = 448;
13// Verbatim from docling's tm_config.json image_normalization (more digits than
14// f32 holds; kept exact for provenance).
15#[allow(clippy::excessive_precision)]
16const MEAN: [f32; 3] = [0.94247851, 0.94254675, 0.94292611];
17#[allow(clippy::excessive_precision)]
18const STD: [f32; 3] = [0.17910956, 0.17940403, 0.17931663];
19const MAX_STEPS: usize = 1024;
20/// Decoder geometry, fixed by the exported TableModel04_rs graph: the cached
21/// decoder threads a `[N_LAYERS, past, 1, EMBED_DIM]` per-layer state cache.
22const N_LAYERS: usize = 6;
23const EMBED_DIM: usize = 512;
24
25/// OTSL structure tokens (TableModel04_rs wordmap indices).
26pub const START: i64 = 2;
27pub const END: i64 = 3;
28pub const ECEL: i64 = 4; // empty cell
29pub const FCEL: i64 = 5; // full (content) cell
30pub const LCEL: i64 = 6; // left-looking: extends the cell to its left (colspan)
31pub const UCEL: i64 = 7; // up-looking: extends the cell above (rowspan)
32pub const XCEL: i64 = 8; // cross: spans both ways
33pub const NL: i64 = 9; // new row
34pub const CHED: i64 = 10; // column header
35pub const RHED: i64 = 11; // row header
36pub const SROW: i64 = 12; // section row
37
38/// A predicted table cell: an OTSL grid position (with spans) + its box in the
39/// 448 image normalized cxcywh, and the OTSL tag.
40#[derive(Debug, Clone)]
41pub struct TableCell {
42    pub row: usize,
43    pub col: usize,
44    pub colspan: usize,
45    pub rowspan: usize,
46    pub tag: i64,
47    pub cx: f32,
48    pub cy: f32,
49    pub w: f32,
50    pub h: f32,
51}
52
53pub struct TableFormer {
54    encoder: Session,
55    decoder: Session,
56    bbox: Session,
57}
58
59/// Encoder outputs that drive the cached decode loop: the per-layer cross-attention
60/// K/V (projected from the image memory once, constant across decode steps) and
61/// `enc_out` for the bbox decoder. Each is a `(shape, flattened data)` pair.
62struct EncodeOut {
63    ck_shape: Vec<usize>,
64    ck: Vec<f32>,
65    cv_shape: Vec<usize>,
66    cv: Vec<f32>,
67    eo_shape: Vec<usize>,
68    eo: Vec<f32>,
69}
70
71impl TableFormer {
72    /// Load the exported encoder/decoder/bbox ONNX graphs (env overrides, else
73    /// `models/tableformer/{encoder,decoder,bbox}.onnx`). Returns `None` if any is
74    /// absent, so the pipeline falls back to geometric reconstruction.
75    pub fn load() -> Option<Self> {
76        Self::load_with(crate::intra_threads())
77    }
78
79    /// Like [`load`](Self::load) but with an explicit intra-op thread count, so a
80    /// parallel page-worker pool can run each table model on fewer threads (the
81    /// throughput comes from running pages concurrently, not from one fat model).
82    pub fn load_with(intra: usize) -> Option<Self> {
83        let enc = std::env::var("DOCLING_TABLEFORMER_ENCODER")
84            .unwrap_or_else(|_| "models/tableformer/encoder.onnx".to_string());
85        let dec = std::env::var("DOCLING_TABLEFORMER_DECODER")
86            .unwrap_or_else(|_| "models/tableformer/decoder.onnx".to_string());
87        let bbx = std::env::var("DOCLING_TABLEFORMER_BBOX")
88            .unwrap_or_else(|_| "models/tableformer/bbox.onnx".to_string());
89        if [&enc, &dec, &bbx]
90            .iter()
91            .any(|p| !std::path::Path::new(p).exists())
92        {
93            return None;
94        }
95        let build = |path: &str| -> Result<Session, String> {
96            Session::builder()
97                .map_err(|e| e.to_string())?
98                .with_intra_threads(intra)
99                .map_err(|e| e.to_string())?
100                .commit_from_file(path)
101                .map_err(|e| format!("tableformer load {path}: {e}"))
102        };
103        match (build(&enc), build(&dec), build(&bbx)) {
104            (Ok(encoder), Ok(decoder), Ok(bbox)) => Some(Self {
105                encoder,
106                decoder,
107                bbox,
108            }),
109            _ => None,
110        }
111    }
112
113    /// Run the image encoder and capture what the cached decoder loop needs: each
114    /// decoder layer's cross-attention K/V (projected from the image memory once,
115    /// shape `[N_LAYERS,1,H,S,head_dim]`) and `enc_out` for the bbox decoder.
116    fn encode(&mut self, img: &RgbImage) -> Result<EncodeOut, String> {
117        let input = preprocess(img)?;
118        let enc_out = self
119            .encoder
120            .run(ort::inputs!["image" => input])
121            .map_err(|e| format!("tableformer: encode: {e}"))?;
122        let grab = |name: &str| -> Result<(Vec<usize>, Vec<f32>), String> {
123            let (sh, data) = enc_out[name]
124                .try_extract_tensor::<f32>()
125                .map_err(|e| format!("tableformer: {name}: {e}"))?;
126            Ok((sh.iter().map(|&x| x as usize).collect(), data.to_vec()))
127        };
128        let (ck_shape, ck) = grab("cross_k")?;
129        let (cv_shape, cv) = grab("cross_v")?;
130        let (eo_shape, eo) = grab("enc_out")?;
131        Ok(EncodeOut {
132            ck_shape,
133            ck,
134            cv_shape,
135            cv,
136            eo_shape,
137            eo,
138        })
139    }
140
141    /// One doubly-cached decode step: feed the current `tags`, the constant cross
142    /// K/V views, and the growing self-attention `cache`; return the raw argmax tag
143    /// and the last token's hidden state, advancing the cache. `empty_cache` is the
144    /// zero-`past` value used on the first step (ort's array constructors reject a
145    /// 0-length dim, so it is allocated through the session allocator by the caller).
146    fn decode_step(
147        &mut self,
148        tags: &[i64],
149        enc: &EncodeOut,
150        cache: &mut Vec<f32>,
151        cache_past: &mut usize,
152        empty_cache: &Tensor<f32>,
153    ) -> Result<(i64, Vec<f32>), String> {
154        let tags_t = Tensor::from_array(([tags.len(), 1usize], tags.to_vec()))
155            .map_err(|e| format!("tableformer: tags: {e}"))?;
156        // Constant per-table cross-attention K/V — zero-copy views each step.
157        let ck_t = TensorRef::from_array_view((enc.ck_shape.as_slice(), enc.ck.as_slice()))
158            .map_err(|e| format!("tableformer: cross_k: {e}"))?;
159        let cv_t = TensorRef::from_array_view((enc.cv_shape.as_slice(), enc.cv.as_slice()))
160            .map_err(|e| format!("tableformer: cross_v: {e}"))?;
161        let dout = if *cache_past == 0 {
162            self.decoder.run(ort::inputs![
163                "tags" => tags_t, "cross_k" => ck_t, "cross_v" => cv_t, "cache" => empty_cache])
164        } else {
165            let cache_t = TensorRef::from_array_view((
166                [N_LAYERS, *cache_past, 1, EMBED_DIM],
167                cache.as_slice(),
168            ))
169            .map_err(|e| format!("tableformer: cache: {e}"))?;
170            self.decoder.run(ort::inputs![
171                "tags" => tags_t, "cross_k" => ck_t, "cross_v" => cv_t, "cache" => cache_t])
172        }
173        .map_err(|e| format!("tableformer: decode: {e}"))?;
174        let (_, logits) = dout["logits"]
175            .try_extract_tensor::<f32>()
176            .map_err(|e| format!("tableformer: logits: {e}"))?;
177        let raw = argmax(logits) as i64;
178        let (oshape, ocache) = dout["out_cache"]
179            .try_extract_tensor::<f32>()
180            .map_err(|e| format!("tableformer: out_cache: {e}"))?;
181        let next_cache = ocache.to_vec();
182        let next_past = oshape[1] as usize;
183        let (_, hidden) = dout["hidden"]
184            .try_extract_tensor::<f32>()
185            .map_err(|e| format!("tableformer: hidden: {e}"))?;
186        let hidden = hidden.to_vec();
187        *cache = next_cache;
188        *cache_past = next_past;
189        Ok((raw, hidden))
190    }
191
192    /// The zero-`past` first-step cache, allocated through the session allocator
193    /// (ort's array constructors reject a 0-length dim; the C API does allow it).
194    fn empty_cache(&self) -> Result<Tensor<f32>, String> {
195        Tensor::<f32>::new(self.decoder.allocator(), [N_LAYERS, 0usize, 1, EMBED_DIM])
196            .map_err(|e| format!("tableformer: empty cache: {e}"))
197    }
198
199    /// Predict the OTSL structure-token sequence for a table-region image.
200    pub fn predict_otsl(&mut self, img: &RgbImage) -> Result<Vec<i64>, String> {
201        let enc = self.encode(img)?;
202        // The two structure corrections mirror docling's `predict` exactly — note
203        // its `line_num` is never incremented, so `xcel→lcel` applies on every row.
204        let mut tags: Vec<i64> = vec![START];
205        let mut out: Vec<i64> = Vec::new();
206        let mut prev_ucel = false;
207        let mut cache: Vec<f32> = Vec::new();
208        let mut cache_past = 0usize;
209        let empty = self.empty_cache()?;
210        while out.len() < MAX_STEPS {
211            let (raw, _hidden) =
212                self.decode_step(&tags, &enc, &mut cache, &mut cache_past, &empty)?;
213            let mut tag = raw;
214            if tag == XCEL {
215                tag = LCEL;
216            }
217            if prev_ucel && tag == LCEL {
218                tag = FCEL;
219            }
220            if tag == END {
221                break;
222            }
223            out.push(tag);
224            tags.push(tag);
225            prev_ucel = tag == UCEL;
226        }
227        Ok(out)
228    }
229
230    /// Full structure prediction: OTSL grid cells with per-cell boxes (in the 448
231    /// image, normalized cxcywh). Collects per-cell decoder hidden states using
232    /// docling's exact bbox bookkeeping (skip-after-row-break, first-lcel of a
233    /// horizontal span), runs the bbox decoder, merges span boxes, then lays the
234    /// cells onto the OTSL grid with row/col spans.
235    pub fn predict_table_structure(&mut self, img: &RgbImage) -> Result<Vec<TableCell>, String> {
236        let enc = self.encode(img)?;
237
238        let mut tags: Vec<i64> = vec![START];
239        let mut otsl: Vec<i64> = Vec::new();
240        let mut hiddens: Vec<f32> = Vec::new(); // flattened [n, 512]
241        let mut n = 0usize;
242        let mut prev_ucel = false;
243        let mut skip = true; // first tag after <start> is skipped
244        let mut first_lcel = true;
245        let mut bbox_ind = 0usize;
246        let mut cur_bbox_ind = 0usize;
247        let mut merge: std::collections::HashMap<usize, i64> = std::collections::HashMap::new();
248        let mut cache: Vec<f32> = Vec::new();
249        let mut cache_past = 0usize;
250        let empty = self.empty_cache()?;
251        while otsl.len() < MAX_STEPS {
252            let (raw, hidden) =
253                self.decode_step(&tags, &enc, &mut cache, &mut cache_past, &empty)?;
254            let mut tag = raw;
255            if tag == XCEL {
256                tag = LCEL;
257            }
258            if prev_ucel && tag == LCEL {
259                tag = FCEL;
260            }
261            if tag == END {
262                break;
263            }
264            // docling's tag_H_buf / bboxes_to_merge bookkeeping.
265            if !skip && matches!(tag, FCEL | ECEL | CHED | RHED | SROW | NL | UCEL) {
266                hiddens.extend_from_slice(&hidden);
267                n += 1;
268                if !first_lcel {
269                    merge.insert(cur_bbox_ind, bbox_ind as i64);
270                }
271                bbox_ind += 1;
272            }
273            if tag != LCEL {
274                first_lcel = true;
275            } else if first_lcel {
276                hiddens.extend_from_slice(&hidden);
277                n += 1;
278                first_lcel = false;
279                cur_bbox_ind = bbox_ind;
280                merge.insert(cur_bbox_ind, -1);
281                bbox_ind += 1;
282            }
283            skip = matches!(tag, NL | UCEL | XCEL);
284            prev_ucel = tag == UCEL;
285            otsl.push(tag);
286            tags.push(tag);
287        }
288        if n == 0 {
289            return Ok(Vec::new());
290        }
291        let tag_h = Tensor::from_array(([n, 512usize], hiddens))
292            .map_err(|e| format!("tableformer: tag_h: {e}"))?;
293        let eo_t = Tensor::from_array((enc.eo_shape.clone(), enc.eo.clone()))
294            .map_err(|e| format!("tableformer: eo: {e}"))?;
295        let bout = self
296            .bbox
297            .run(ort::inputs!["enc_out" => eo_t, "tag_h" => tag_h])
298            .map_err(|e| format!("tableformer: bbox: {e}"))?;
299        let (_, raw) = bout["boxes"]
300            .try_extract_tensor::<f32>()
301            .map_err(|e| format!("tableformer: boxes: {e}"))?;
302        let boxes: Vec<[f32; 4]> = raw
303            .chunks_exact(4)
304            .map(|c| [c[0], c[1], c[2], c[3]])
305            .collect();
306        let merged = merge_spans(&boxes, &merge);
307        Ok(build_table_cells(&otsl, &merged))
308    }
309
310    /// Predict a table region's Markdown grid: crop the region (docling's
311    /// page→1024px box-average then bbox crop), run the structure model, map each
312    /// cell box back to page points, match the page's word cells into cells by
313    /// intersection-over-word-area, and expand spans into a dense `rows × cols`
314    /// grid. `region` is `(l, t, r, b)` in page points (top-left). Returns `None`
315    /// if no structure is predicted.
316    pub fn predict_table_rows(
317        &mut self,
318        page_image: &RgbImage,
319        page_h: f32,
320        region: [f32; 4],
321        words: &[TextCell],
322    ) -> Option<Vec<Vec<String>>> {
323        // page → 1024px height (cv2.INTER_AREA), then crop the table bbox.
324        let sf = 1024.0 / page_image.height() as f32;
325        let pw = (page_image.width() as f32 * sf) as u32;
326        let page1024 = crate::resample::inter_area(page_image, pw, 1024);
327        let k = 1024.0 / page_h;
328        let x = (region[0] * k).round().max(0.0) as u32;
329        let y = (region[1] * k).round().max(0.0) as u32;
330        let x2 = ((region[2] * k).round() as u32).min(page1024.width());
331        let y2 = ((region[3] * k).round() as u32).min(page1024.height());
332        if x2 <= x || y2 <= y {
333            return None;
334        }
335        let crop = image::imageops::crop_imm(&page1024, x, y, x2 - x, y2 - y).to_image();
336        let cells = self.predict_table_structure(&crop).ok()?;
337        if cells.is_empty() {
338            return None;
339        }
340        let (rw, rh) = (region[2] - region[0], region[3] - region[1]);
341
342        // Cell boxes in page points (top-left), aligned with `cells`.
343        let boxes: Vec<[f32; 4]> = cells
344            .iter()
345            .map(|c| {
346                [
347                    region[0] + (c.cx - c.w / 2.0) * rw,
348                    region[1] + (c.cy - c.h / 2.0) * rh,
349                    region[0] + (c.cx + c.w / 2.0) * rw,
350                    region[1] + (c.cy + c.h / 2.0) * rh,
351                ]
352            })
353            .collect();
354
355        // Assign each word to the cell it overlaps most (intersection / word area).
356        let mut cell_words: Vec<Vec<usize>> = vec![Vec::new(); cells.len()];
357        for (wi, w) in words.iter().enumerate() {
358            let wa = ((w.r - w.l) * (w.b - w.t)).max(1.0);
359            let mut best: Option<(f32, usize)> = None;
360            for (ci, b) in boxes.iter().enumerate() {
361                let ix = (w.r.min(b[2]) - w.l.max(b[0])).max(0.0);
362                let iy = (w.b.min(b[3]) - w.t.max(b[1])).max(0.0);
363                let io = ix * iy / wa;
364                if io > 0.0 && best.is_none_or(|(bo, _)| io > bo) {
365                    best = Some((io, ci));
366                }
367            }
368            if let Some((_, ci)) = best {
369                cell_words[ci].push(wi);
370            }
371        }
372
373        let num_rows = cells.iter().map(|c| c.row + c.rowspan).max().unwrap_or(0);
374        let num_cols = cells.iter().map(|c| c.col + c.colspan).max().unwrap_or(0);
375        if num_rows == 0 || num_cols == 0 {
376            return None;
377        }
378        let mut grid = vec![vec![String::new(); num_cols]; num_rows];
379        for (ci, c) in cells.iter().enumerate() {
380            // Keep words in text-stream order (the order they were collected =
381            // their word index), matching docling's cell text assembly — geometric
382            // re-sorting scrambles wrapped cells (`Inference time (secs)`).
383            let wis = std::mem::take(&mut cell_words[ci]);
384            let text = wis
385                .iter()
386                .map(|&i| words[i].text.trim())
387                .collect::<Vec<_>>()
388                .join(" ");
389            // Spanned cells repeat their text across the covered grid positions.
390            for row in grid.iter_mut().skip(c.row).take(c.rowspan) {
391                for cell in row.iter_mut().skip(c.col).take(c.colspan) {
392                    *cell = text.clone();
393                }
394            }
395        }
396        Some(grid)
397    }
398}
399
400/// docling's preprocessing: bilinear (cv2.INTER_LINEAR) resize the crop to 448²,
401/// normalize `(x/255 − mean)/std`, laid out as (C, W, H) — docling transposes
402/// (2,1,0), so width is the major spatial axis. The page→1024px box-average
403/// (cv2.INTER_AREA) is the caller's job.
404fn preprocess(img: &RgbImage) -> Result<Tensor<f32>, String> {
405    let nn = (SIDE * SIDE) as usize;
406    let side = SIDE as usize;
407    let (sw, sh) = (img.width() as i32, img.height() as i32);
408    let sxr = sw as f32 / SIDE as f32;
409    let syr = sh as f32 / SIDE as f32;
410    let mut data = vec![0f32; 3 * nn];
411    for h in 0..side {
412        let fy = (h as f32 + 0.5) * syr - 0.5;
413        let wy = fy - fy.floor();
414        let y0c = (fy.floor() as i32).clamp(0, sh - 1) as u32;
415        let y1c = (fy.floor() as i32 + 1).clamp(0, sh - 1) as u32;
416        for w in 0..side {
417            let fx = (w as f32 + 0.5) * sxr - 0.5;
418            let wx = fx - fx.floor();
419            let x0c = (fx.floor() as i32).clamp(0, sw - 1) as u32;
420            let x1c = (fx.floor() as i32 + 1).clamp(0, sw - 1) as u32;
421            let p00 = img.get_pixel(x0c, y0c);
422            let p01 = img.get_pixel(x1c, y0c);
423            let p10 = img.get_pixel(x0c, y1c);
424            let p11 = img.get_pixel(x1c, y1c);
425            let idx = w * side + h; // (C, W, H): c*n + w*H + h
426            for c in 0..3 {
427                let top = p00[c] as f32 * (1.0 - wx) + p01[c] as f32 * wx;
428                let bot = p10[c] as f32 * (1.0 - wx) + p11[c] as f32 * wx;
429                let v = top * (1.0 - wy) + bot * wy;
430                data[c * nn + idx] = (v / 255.0 - MEAN[c]) / STD[c];
431            }
432        }
433    }
434    Tensor::from_array(([1usize, 3, side, side], data))
435        .map_err(|e| format!("tableformer: input: {e}"))
436}
437
438/// docling's `mergebboxes` (cxcywh): the union box of a horizontal span's first
439/// and last cell.
440fn mergebboxes(b1: [f32; 4], b2: [f32; 4]) -> [f32; 4] {
441    let new_w = (b2[0] + b2[2] / 2.0) - (b1[0] - b1[2] / 2.0);
442    let new_h = (b2[1] + b2[3] / 2.0) - (b1[1] - b1[3] / 2.0);
443    let new_left = b1[0] - b1[2] / 2.0;
444    let new_top = (b2[1] - b2[3] / 2.0).min(b1[1] - b1[3] / 2.0);
445    [new_left + new_w / 2.0, new_top + new_h / 2.0, new_w, new_h]
446}
447
448/// Apply docling's span merges: each merge key combines its box with the partner
449/// (`-1` → the last box); partners are dropped.
450fn merge_spans(boxes: &[[f32; 4]], merge: &std::collections::HashMap<usize, i64>) -> Vec<[f32; 4]> {
451    let skip: std::collections::HashSet<usize> = merge
452        .values()
453        .filter(|&&v| v >= 0)
454        .map(|&v| v as usize)
455        .collect();
456    let mut out = Vec::new();
457    for (i, &b) in boxes.iter().enumerate() {
458        if let Some(&j) = merge.get(&i) {
459            let partner = if j < 0 { boxes.len() - 1 } else { j as usize };
460            out.push(mergebboxes(b, boxes[partner.min(boxes.len() - 1)]));
461        } else if !skip.contains(&i) {
462            out.push(b);
463        }
464    }
465    out
466}
467
468const CELL_TAGS: [i64; 6] = [FCEL, ECEL, XCEL, CHED, RHED, SROW];
469
470/// Lay the OTSL tag stream onto a grid (docling's `_build_table_cells`, OTSL
471/// mode): cell tags create cells at (row, col); `lcel`/`ucel`/`xcel` are spans
472/// (counted toward the column index but not cells). Colspan/rowspan are read off
473/// the grid (consecutive `lcel`/`ucel` to the right/below). `boxes` are indexed
474/// by cell order and aligned with the cells.
475fn build_table_cells(otsl: &[i64], boxes: &[[f32; 4]]) -> Vec<TableCell> {
476    // 2D grid of tags (rows split on NL) for span lookups.
477    let mut grid: Vec<Vec<i64>> = vec![Vec::new()];
478    for &t in otsl {
479        if t == NL {
480            grid.push(Vec::new());
481        } else {
482            grid.last_mut().unwrap().push(t);
483        }
484    }
485    let mut cells = Vec::new();
486    let mut cell_id = 0usize;
487    for (r, row) in grid.iter().enumerate() {
488        for (c, &tag) in row.iter().enumerate() {
489            if !CELL_TAGS.contains(&tag) {
490                continue;
491            }
492            let mut colspan = 1;
493            while c + colspan < row.len() && matches!(row[c + colspan], LCEL | XCEL) {
494                colspan += 1;
495            }
496            let mut rowspan = 1;
497            while r + rowspan < grid.len()
498                && grid[r + rowspan]
499                    .get(c)
500                    .is_some_and(|&t| matches!(t, UCEL | XCEL))
501            {
502                rowspan += 1;
503            }
504            let b = boxes.get(cell_id).copied().unwrap_or([0.0; 4]);
505            cells.push(TableCell {
506                row: r,
507                col: c,
508                colspan,
509                rowspan,
510                tag,
511                cx: b[0],
512                cy: b[1],
513                w: b[2],
514                h: b[3],
515            });
516            cell_id += 1;
517        }
518    }
519    cells
520}
521
522fn argmax(v: &[f32]) -> usize {
523    v.iter()
524        .enumerate()
525        .max_by(|a, b| a.1.total_cmp(b.1))
526        .map(|(i, _)| i)
527        .unwrap_or(0)
528}