docling icon indicating copy to clipboard operation
docling copied to clipboard

TableFormer: a table crop given to `multi_table_predict` is upscaled to 1024 px, and the predicted structure degrades

Open sibisrinivasb opened this issue 2 weeks ago • 1 comments

Bug

TFPredictor.multi_table_predict (docling-ibm-models) starts with

# Prevent large image submission, by resizing input
page_image_resized, scale_factor = self.resize_img(page_image, height=1024)

resize_img always resizes to the requested height so an image smaller than 1024 px is scaled up. For a PDF page this does not matter. For a table crop it does: TableStructureModel._do_prediction_on_image_to_table gives the crop as the page, with the whole image as the table box. A 245 x 158 px PubTabNet crop is scaled up 6.5 times (INTER_AREA) and only then goes through the 448 px preprocessing of TableFormer. On such crops the model often ends the table right after the header.

The method has the note "In the near future, we expect this method to be used in predict_tables", and docling-eval makes the same call for its table benchmarks, so I think it is worth fixing before more code depends on it.

Steps to reproduce

The script below needs only docling-ibm-models, huggingface_hub, pyarrow and pillow. It reads six tables of docling-project/PubTabNet_OTSL (val) twice with TableFormer accurate: as-is, and padded with blank white space to a height of 1024 px, so that the resize has a factor of exactly 1. It runs on the CPU.

repro.py
"""TableFormer on small table crops: the page resize of `TFPredictor.multi_table_predict` scales them up and the structure degrades.

For each table of docling-project/PubTabNet_OTSL (val), the table image is read twice by TableFormer (accurate):
  as-is    the crop is given to `multi_table_predict` as the page, the whole image as the table box
           (what `TableStructureModel._do_prediction_on_image_to_table` and docling-eval do);
  padded   the same call, with the crop padded with white rows to a height of 1024 px, so the page resize has a factor of exactly 1.
The script prints the number of predicted rows next to the number of rows in the ground truth.

Needs: docling-ibm-models, huggingface_hub, pyarrow, pillow, numpy.  Runs on the CPU in about 3 s per table.
    python repro.py                 # six example tables
    python repro.py --n 20          # the first 20 samples
"""
import argparse
import io
import json
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
from PIL import Image

PAGE_HEIGHT = 1024  # the height `multi_table_predict` resizes every page image to
EXAMPLES = {"PMC5863103_002_00.png", "PMC2572633_003_00.png", "PMC2546377_005_00.png", "PMC5296661_008_00.png",
            "PMC2760526_010_00.png", "PMC5011633_006_00.png"}


def pad_to_page_height(image: np.ndarray) -> np.ndarray:
    if image.shape[0] >= PAGE_HEIGHT:
        return image
    padding = np.full((PAGE_HEIGHT - image.shape[0], *image.shape[1:]), 255, dtype=image.dtype)
    return np.concatenate([image, padding], axis=0)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--n", type=int, default=0, help="read the first N samples instead of the six examples")
    ap.add_argument("--parquet", default=None)
    ap.add_argument("--weights", default=None)
    args = ap.parse_args()

    from docling_ibm_models.tableformer.data_management.tf_predictor import TFPredictor
    from huggingface_hub import hf_hub_download, snapshot_download

    if args.weights is None:
        root = snapshot_download("docling-project/docling-models", allow_patterns="model_artifacts/tableformer/accurate/*")
        args.weights = str(Path(root) / "model_artifacts" / "tableformer" / "accurate")
    if args.parquet is None:
        args.parquet = hf_hub_download("docling-project/PubTabNet_OTSL", "data/val-00000-of-00001-2d685be412ba1e61.parquet",
                                       repo_type="dataset")
    config = json.loads((Path(args.weights) / "tm_config.json").read_text(encoding="utf-8"))
    config["model"]["save_dir"] = args.weights
    predictor = TFPredictor(config, device="cpu", num_threads=4)

    def rows(image: np.ndarray, width: int, height: int) -> int:
        page = {"image": image, "width": image.shape[1], "height": image.shape[0], "tokens": []}
        out = predictor.multi_table_predict(page, [[0.0, 0.0, float(width), float(height)]], do_matching=False)
        return out[0]["predict_details"]["prediction"]["rs_seq"].count("nl")

    table = pq.ParquetFile(args.parquet)
    if args.n:
        batch = next(table.iter_batches(batch_size=args.n, columns=["filename", "rows", "image"])).to_pylist()
    else:  # the six examples of this report; all are among the first 1,000 samples
        head = next(table.iter_batches(batch_size=1000, columns=["filename", "rows", "image"])).to_pylist()
        batch = [s for s in head if s["filename"] in EXAMPLES]
    right_as_is = right_padded = 0
    print(f"{'file':26s} {'size':>9s} {'true':>5s} {'as-is':>6s} {'padded':>7s}")
    for sample in batch:
        pil = Image.open(io.BytesIO(sample["image"]["bytes"])).convert("RGB")
        bgr = np.ascontiguousarray(np.asarray(pil)[:, :, ::-1])  # the channel order of cv2.imread, as in the tests of docling-ibm-models
        height, width = bgr.shape[:2]
        as_is, padded = rows(bgr, width, height), rows(pad_to_page_height(bgr), width, height)
        right_as_is += as_is == sample["rows"]
        right_padded += padded == sample["rows"]
        print(f"{sample['filename']:26s} {width:4d}x{height:<4d} {sample['rows']:5d} {as_is:6d} {padded:7d}")
    print(f"\nrow count equal to the ground truth: as-is {right_as_is} / {len(batch)}, padded {right_padded} / {len(batch)}")


if __name__ == "__main__":
    main()

Output (rows in the ground truth, rows predicted as-is, rows predicted padded):

file                            size  true  as-is  padded
PMC5296661_008_00.png       506x124     10      2      10
PMC2546377_005_00.png       503x220     17      3      17
PMC5011633_006_00.png       243x169     14      2      13
PMC5863103_002_00.png       243x182     18      2      18
PMC2572633_003_00.png       245x158     13      2      13
PMC2760526_010_00.png       245x127     10      2      10

row count equal to the ground truth: as-is 0 / 6, padded 5 / 6

On the first 1,000 samples of the same split, structure-only TEDS computed with the TEDScorer of docling-eval (structure_only=True, the model's structure output, no cell matching):

TEDS-struct tables below 0.5
as-is 0.938 34
padded to 1024 px 0.949 20

The difference is +0.011 (95 % bootstrap interval +0.005 to +0.018). It is not uniform: 53 tables improve, 38 get worse, 909 are identical. The gain is largest for crops between 100 and 199 px high and absent from 300 px.

Possible fixes

  1. In docling: pad a crop shorter than 1024 px before the call (small, no change in docling-ibm-models). I have this ready as a PR.
  2. In docling-ibm-models: resize only when the page is higher than 1024 px, which is what the comment says. This also covers docling-eval and small page images, but it changes the output for every page below 1024 px, so it needs your benchmarks.

Docling version

docling main at e16c4b7, docling-ibm-models main at 4419794, weights docling-project/docling-models, model_artifacts/tableformer/accurate.

Python version

3.12, Windows 11

sibisrinivasb avatar Nov 16 '26 21:11 sibisrinivasb

Classification labels added: priority:medium.

These labels are advisory. Maintainers can correct them. The workflow preserves these corrections.

github-actions[bot] avatar Nov 16 '26 21:11 github-actions[bot]