Run this model with HF Jobs

Run OpenTensorLab/OCRia-1-W4A16-AutoRound on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs and TRL to fine-tune https://huggingface.co/OpenTensorLab/OCRia-1-W4A16-AutoRound. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/OpenTensorLab/OCRia-1-W4A16-AutoRound on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.

Evaluate on a benchmark

Use HF Jobs to evaluate https://huggingface.co/OpenTensorLab/OCRia-1-W4A16-AutoRound. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
File size: 6,149 Bytes
90d9faa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved.
# Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository).
# This is not open-source software: see the license for permitted uses.
"""Reusable pixel-free layout extraction from precomputed word attention.

Frozen predictors are loaded once per instance. Capture coordinates and output
boxes use the original image pixel frame; PDF frame conversion belongs to the caller.
"""

from pathlib import Path
import time
from numbers import Integral

import numpy as np

import joblib

from .navigation import constrain_sidebar_icons
from .headings import (
    expand_table_to_embedded_heading,
    merge_bold_heading_continuations,
    merge_heading_lines,
    merge_numeric_callouts,
    trim_paragraph_heading_overlap,
)
from .pictures import (
    merge_figure_tables,
    trim_picture_text_overlap,
    trim_picture_table_overlap,
)
from .io import join_paragraph_segments, merge_duplicate_text, to_layout_page
from .learned import ground_cached


def finalize_layout(answer: str, page: dict) -> dict:
    """Apply the retained checkpoint's geometry rules in their evaluation order."""
    page["items"] = merge_duplicate_text(merge_heading_lines(page["items"]))
    trim_picture_text_overlap(page["items"])
    page["items"] = merge_numeric_callouts(page["items"])
    trim_paragraph_heading_overlap(page["items"])
    page["items"] = join_paragraph_segments(answer, page["items"])
    page["items"] = merge_figure_tables(page["items"])
    page["items"] = merge_bold_heading_continuations(answer, page["items"])
    page["items"] = constrain_sidebar_icons(
        page["items"], page["width"], page["height"]
    )
    trim_picture_table_overlap(page["items"])
    expand_table_to_embedded_heading(page["items"])
    return page


def validate_capture(attention: dict) -> None:
    """Check external sparse coordinates before indexing arrays or native buffers."""
    dimensions = np.asarray([attention["width"], attention["height"]], dtype=float)
    if not np.isfinite(dimensions).all() or (dimensions <= 0).any():
        raise ValueError("Page dimensions must be finite and positive")
    grid = attention["grid"]
    if len(grid) != 2 or any(
        not isinstance(n, Integral) or isinstance(n, bool) or n <= 0 for n in grid
    ):
        raise ValueError("Attention grid must contain two positive integers")
    sparse = attention["sparse_maps"]
    if not len(sparse["idx"]) == len(sparse["val"]) == len(sparse["has"]):
        raise ValueError("Sparse indices, values, and validity rows must align")
    flags = np.asarray(sparse["has"])
    if flags.ndim != 1 or (len(flags) and flags.dtype.kind != "b"):
        raise ValueError("Attention validity flags must be boolean")
    cells = int(grid[0]) * int(grid[1])
    for indices, values in zip(sparse["idx"], sparse["val"], strict=True):
        if len(indices) != len(values):
            raise ValueError("Each sparse index must have one attention value")
        if not len(indices):
            continue
        indices = np.asarray(indices)
        values = np.asarray(values, dtype=np.float32)
        if (
            indices.ndim != 1
            or indices.dtype.kind not in "iu"
            or (indices < 0).any()
            or (indices >= cells).any()
        ):
            raise ValueError(
                "Sparse indices must be integers inside the attention grid"
            )
        if values.ndim != 1 or not np.isfinite(values).all() or (values < 0).any():
            raise ValueError("Sparse attention values must be finite and nonnegative")


class FastLayout:
    """A reusable backend with explicit, trusted frozen predictor artifacts."""

    def __init__(
        self, *, words: Path, pictures: Path, regions: Path, tables: Path, peaks: Path
    ) -> None:
        self.words = joblib.load(words)
        self.pictures = joblib.load(pictures)
        self.regions = joblib.load(regions)
        self.tables = joblib.load(tables)
        self.peaks = joblib.load(peaks)

    def layout_page(self, *, answer: str, attention: dict) -> dict:
        """Return a ParseBench page in pixels, including spatial text segments.

        Attention uses the existing cache contract: width, height, grid [h,w],
        sparse_maps {idx, val, has}, one row per transcript attention unit.
        This method performs no image, PDF, network, or model-inference I/O.
        """
        validate_capture(attention)
        result = ground_cached(
            answer,
            attention,
            self.words,
            picture_model=self.pictures,
            with_extended_context=True,
            region_models=self.regions,
            table_model=self.tables,
            with_region_context=True,
            peak_model=self.peaks,
        )
        page = to_layout_page(
            answer, result["elements"], attention["width"], attention["height"]
        )
        return finalize_layout(answer, page)

    def __call__(self, *, answer: str, attention: dict) -> dict:
        """Return the public OCRia item schema, retaining detailed text segments."""
        started = time.perf_counter()
        page = self.layout_page(answer=answer, attention=attention)
        items = []
        for item in page["items"]:
            box = item["bbox"]
            items.append(
                {
                    "type": item["type"],
                    "label": box["label"],
                    "md": item["md"],
                    "box": [
                        box["x"],
                        box["y"],
                        box["x"] + box["w"],
                        box["y"] + box["h"],
                    ],
                    "layout_segments": item["layout_segments"],
                }
            )
        return {
            "width": page["width"],
            "height": page["height"],
            "items": items,
            "attention_source": "precomputed",
            "timings_ms": {
                "attention_capture": 0.0,
                "layout_postprocessing": (time.perf_counter() - started) * 1000,
            },
        }