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: 10,438 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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# 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.
"""Transcript spans, sparse attention decoding, and layout serialization."""

import re
import numpy as np
from .blocks import Block, split_blocks
from .words import word_spans

_FURN_TAG = re.compile(r"</?(page_header|page_footer|page_number|watermark)>")
_HEADING_PREFIX = re.compile(r"^#{1,6}\s+")


def merge_duplicate_text(items: list[dict]) -> list[dict]:
    """Merge identical text predictions occupying the same page region.

    Formatting markers and whitespace do not distinguish duplicate text;
    punctuation, numbers and element types do. Keep the first occurrence's
    content with the tighter of two boxes whose intersection-over-union exceeds
    one half. Distinct locations remain separate occurrences.
    """
    kept: list[dict] = []
    seen: dict[tuple[str, str], list[int]] = {}
    for item in items:
        typ = item["type"]
        if typ not in {"Text", "Section-header", "Page-header", "Page-footer"}:
            kept.append(item)
            continue
        text = _HEADING_PREFIX.sub("", item["md"].strip())
        text = text.replace("**", "").replace("__", "").strip("*`_ \n")
        key = (typ, " ".join(text.casefold().split()))
        if len(key[1]) < 12:
            kept.append(item)
            continue
        box = item["bbox"]
        area = box["w"] * box["h"]
        for index in seen.get(key, []):
            old = kept[index]
            other = old["bbox"]
            other_area = other["w"] * other["h"]
            intersection = max(
                0,
                min(box["x"] + box["w"], other["x"] + other["w"])
                - max(box["x"], other["x"]),
            ) * max(
                0,
                min(box["y"] + box["h"], other["y"] + other["h"])
                - max(box["y"], other["y"]),
            )
            if intersection / max(1e-12, area + other_area - intersection) <= 0.5:
                continue
            if area < other_area:
                kept[index] = {
                    **old,
                    "bbox": box,
                    "layout_segments": item["layout_segments"],
                }
            break
        else:
            seen.setdefault(key, []).append(len(kept))
            kept.append(item)
    return kept


def element_text(answer: str, start: int, end: int) -> str:
    """Return scored element text while retaining raw spans for attention lookup."""
    return _FURN_TAG.sub("", answer[start:end]).strip()


def units_for(
    answer: str, blocks: list[Block]
) -> tuple[list[tuple[int, int]], list[list[int]]]:
    """Attention units and, per block, the indices of its units: every content word inside the block; an image
    block is one unit (its whole reference), because the picture it points at has no words to snap to."""
    spans = word_spans(answer)
    units: list[tuple[int, int]] = []
    per_block: list[list[int]] = []
    k = 0
    for b in blocks:
        mine: list[int] = []
        if b.type == "image":
            mine.append(len(units))
            units.append((b.start, b.end))
            per_block.append(mine)
            continue
        while k < len(spans) and spans[k][0] < b.start:
            k += 1
        j = k
        while j < len(spans) and spans[j][1] <= b.end:
            mine.append(len(units))
            units.append((spans[j][0], spans[j][1]))
            j += 1
        per_block.append(mine)
    return units, per_block


def dense_maps(sparse: dict, grid: tuple[int, int]) -> tuple[np.ndarray, np.ndarray]:
    """Inverse of `sparsify` (cells outside the kept top-k are 0)."""
    gh, gw = grid
    maps = np.zeros((len(sparse["idx"]), gh * gw), np.float32)
    for u, (i, v) in enumerate(zip(sparse["idx"], sparse["val"])):
        if i:
            maps[u, i] = v
    return maps.reshape(-1, gh, gw), np.array(sparse["has"], bool)


class SparseWordMaps:
    """Sparse float32 maps with one borrowed grid, valid until the next lookup."""

    def __init__(self, sparse: dict, grid: tuple[int, int]) -> None:
        self._scratch = np.zeros(grid, dtype=np.float32)
        self._last = np.empty(0, dtype=np.intp)
        self.indices = []
        self.values = []
        self.peaks = np.zeros(len(sparse["idx"]), dtype=np.intp)
        self.maxima = np.zeros(len(sparse["idx"]), dtype=np.float32)
        for u, (indices, values) in enumerate(zip(sparse["idx"], sparse["val"])):
            # Dense scatter keeps the last occurrence of a repeated cell.
            if len(set(indices)) != len(indices):
                cells = dict(zip(indices, values))
                indices, values = list(cells), list(cells.values())
            ix = np.asarray(indices, dtype=np.intp)
            mass = np.asarray(values, dtype=np.float32)
            self.indices.append(ix)
            self.values.append(mass)
        lengths = np.asarray([len(v) for v in self.values], dtype=np.intp)
        valid = np.flatnonzero(lengths)
        if len(valid):
            mass = np.concatenate(self.values)
            indices = np.concatenate(self.indices)
            starts = np.r_[0, np.cumsum(lengths[valid][:-1])]
            maxima = np.maximum.reduceat(mass, starts)
            if not np.isfinite(maxima).all():
                raise ValueError("Sparse word attention must have a finite maximum")
            # Resolve float32 ties by the first cell in dense grid order.
            candidates = np.where(
                mass == np.repeat(maxima, lengths[valid]), indices, grid[0] * grid[1]
            )
            peaks = np.minimum.reduceat(candidates, starts)
            positive = maxima > 0
            self.maxima[valid[positive]] = maxima[positive]
            self.peaks[valid[positive]] = peaks[positive]

    def __getitem__(self, unit: int) -> np.ndarray:
        self._scratch.flat[self._last] = 0
        self._scratch.flat[self.indices[unit]] = self.values[unit]
        self._last = self.indices[unit]
        return self._scratch


_V2_TYPE = {
    "text": ("Text", "text"),
    "heading": ("Section-header", "paragraph_title"),
    "table": ("Table", "table"),
    "image": ("Picture", "image"),
    "header": ("Page-header", "header"),
    "footer": ("Page-footer", "footer"),
}


def to_layout_page(
    answer: str,
    elements: list[dict],
    width: float,
    height: float,
    scale: float = 1.0,
    page_md: str = "",
) -> dict:
    """llamacloud-bench / ParseBench `layout_pages` entry. Boxes are x, y, w, h in the page's own units (pixels x
    `scale`; use 72 / DPI for PDF points), each item with one `layout_segments` entry equal to its box, because
    the v2 layout scorer ignores items without layout-aware segments."""
    items = []
    for el in elements:
        if el["box"] is None:
            continue
        x0, y0, x1, y1 = (v * scale for v in el["box"])
        if x1 <= x0 or y1 <= y0:
            continue
        md = element_text(answer, el["start"], el["end"])
        if el.get("close_table"):
            md += "</table>"
        typ, label = _V2_TYPE.get(el["type"], _V2_TYPE["text"])
        seg = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0, "label": label}
        items.append(
            {
                "type": typ,
                "md": md,
                "value": md,
                "bbox": dict(seg),
                "layout_segments": [seg],
            }
        )
    return {
        "page_number": 1,
        "width": width * scale,
        "height": height * scale,
        "md": page_md,
        "items": items,
    }


def join_paragraph_segments(answer: str, items: list[dict]) -> list[dict]:
    """Keep transcript paragraphs as logical items with indexed spatial segments.

    Adjacent text fragments must exactly reconstruct one original paragraph.
    Segment indices are inclusive offsets in the reconstructed Markdown, while
    boxes retain the page coordinate frame supplied by the caller.
    """
    paragraphs = {}
    for block in split_blocks(answer):
        if block.type == "text":
            markdown = element_text(answer, block.start, block.end)
            paragraphs["".join(markdown.split())] = markdown
    texts = ["".join(item["md"].split()) for item in items]
    result = []
    index = 0
    while index < len(items):
        item = items[index]
        stop = None
        if item["type"] == "Text" and texts[index] not in paragraphs:
            joined = []
            # Bound the search for a paragraph crossing several columns.
            for end in range(index, min(index + 8, len(items))):
                if (
                    items[end]["type"] != "Text"
                    or len(items[end]["layout_segments"]) != 1
                ):
                    break
                joined.append(texts[end])
                if end > index and "".join(joined) in paragraphs:
                    stop = end + 1
                    break
        if stop is None:
            result.append(item)
            index += 1
            continue
        markdown = paragraphs["".join(texts[index:stop])]
        # Map the whitespace-free match back to the untouched source Markdown.
        # Column cuts can fall beside formatting markers, not just spaces.
        offsets = [offset for offset, char in enumerate(markdown) if not char.isspace()]
        segments = []
        position = 0
        for piece, text in zip(items[index:stop], texts[index:stop]):
            segments.append(
                {
                    **piece["layout_segments"][0],
                    "start_index": offsets[position],
                    "end_index": offsets[position + len(text) - 1],
                }
            )
            position += len(text)
        x = min(segment["x"] for segment in segments)
        y = min(segment["y"] for segment in segments)
        x1 = max(segment["x"] + segment["w"] for segment in segments)
        y1 = max(segment["y"] + segment["h"] for segment in segments)
        result.append(
            {
                **item,
                "md": markdown,
                "value": markdown,
                "bbox": {**item["bbox"], "x": x, "y": y, "w": x1 - x, "h": y1 - y},
                "layout_segments": segments,
            }
        )
        index = stop
    return result