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,789 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
# 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.
"""Select a word attention mode using sparse support and transcript neighbors."""

from typing import Protocol
from .predict import predict
from .rust import get_rust

import numpy as np
from .blocks import Block

PEAK_FEATURE_VERSION = "word-peaks-v1"
PEAK_FEATURE_COUNT = 22
PEAK_SELECTION_MARGIN = 0.1


class PeakPredictor(Protocol):
    def predict(self, features: np.ndarray) -> np.ndarray: ...


def peak_candidates(
    context: np.ndarray,
    peak: np.ndarray,
    indices: list[int],
    values: list[float],
    grid_width: int,
) -> tuple[list[int], list[list[float]]]:
    """Return sparse-array positions and features for four separated modes.

    Positions index the original sparse arrays, not sorted ranks or grid cells.
    Geometry uses grid-cell units. Neighbor offsets come from the existing
    53-column word context representation; reference boxes are not inputs.
    """
    ix, attention = np.asarray(indices), np.asarray(values)
    points = np.column_stack([ix % grid_width + 0.5, ix // grid_width + 0.5])
    remaining = np.argsort(-attention)
    retained = []
    while len(remaining) and len(retained) < 4:
        index = int(remaining[0])
        retained.append(index)
        # Squared distance preserves the 1.5-cell separation without square roots.
        distance = points[remaining] - points[index]
        remaining = remaining[distance[:, 0] ** 2 + distance[:, 1] ** 2 >= 2.25]
    selected = points[retained]
    delta = selected - peak
    nearby = (abs(points[None, :, 0] - selected[:, None, 0]) <= 1) & (
        abs(points[None, :, 1] - selected[:, None, 1]) <= 1
    )
    rows = np.empty((len(retained), PEAK_FEATURE_COUNT))
    rows[:, 0] = np.arange(len(retained))
    rows[:, 1] = attention[retained] / attention.max()
    total = attention.sum()
    rows[:, 2] = [attention[mask].sum() / total for mask in nearby]
    rows[:, 3] = np.log1p(context[0])
    rows[:, 4:6] = delta
    neighbors = context[34:50].reshape(4, 4)
    offsets = np.clip(neighbors[None, :, :2] - delta[:, None, :], -30, 30)
    offsets = np.where(neighbors[None, :, 3:4] != 0, offsets, 0)
    tail = rows[:, 6:].reshape(-1, 4, 4)
    tail[:, :, :2] = offsets
    tail[:, :, 2] = np.log1p(neighbors[:, 2])
    tail[:, :, 3] = neighbors[:, 3]
    return retained, rows.tolist()


def select_word_peaks(
    context: np.ndarray,
    valid: list[int],
    peaks: np.ndarray,
    sparse: dict,
    grid: tuple[int, int],
    blocks: list[Block],
    per_block: list[list[int]],
    model: PeakPredictor,
) -> dict[int, int]:
    """Map original text-unit indices to selected sparse-array positions.

    Batch candidate scoring across the page. Preserve the primary mode unless
    an alternative clears the quality margin; image and table maps are skipped.
    """
    eligible = {
        u
        for block, units in zip(blocks, per_block)
        if block.type in {"text", "list", "heading", "header", "footer"}
        for u in units
    }
    rust = get_rust()
    if rust is not None:
        rows, records = rust.peak_features(
            context, valid, peaks, sparse, grid, eligible
        )
    else:
        rows, records = [], []
        for j, u in enumerate(valid):
            if u not in eligible:
                continue
            retained, features = peak_candidates(
                context[j], peaks[j], sparse["idx"][u], sparse["val"][u], grid[1]
            )
            records.append((u, len(rows), retained))
            rows.extend(features)
    if not len(rows):
        return {}
    quality = predict(model, np.asarray(rows))
    choices = {}
    for u, start, retained in records:
        scores = quality[start : start + len(retained)]
        best = int(scores.argmax())
        if best and scores[best] > scores[0] + PEAK_SELECTION_MARGIN:
            choices[u] = retained[best]
    _repair_bracketed_peaks(choices, valid, peaks, sparse, grid, blocks, per_block)
    return choices


def _repair_bracketed_peaks(
    choices: dict[int, int],
    valid: list[int],
    peaks: np.ndarray,
    sparse: dict,
    grid: tuple[int, int],
    blocks: list[Block],
    per_block: list[list[int]],
) -> None:
    """Repair isolated vertical outliers bracketed by same-line transcript words.

    Coordinates and tolerances use attention cells. Snapshot ranked peaks before
    repairs so changes do not propagate into subsequent repair decisions. Choices
    retain original sparse-array positions, including gaps from missing attention.
    """
    grid_width = grid[1]
    lookup = {unit: row for row, unit in enumerate(valid)}
    positions = peaks.copy()
    for unit, index in choices.items():
        cell = sparse["idx"][unit][index]
        positions[lookup[unit]] = [cell % grid_width + 0.5, cell // grid_width + 0.5]
    for block, units in zip(blocks, per_block):
        if block.type not in {"text", "list"}:
            continue
        rows = [lookup[unit] for unit in units if unit in lookup]
        if len(rows) < 8:
            continue
        for index in range(1, len(rows) - 1):
            row = rows[index]
            before, after = positions[rows[index - 1]], positions[rows[index + 1]]
            if abs(before[1] - after[1]) > 1 or after[0] < before[0]:
                continue
            neighbors = rows[max(0, index - 3) : index] + rows[index + 1 : index + 4]
            nearby = positions[neighbors]
            ys = nearby[:, 1]
            low, high = ys.min(), ys.max()
            # A point inside a one-cell band cannot be 1.5 cells from its median.
            # Reject these common cases before computing the median.
            if high - low > 1 or low <= positions[row, 1] <= high:
                continue
            line_y = float(np.median(ys))
            if abs(positions[row, 1] - line_y) <= 1.5:
                continue
            unit = valid[row]
            cells = np.asarray(sparse["idx"][unit])
            values = np.asarray(sparse["val"][unit])
            x, y = cells % grid_width + 0.5, cells // grid_width + 0.5
            # Require a strong alternative between immediate neighbors. Endpoints
            # and line resets lack this evidence and retain the ranked choice.
            eligible = (
                (abs(y - line_y) <= 0.5)
                & (x >= before[0] - 0.5)
                & (x <= after[0] + 0.5)
                & (values >= 0.25 * values.max())
            )
            if eligible.any():
                indices = np.flatnonzero(eligible)
                choices[unit] = int(indices[values[indices].argmax()])