Skip to main content

docling_pdf/
layout.rs

1//! Layout detection via the RT-DETR (`docling-layout-heron`) model exported to
2//! ONNX, run with `ort`. A port of docling-ibm-models' `LayoutPredictor`:
3//! resize the page image to 640×640 and rescale to `[0,1]` (the heron processor
4//! has `do_normalize=false`), run the model, then RT-DETR
5//! `post_process_object_detection` (sigmoid → top-k over query×class →
6//! center-to-corners boxes scaled to the page).
7
8#[cfg(feature = "ml")]
9use image::imageops::FilterType;
10#[cfg(feature = "ml")]
11use ort::session::Session;
12#[cfg(feature = "ml")]
13use ort::value::Tensor;
14
15/// The 17 canonical layout classes, indexed by the model's class id
16/// (`config.json` `id2label`).
17pub const LABELS: [&str; 17] = [
18    "caption",
19    "footnote",
20    "formula",
21    "list_item",
22    "page_footer",
23    "page_header",
24    "picture",
25    "section_header",
26    "table",
27    "text",
28    "title",
29    "document_index",
30    "code",
31    "checkbox_selected",
32    "checkbox_unselected",
33    "form",
34    "key_value_region",
35];
36
37/// One detected region, in page points (top-left origin).
38#[derive(Debug, Clone)]
39pub struct Region {
40    pub label: &'static str,
41    pub score: f32,
42    pub l: f32,
43    pub t: f32,
44    pub r: f32,
45    pub b: f32,
46}
47
48/// What a layout inference call receives per page — which resize kernel packs
49/// the 640×640 model input depends on it (docling parity, #58-branch):
50///
51/// docling's layout stage runs on `page.get_image(scale=1.0)` — the
52/// point-sized page image (pdfium at 1.5×, PIL-BICUBIC down) — which its
53/// RT-DETR processor then stretches to 640×640 with **PIL BILINEAR**
54/// (`preprocessor_config.json`: `do_pad: false`, `resample: 2`; no letterbox,
55/// no normalize beyond `/255`). [`PageImage`](LayoutSrc::PageImage) is that
56/// image and goes through the byte-exact PIL kernel. [`Raw`](LayoutSrc::Raw)
57/// is any other bitmap (the browser path's canvas render, METS/TIFF page
58/// scans) and keeps the legacy Triangle stretch.
59#[cfg(feature = "ocr-prep")]
60#[derive(Clone, Copy)]
61pub enum LayoutSrc<'a> {
62    /// The scale-1.0 page image (`PdfPage::image_layout`), docling-exact.
63    PageImage(&'a image::RgbImage),
64    /// Any other page bitmap — legacy stretch.
65    Raw(&'a image::RgbImage),
66}
67
68/// Base confidence threshold (docling-ibm-models `base_threshold`): the raw
69/// RT-DETR floor before docling's `LayoutPostprocessor` applies its stricter
70/// per-label thresholds ([`label_threshold`]).
71const THRESHOLD: f32 = 0.3;
72/// RT-DETR's fixed square input side.
73pub const SIDE: u32 = 640;
74
75/// Per-label confidence threshold, ported from docling's
76/// `LayoutPostprocessor.CONFIDENCE_THRESHOLDS`. The raw predictor keeps every
77/// detection above the 0.3 base; the postprocessor then drops a cluster whose
78/// score is below its label's threshold. Applying it here (equivalent, since
79/// every per-label threshold is ≥ the 0.3 base) keeps low-confidence pictures /
80/// tables / list-items out of the assembly, matching docling.
81pub fn label_threshold(label: &str) -> f32 {
82    match label {
83        "section_header"
84        | "title"
85        | "code"
86        | "checkbox_selected"
87        | "checkbox_unselected"
88        | "form"
89        | "key_value_region"
90        | "document_index" => 0.45,
91        // caption, footnote, formula, list_item, page_footer, page_header,
92        // picture, table, text — all 0.5 in docling.
93        _ => 0.5,
94    }
95}
96
97#[cfg(feature = "ml")]
98pub struct LayoutModel {
99    session: Session,
100    /// Set when a multi-page inference fails — e.g. a locally built pre-#73
101    /// static graph (fixed batch=1) via `DOCLING_LAYOUT_ONNX` or a stale
102    /// `layout_heron_int8.onnx`. Batched calls then fall back to per-page runs
103    /// instead of failing the conversion.
104    batch_unsupported: bool,
105    /// The fp32 graph to escalate a suspicious page to, set only when the
106    /// *auto-selected* int8 graph loaded (an explicit `DOCLING_LAYOUT_ONNX` /
107    /// `DOCLING_RS_FP32` choice is respected). Int8 confidences sit close
108    /// enough to the 0.5 label thresholds that a different CPU's quantized
109    /// kernels (AVX-VNNI vs AVX2, CUDA's fallback mix) can flip a whole page's
110    /// detections — observed as a bill page whose tables all dissolved into
111    /// orphan lines on one machine while converting perfectly on another.
112    fp32_path: Option<String>,
113    /// Lazily-loaded session over `fp32_path` — most documents never pay for it.
114    fp32: Option<Session>,
115    /// Intra-op threads, kept for the lazy fp32 load.
116    intra: usize,
117}
118
119#[cfg(feature = "ml")]
120impl LayoutModel {
121    /// Load the ONNX model from `DOCLING_LAYOUT_ONNX`. Without the override,
122    /// prefers `.models/layout_heron_int8.onnx` when present (the quantized
123    /// default; `DOCLING_RS_FP32=1` opts out), else `.models/layout_heron.onnx`.
124    pub fn load() -> Result<Self, String> {
125        Self::load_with(crate::intra_threads())
126    }
127
128    /// Like [`load`](Self::load) but with an explicit intra-op thread count. A
129    /// parallel page-worker pool loads its helper models on a single thread each
130    /// and gets its speed-up from running pages concurrently instead.
131    pub fn load_with(intra: usize) -> Result<Self, String> {
132        let path = crate::model_path(
133            "DOCLING_LAYOUT_ONNX",
134            ".models/layout_heron.onnx",
135            ".models/layout_heron_int8.onnx",
136        );
137        if crate::timing::enabled() {
138            eprintln!("docling-pdf: layout model: {path}");
139        }
140        // Escalation target for the quant-robustness guard: only when the
141        // int8 graph was picked automatically and the fp32 one is also there.
142        let fp32_path = if docling_core::env::nonempty("DOCLING_LAYOUT_ONNX").is_none() {
143            let fp32 = crate::resolve_asset(".models/layout_heron.onnx");
144            (path != fp32 && std::path::Path::new(&fp32).exists()).then_some(fp32)
145        } else {
146            None
147        };
148        let session = Self::open_session(&path, intra)?;
149        Ok(Self {
150            session,
151            batch_unsupported: false,
152            fp32_path,
153            fp32: None,
154            intra,
155        })
156    }
157
158    fn open_session(path: &str, intra: usize) -> Result<Session, String> {
159        // The layout model is the pipeline's first hard model dependency; a
160        // missing file here almost always means the models were never
161        // downloaded (`cargo install` ships none) — say what to do.
162        if !std::path::Path::new(path).exists() {
163            return Err(format!(
164                "layout: model not found at {path} — PDF/image conversion needs \
165                 the ONNX models: fetch them with \
166                 scripts/install/download_dependencies.sh from a docling.rs \
167                 checkout (https://github.com/docling-project/docling.rs), or \
168                 set DOCLING_LAYOUT_ONNX. A digital PDF's embedded text layer \
169                 converts without models in no-OCR mode (CLI: --no-ocr)"
170            ));
171        }
172        let mut builder = Session::builder()
173            .map_err(|e| format!("layout: builder: {e}"))?
174            // Let inference use the available cores (ort otherwise defaults low);
175            // a large PDF runs this model once per page.
176            .with_intra_threads(intra)
177            .map_err(|e| format!("layout: intra_threads: {e}"))?;
178        // Per-page mode pins the model's dynamic `batch` axis to 1 (#339):
179        // the free dimension blocks ONNX Runtime's channels-last conv
180        // transform, so the graph runs NCHW `FusedConv` instead of
181        // `NhwcFusedConv` — the issue measured ~1.4× on Apple-silicon CPU
182        // for the same weights re-exported static. Overriding the dimension
183        // at session creation gets the static graph without a re-export; it
184        // also leaves the whole graph static-shaped, which is what the
185        // CoreML provider's static-partitions default (#324) wants. Batched
186        // mode keeps the axis free — those sessions must accept N pages.
187        if crate::pdf_layout_batch() == 1 {
188            builder = builder
189                .with_dimension_override("batch", 1)
190                .map_err(|e| format!("layout: dimension override: {e}"))?;
191        }
192        let builder = docling_onnx::apply(builder).map_err(|e| format!("layout: {e}"))?;
193        // The pinned batch axis changes the optimized graph — separate cache entry.
194        let variant = if crate::pdf_layout_batch() == 1 {
195            "batch=1"
196        } else {
197            "batch=dyn"
198        };
199        docling_onnx::commit(builder, path, variant)
200            .map_err(|e| format!("layout: load {path}: {e}"))
201    }
202
203    /// Re-run one page through the fp32 graph — the escape hatch for a page
204    /// whose int8 detections look implausible (see `fp32_path`). `Ok(None)`
205    /// when there is nothing to escalate to: fp32 already loaded, an explicit
206    /// model override, or no fp32 file on disk.
207    pub fn predict_fp32_fallback(
208        &mut self,
209        img: LayoutSrc<'_>,
210        page_w: f32,
211        page_h: f32,
212    ) -> Result<Option<Vec<Region>>, String> {
213        let Some(path) = self.fp32_path.clone() else {
214            return Ok(None);
215        };
216        if self.fp32.is_none() {
217            if crate::timing::enabled() {
218                eprintln!("docling-pdf: loading fp32 layout fallback: {path}");
219            }
220            self.fp32 = Some(Self::open_session(&path, self.intra)?);
221        }
222        let session = self.fp32.as_mut().expect("just loaded");
223        Ok(Some(
224            Self::run_on(session, &[(img, page_w, page_h)])?
225                .pop()
226                .expect("one result per input page"),
227        ))
228    }
229
230    /// Detect layout regions on a page image. `page_w`/`page_h` are the page size
231    /// in points; returned boxes are in those coordinates.
232    pub fn predict(
233        &mut self,
234        img: LayoutSrc<'_>,
235        page_w: f32,
236        page_h: f32,
237    ) -> Result<Vec<Region>, String> {
238        Ok(self
239            .predict_batch(&[(img, page_w, page_h)])?
240            .pop()
241            .expect("one result per input page"))
242    }
243
244    /// Detect layout regions on several page images with **one** inference call
245    /// (issue #73). The ONNX export has a dynamic batch dimension, so a worker
246    /// can amortize the per-run framework overhead and keep its cores busier on
247    /// multi-page documents. Results are per-image, index-aligned with `pages`,
248    /// and identical to calling [`predict`](Self::predict) per page.
249    pub fn predict_batch(
250        &mut self,
251        pages: &[(LayoutSrc<'_>, f32, f32)],
252    ) -> Result<Vec<Vec<Region>>, String> {
253        if pages.len() > 1 && self.batch_unsupported {
254            return self.predict_singly(pages);
255        }
256        match self.run_batch(pages) {
257            Err(e) if pages.len() > 1 => {
258                // A graph without the dynamic batch dim (pre-#73 export) fails
259                // only for batch > 1 — remember and recover per page. Warn once
260                // per process, not per worker: every worker owns a LayoutModel
261                // over the same graph file, so repeats carry no information.
262                static WARNED: std::sync::atomic::AtomicBool =
263                    std::sync::atomic::AtomicBool::new(false);
264                if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
265                    eprintln!(
266                        "docling-pdf: layout model rejected a {}-page batch ({e}); \
267                         falling back to per-page inference — re-export with \
268                         scripts/install/export_layout.py for batched layout",
269                        pages.len()
270                    );
271                }
272                self.batch_unsupported = true;
273                self.predict_singly(pages)
274            }
275            other => other,
276        }
277    }
278
279    fn predict_singly(
280        &mut self,
281        pages: &[(LayoutSrc<'_>, f32, f32)],
282    ) -> Result<Vec<Vec<Region>>, String> {
283        pages
284            .iter()
285            .map(|p| Ok(self.run_batch(&[*p])?.pop().expect("one result")))
286            .collect()
287    }
288
289    fn run_batch(
290        &mut self,
291        pages: &[(LayoutSrc<'_>, f32, f32)],
292    ) -> Result<Vec<Vec<Region>>, String> {
293        Self::run_on(&mut self.session, pages)
294    }
295
296    fn run_on(
297        session: &mut Session,
298        pages: &[(LayoutSrc<'_>, f32, f32)],
299    ) -> Result<Vec<Vec<Region>>, String> {
300        if pages.is_empty() {
301            return Ok(Vec::new());
302        }
303        // Resize each page to 640×640 (RT-DETR ignores aspect ratio), rescale to
304        // [0,1], lay out as NCHW. The kernel depends on the source (see
305        // [`LayoutSrc`]): the docling-exact page image goes through Pillow's
306        // BILINEAR (the RT-DETR processor's kernel, byte-for-byte), raw
307        // bitmaps keep the legacy Triangle stretch.
308        let n = (SIDE * SIDE) as usize;
309        let batch = pages.len();
310        let mut data = vec![0f32; batch * 3 * n];
311        for (p, (src, _, _)) in pages.iter().enumerate() {
312            let resized = match src {
313                LayoutSrc::PageImage(img) => crate::resample::pil_resize(
314                    img,
315                    SIDE,
316                    SIDE,
317                    crate::resample::PilFilter::Bilinear,
318                ),
319                LayoutSrc::Raw(img) => {
320                    image::imageops::resize(*img, SIDE, SIDE, FilterType::Triangle)
321                }
322            };
323            let page_off = p * 3 * n;
324            for (i, px) in resized.pixels().enumerate() {
325                data[page_off + i] = px[0] as f32 / 255.0;
326                data[page_off + n + i] = px[1] as f32 / 255.0;
327                data[page_off + 2 * n + i] = px[2] as f32 / 255.0;
328            }
329        }
330        let input = Tensor::from_array(([batch, 3, SIDE as usize, SIDE as usize], data))
331            .map_err(|e| format!("layout: input tensor: {e}"))?;
332        let outputs = session
333            .run(ort::inputs!["pixel_values" => input])
334            .map_err(|e| format!("layout: inference: {e}"))?;
335        let (lshape, logits) = outputs["logits"]
336            .try_extract_tensor::<f32>()
337            .map_err(|e| format!("layout: extract logits: {e}"))?;
338        let (_, boxes) = outputs["pred_boxes"]
339            .try_extract_tensor::<f32>()
340            .map_err(|e| format!("layout: extract boxes: {e}"))?;
341
342        let num_queries = lshape[1] as usize;
343        let num_classes = lshape[2] as usize;
344
345        let mut all = Vec::with_capacity(batch);
346        for (p, (_, page_w, page_h)) in pages.iter().enumerate() {
347            let logits =
348                &logits[p * num_queries * num_classes..(p + 1) * num_queries * num_classes];
349            let boxes = &boxes[p * num_queries * 4..(p + 1) * num_queries * 4];
350            all.push(decode_layout(
351                logits,
352                boxes,
353                num_queries,
354                num_classes,
355                *page_w,
356                *page_h,
357            ));
358        }
359        Ok(all)
360    }
361}
362
363fn sigmoid(x: f32) -> f32 {
364    1.0 / (1.0 + (-x).exp())
365}
366
367/// Pack one page image into the model's `(1, 3, SIDE, SIDE)` input: resize
368/// (aspect ignored, RT-DETR convention), rescale to `[0,1]`, CHW. Shared
369/// with the browser build (#157), which delegates only the session call.
370#[cfg(feature = "ocr-prep")]
371pub fn layout_input(img: &image::RgbImage) -> Vec<f32> {
372    let n = (SIDE * SIDE) as usize;
373    let mut data = vec![0f32; 3 * n];
374    let resized = image::imageops::resize(img, SIDE, SIDE, image::imageops::FilterType::Triangle);
375    for (i, px) in resized.pixels().enumerate() {
376        data[i] = px[0] as f32 / 255.0;
377        data[n + i] = px[1] as f32 / 255.0;
378        data[2 * n + i] = px[2] as f32 / 255.0;
379    }
380    data
381}
382
383/// Decode one page's raw RT-DETR outputs into scored [`Region`]s in page
384/// points — sigmoid over every (query, class), top-`num_queries` kept, boxes
385/// converted center→corners and scaled. Shared with the browser build; the
386/// native batch path calls it per page, so both decode identically.
387pub fn decode_layout(
388    logits: &[f32],
389    boxes: &[f32],
390    num_queries: usize,
391    num_classes: usize,
392    page_w: f32,
393    page_h: f32,
394) -> Vec<Region> {
395    let mut scored: Vec<(f32, usize)> = (0..num_queries * num_classes)
396        .map(|idx| (sigmoid(logits[idx]), idx))
397        .collect();
398    scored.sort_unstable_by(|a, b| b.0.total_cmp(&a.0));
399    scored.truncate(num_queries);
400
401    let mut regions = Vec::new();
402    for (score, idx) in scored {
403        if score <= THRESHOLD {
404            continue;
405        }
406        let label_id = idx % num_classes;
407        let q = idx / num_classes;
408        let cx = boxes[q * 4];
409        let cy = boxes[q * 4 + 1];
410        let w = boxes[q * 4 + 2];
411        let h = boxes[q * 4 + 3];
412        // center_to_corners, then scale normalized coords to page points.
413        let l = (cx - w / 2.0) * page_w;
414        let t = (cy - h / 2.0) * page_h;
415        let r = (cx + w / 2.0) * page_w;
416        let b = (cy + h / 2.0) * page_h;
417        regions.push(Region {
418            label: LABELS.get(label_id).copied().unwrap_or("text"),
419            score,
420            l,
421            t,
422            r,
423            b,
424        });
425    }
426    regions
427}