Glancelot / README.md
johnsonkuan's picture
Polish README wording and flow
fd412cb verified
|
Raw History Blame Contribute Delete
7.53 kB
metadata
license: apache-2.0
library_name: onnx
pipeline_tag: image-classification
tags:
  - onnx
  - document-layout
  - page-routing
  - mobilenetv3
model_name: Glancelot
inference: false

Glancelot mascot

Glancelot

Glancelot is a tiny vision model that helps document pipelines decide which pages to send to more expensive layout analysis. Given a 224×224 page thumbnail, the 1.53M-parameter classifier produces a layout-routing score alongside predictions for eight structural categories, including tables, pictures, and formulas.

Model details

Property Value
Architecture ImageNet-pretrained MobileNetV3-Small, nine-output head
Parameters 1,527,081
Deployment FP32 ONNX, about 6 MB
Input RGB thumbnails, float32 NCHW, (batch, 3, 224, 224)
Output Nine raw logits, (batch, 9)
Routing sigmoid(logits[:, 8]) > config["tau"]

Outputs

Glancelot is multi-label: several structures can appear on one page. Apply sigmoid to each logit; the scores do not sum to one. The eight structural predictions indicate content types, not locations on the page.

Index Target Structure or role
0 has_table Table
1 has_picture Picture
2 has_formula Formula
3 has_code Code
4 has_doc_index Document index
5 has_checkbox Selected or unselected checkbox
6 has_form Form
7 has_kv_region Key/value region
8 needs_layout_analysis Layout-routing output

For each structural target at indices 0–7, the training label is 1 when Heron, Docling's document layout analysis model, records at least one detection of the corresponding structure; otherwise the label is 0.

The ninth training target, needs_layout_analysis, is 1 when any of the first eight structural targets is 1, and 0 otherwise. Heron’s other labels (text, headers, footers, titles, lists, footnotes, and captions) do not contribute to Glancelot’s needs_layout_analysis training label.

At inference, compute the routing score as sigmoid(logits[:, 8]). The ninth output is a separately learned prediction, not a combination of the eight structural predictions. Use the routing score with the tau threshold in config.json (currently 0.20900137722492218). A score above tau flags the page for layout analysis. See target definitions and training details.

Usage

The example returns layout-routing scores for prepared page thumbnails. Your pipeline supplies PDF rendering, text extraction, and any OCR.

Install the dependencies:

pip install huggingface_hub onnxruntime numpy pillow

The example downloads the configuration and ONNX model. The repository is currently private, so authenticate with a Hugging Face account that has access. For reproducible deployments, pass the same full commit SHA as revision to both downloads.

import json
from pathlib import Path

import numpy as np
import onnxruntime as ort
from huggingface_hub import hf_hub_download
from PIL import Image

repo = "chowderai/Glancelot"
config_path = hf_hub_download(repo, "config.json")
config = json.loads(Path(config_path).read_text())
model_path = hf_hub_download(repo, config["onnx_file"])
session = ort.InferenceSession(model_path, providers=["CPUExecutionProvider"])

mean = np.asarray(config["image_mean"], dtype=np.float32).reshape(1, 3, 1, 1)
std = np.asarray(config["image_std"], dtype=np.float32).reshape(1, 3, 1, 1)


def route_thumbnails(paths):
    """Return routing scores and needs-layout flags for prepared 224×224 thumbnails."""
    images = []
    for path in paths:
        with Image.open(path) as image:
            image = image.convert("RGB")
            if image.size != (config["image_size"], config["image_size"]):
                raise ValueError("Prepare 224×224 page thumbnails before inference")
            images.append(np.asarray(image, dtype=np.float32).transpose(2, 0, 1))
    x = np.stack(images) / np.float32(255.0)
    x = np.ascontiguousarray((x - mean) / std)
    logits = session.run([config["output_name"]], {config["input_name"]: x})[0]
    routing_logits = np.clip(logits[:, config["routing_head_index"]], -80.0, 80.0)
    scores = 1.0 / (1.0 + np.exp(-routing_logits))
    return scores, scores > config["tau"]


scores, needs_layout = route_thumbnails(["page-0001.jpg", "page-0002.jpg"])
for score, decision in zip(scores, needs_layout):
    print({"routing_score": float(score), "needs_layout": bool(decision)})

The function expects a non-empty list of prepared page thumbnails. Match the training preprocessing: render each page with its longer side at 224 pixels, resize to 224×224 using Pillow’s LANCZOS resampling, save as JPEG at quality 85, and reload the JPEG before inference. The inference code divides RGB values by 255 and normalizes them with the ImageNet mean and standard deviation recorded in config.json.

Different rendering or preprocessing can change scores, especially near the routing threshold.

We recommend validating routing thresholds on representative documents from your target domain and checking downstream extraction quality.

To measure processing-time savings on your workload, include thumbnail rendering, Glancelot inference, and downstream extraction.

Training and evaluation

Glancelot was fine-tuned with binary cross-entropy on binary labels derived from Heron detections. The source pool contains approximately 1.29M page thumbnails, including evaluation pages. The source PDFs and training dataset are not included in this repository.

We selected a conservative routing threshold to favor recall: skipping layout analysis on a page with an important table can damage extraction, while sending a simple page to layout analysis adds computation.

The checkpoint and threshold were selected on the same 36,605-page validation split. Recall was 99.002% on pages Heron labeled as needing layout. The false-positive rate was 32.074% on pages Heron labeled as not needing layout. These metrics measure validation agreement with Heron, rather than independent extraction quality.

A recorded CPU measurement on an M2 Pro was 39.2 ms per 32 thumbnails (about 1.22 ms/page when batched). The timing covers model inference after warmup, excluding model loading, thumbnail rendering, and extraction. See training, evaluation, and timing conditions.

Files

triage_fp32.onnx contains the deployed model; config.json records preprocessing and the operating threshold. threshold.json is the threshold-only export, and best.pt is the PyTorch training checkpoint for re-export or fine-tuning with the nine-output MobileNetV3-Small architecture.

License

The model weights are licensed under Apache 2.0. See NOTICE for upstream attribution and model modifications.

Authors

  • Johnson Kuan

Citation

@misc{chowderai2026glancelot,
  title = {Glancelot: A Tiny Vision Model for Knowing When to Skip Document Layout Analysis},
  author = {{Chowder AI}},
  year = {2026},
  url = {https://huggingface.co/chowderai/Glancelot}
}

Contact

For questions about this model, contact support@chowder.ai.