Run this model with HF Jobs

Run OpenTensorLab/OCRia-1-W4A16-LLM-Compressor 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-LLM-Compressor. 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-LLM-Compressor 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-LLM-Compressor. 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: 16,502 Bytes
d8db4d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# 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.
"""Optional page-batched Rust peak features, built explicitly outside the package."""

import argparse
import ctypes
from functools import lru_cache
import os
from pathlib import Path
import subprocess

import numpy as np

from .words import norm

_LIBRARY_ENV = "OCRIA_GROUNDING_RUST"


class RustKernels:
    """Own a trusted library; validate array dimensions before crossing the ABI."""

    def __init__(self, path: str) -> None:
        self.library = ctypes.CDLL(path)
        integer = np.ctypeslib.ndpointer(np.int64, flags="C_CONTIGUOUS")
        double = np.ctypeslib.ndpointer(np.float64, flags="C_CONTIGUOUS")
        self.function = self.library.page_peak_features
        self.function.argtypes = [
            ctypes.c_size_t,
            ctypes.c_int64,
            integer,
            integer,
            double,
            integer,
            double,
            double,
            double,
            integer,
            double,
            integer,
        ]
        self.function.restype = None
        self.bounds_function = self.library.context_bounds
        self.bounds_function.argtypes = [
            ctypes.c_size_t,
            ctypes.c_int64,
            integer,
            integer,
            double,
            double,
            integer,
            integer,
            double,
            double,
        ]
        self.bounds_function.restype = None
        self.local_function = self.library.local_features_unsorted
        self.local_function.argtypes = [
            ctypes.c_size_t,
            ctypes.c_int64,
            ctypes.c_int64,
            integer,
            integer,
            double,
            integer,
            integer,
            double,
            double,
        ]
        self.local_function.restype = None
        self.paths_function = self.library.paragraph_paths
        self.paths_function.argtypes = [ctypes.c_size_t, double, integer, integer]
        self.paths_function.restype = ctypes.c_size_t
        self.components_function = self.library.add_components
        self.components_function.argtypes = [
            ctypes.c_size_t,
            ctypes.c_size_t,
            ctypes.c_size_t,
            integer,
            integer,
            np.ctypeslib.ndpointer(np.float32, flags="C_CONTIGUOUS"),
            integer,
            double,
            integer,
            double,
        ]
        self.components_function.restype = ctypes.c_bool
        self.density_function = self.library.add_component_centroid
        self.density_function.argtypes = [
            ctypes.c_size_t,
            ctypes.c_size_t,
            np.ctypeslib.ndpointer(np.float32, flags="C_CONTIGUOUS"),
            ctypes.c_size_t,
            double,
            integer,
            double,
        ]
        self.density_function.restype = ctypes.c_size_t

    def peak_features(
        self,
        context: np.ndarray,
        valid: list[int],
        positions: np.ndarray,
        sparse: dict,
        grid: tuple[int, int],
        eligible: set[int],
    ) -> tuple[np.ndarray, list[tuple[int, int, list[int]]]]:
        """Pack eligible words once; return features and original sparse positions."""
        chosen = [(j, u) for j, u in enumerate(valid) if u in eligible]
        if not chosen:
            return np.empty((0, 22)), []
        if (
            context.ndim != 2
            or context.shape[0] != len(valid)
            or context.shape[1] < 53
            or positions.shape != (len(valid), 2)
            or grid[1] <= 0
        ):
            raise ValueError("Invalid peak context, positions, or grid width")
        js, us = zip(*chosen)
        arrays = [np.asarray(sparse["val"][u], dtype=np.float64) for u in us]
        indices = [np.asarray(sparse["idx"][u], dtype=np.int64) for u in us]
        if any(
            a.ndim != 1 or ix.ndim != 1 or not len(a) or len(a) != len(ix)
            for a, ix in zip(arrays, indices)
        ):
            raise ValueError(
                "Peak attention needs matching finite nonempty sparse arrays"
            )
        offsets = np.r_[0, np.cumsum([len(a) for a in arrays])].astype(np.int64)
        values = np.concatenate(arrays)
        packed_indices = np.concatenate(indices)
        if not np.isfinite(values).all() or np.any(packed_indices < 0):
            raise ValueError(
                "Peak attention needs matching finite nonempty sparse arrays"
            )
        # NumPy retains the reference tie order and logarithm rounding.
        order = np.concatenate([np.argsort(-a) for a in arrays])
        contexts = np.ascontiguousarray(context[list(js), :53], dtype=np.float64)
        ps = np.ascontiguousarray(positions[list(js)], dtype=np.float64)
        logs = np.ascontiguousarray(np.log1p(contexts[:, [0, 36, 40, 44, 48]]))
        retained = np.empty((len(us), 4), dtype=np.int64)
        out = np.empty((len(us), 4, 22))
        counts = np.empty(len(us), dtype=np.int64)
        self.function(
            len(us),
            grid[1],
            offsets,
            packed_indices,
            values,
            order,
            contexts,
            ps,
            logs,
            retained,
            out,
            counts,
        )
        records = []
        start = 0
        for j, u in enumerate(us):
            n = int(counts[j])
            records.append((u, start, retained[j, :n].tolist()))
            start += n
        # Keep the native feature buffer; incomplete candidate rows are padding.
        rows = (
            out.reshape(-1, 22)
            if np.all(counts == 4)
            else out[np.arange(4) < counts[:, None]]
        )
        return rows, records

    def context_bounds(
        self,
        sparse: dict,
        valid: list[int],
        peaks: np.ndarray,
        grid_width: int,
    ) -> tuple[np.ndarray, list[tuple[np.ndarray, np.ndarray, np.ndarray]]]:
        """Batch cell quantiles and threshold bounds, retaining normalized masses."""
        if grid_width <= 0 or peaks.shape != (len(valid), 2):
            raise ValueError("Invalid context peak shape or grid width")
        rows = []
        for u in valid:
            ix = np.asarray(sparse["idx"][u], dtype=np.int64)
            attention = np.asarray(sparse["val"][u], dtype=np.float64)
            if (
                ix.ndim != 1
                or attention.ndim != 1
                or not len(ix)
                or len(ix) != len(attention)
            ):
                raise ValueError(
                    "Context needs matching finite positive sparse attention"
                )
            rows.append((ix, attention))
        if not rows:
            return np.empty((0, 22)), []
        offsets = np.r_[0, np.cumsum([len(v[0]) for v in rows])].astype(np.int64)
        indices = np.concatenate([v[0] for v in rows])
        attention = np.concatenate([v[1] for v in rows])
        if (
            np.any(indices < 0)
            or not np.isfinite(attention).all()
            or np.any(attention < 0)
            or np.any(np.maximum.reduceat(attention, offsets[:-1]) <= 0)
        ):
            raise ValueError("Context needs matching finite positive sparse attention")
        # Preserve reference float-coordinate tie ordering before cumulative sums.
        if all(len(row[0]) == len(rows[0][0]) for row in rows):
            # Top-k captures usually have equal row lengths. Sort both axes in
            # batches while retaining NumPy's per-row coordinate tie ordering.
            weights = attention.reshape(len(rows), -1)
            normalized = weights / weights.sum(axis=1)[:, None]
            mass = normalized.ravel()
            packed = [
                (ix, values, normalized[j]) for j, (ix, values) in enumerate(rows)
            ]
            cells = indices.reshape(len(rows), -1)
            order_x = np.argsort(cells % grid_width + 0.5, axis=1).ravel()
            order_y = np.argsort(cells // grid_width + 0.5, axis=1).ravel()
        else:
            packed = [(ix, values, values / values.sum()) for ix, values in rows]
            mass = np.concatenate([v[2] for v in packed])
            order_x = np.concatenate(
                [np.argsort(v[0] % grid_width + 0.5) for v in packed]
            )
            order_y = np.concatenate(
                [np.argsort(v[0] // grid_width + 0.5) for v in packed]
            )
        out = np.empty((len(valid), 22))
        self.bounds_function(
            len(valid),
            grid_width,
            offsets,
            indices,
            attention,
            mass,
            order_x,
            order_y,
            np.ascontiguousarray(peaks, dtype=np.float64),
            out,
        )
        return out, packed

    def local_features(
        self,
        answer: str,
        units: list[tuple[int, int]],
        sparse: dict,
        grid: tuple[int, int],
        anchors: dict[int, int] | None = None,
    ) -> tuple[np.ndarray, list[int], np.ndarray]:
        """Batch word patches and moments, preserving original unit indices."""
        if grid[0] <= 0 or grid[1] <= 0:
            raise ValueError("Attention grid dimensions must be positive")
        arrays, indices, valid, lengths, selected = [], [], [], [], []
        rows = []
        for u, (start, end) in enumerate(units):
            ix = np.asarray(sparse["idx"][u], dtype=np.int64)
            values = np.asarray(sparse["val"][u], dtype=np.float64)
            if not len(ix) or not sparse["has"][u]:
                continue
            if ix.ndim != 1 or values.ndim != 1 or len(ix) != len(values):
                raise ValueError("Invalid sparse word attention")
            rows.append((u, start, end, ix, values))
        # Validate before dropping zero-mass rows, using one scan per packed array.
        if rows:
            all_indices = np.concatenate([row[3] for row in rows])
            all_values = np.concatenate([row[4] for row in rows])
            if (
                not np.isfinite(all_values).all()
                or np.any(all_indices < 0)
                or np.any(all_indices >= grid[0] * grid[1])
                or np.any(all_values < 0)
            ):
                raise ValueError("Invalid sparse word attention")
        for u, start, end, ix, values in rows:
            if not values.max():
                continue
            chosen = -1
            if anchors and u in anchors:
                chosen = anchors[u]
                if chosen < 0 or chosen >= len(values):
                    raise ValueError("Anchor is outside sparse word attention")
            selected.append(chosen)
            indices.append(ix)
            arrays.append(values)
            valid.append(u)
            lengths.append(len(norm(answer[start:end])))
        out = np.empty((len(valid), 34))
        peaks = np.empty((len(valid), 2))
        if not valid:
            return out, valid, peaks
        offsets = np.r_[0, np.cumsum([len(a) for a in arrays])].astype(np.int64)
        self.local_function(
            len(valid),
            grid[0],
            grid[1],
            offsets,
            np.concatenate(indices),
            np.concatenate(arrays),
            np.asarray(lengths, dtype=np.int64),
            np.asarray(selected, dtype=np.int64),
            out,
            peaks,
        )
        return out, valid, peaks

    def paragraph_paths(self, boxes: list[list[float]]) -> list[list[int]] | None:
        """Return transcript-index paths through finite pixel-coordinate boxes."""
        if len(boxes) < 3:
            return None
        values = np.ascontiguousarray(boxes, dtype=np.float64)
        if values.shape != (len(boxes), 4) or not np.isfinite(values).all():
            raise ValueError("Paragraph paths require finite N x 4 boxes")
        out = np.empty(len(boxes), dtype=np.int64)
        offsets = np.empty(len(boxes) + 1, dtype=np.int64)
        count = self.paths_function(len(boxes), values, out, offsets)
        return (
            [out[offsets[k] : offsets[k + 1]].tolist() for k in range(count)]
            if count
            else None
        )

    def add_components(
        self,
        indices: list[np.ndarray],
        values: list[np.ndarray],
        seeds: np.ndarray,
        grid: tuple[int, int],
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Accumulate sparse word components in order, returning bounds and centroids."""
        if len(indices) != len(values) or seeds.shape != (len(indices),):
            raise ValueError("Component rows and seeds must match")
        if (
            grid[0] <= 0
            or grid[1] <= 0
            or any(
                ix.ndim != 1 or v.ndim != 1 or len(ix) != len(v)
                for ix, v in zip(indices, values)
            )
        ):
            raise ValueError("Invalid component grid or sparse row shape")
        density = np.zeros(grid, dtype=np.float64)
        bounds = np.empty((len(indices), 4), dtype=np.int64)
        centers = np.empty((len(indices), 2))
        if not indices:
            return density, bounds, centers
        offsets = np.r_[0, np.cumsum([len(ix) for ix in indices])].astype(np.int64)
        cells = np.ascontiguousarray(np.concatenate(indices), dtype=np.int64)
        mass = np.ascontiguousarray(np.concatenate(values), dtype=np.float32)
        seeds = np.ascontiguousarray(seeds, dtype=np.int64)
        if (
            np.any(cells < 0)
            or np.any(cells >= density.size)
            or np.any(seeds < 0)
            or np.any(seeds >= density.size)
        ):
            raise ValueError("Component cell is outside the attention grid")
        if not self.components_function(
            *grid, len(indices), offsets, cells, mass, seeds, density, bounds, centers
        ):
            raise ValueError("Component seed must have positive finite attention")
        return density, bounds, centers

    def add_component(
        self,
        attention: np.ndarray,
        density: np.ndarray,
        seed: int | None = None,
    ) -> tuple[int, int, tuple[int, int, int, int], np.ndarray]:
        """Normalize the 0.3-threshold peak component using float64 accumulation."""
        if (
            attention.ndim != 2
            or not attention.size
            or attention.dtype != np.float32
            or not attention.flags.c_contiguous
            or density.shape != attention.shape
            or density.dtype != np.float64
            or not density.flags.c_contiguous
            or not density.flags.writeable
        ):
            raise ValueError("Component accumulation needs matching contiguous grids")
        seed = int(attention.argmax()) if seed is None else seed
        if seed < 0 or seed >= attention.size:
            raise ValueError("Component seed is outside the attention grid")
        if not np.isfinite(attention.flat[seed]) or attention.flat[seed] <= 0:
            raise ValueError("Component seed must have positive finite attention")
        bounds = np.empty(4, dtype=np.int64)
        center = np.empty(2)
        self.density_function(
            *attention.shape, attention, seed, density, bounds, center
        )
        y, x = divmod(seed, attention.shape[1])
        return (
            y,
            x,
            (int(bounds[0]), int(bounds[1]), int(bounds[2]), int(bounds[3])),
            center,
        )


@lru_cache(maxsize=1)
def get_rust() -> RustKernels | None:
    """Load only an explicitly configured local shared library."""
    path = os.environ.get(_LIBRARY_ENV)
    return RustKernels(path) if path else None


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", required=True, type=Path)
    args = parser.parse_args()
    args.output.parent.mkdir(parents=True, exist_ok=True)
    subprocess.run(
        [
            "rustc",
            "--crate-type",
            "cdylib",
            "--edition",
            "2021",
            "-O",
            str(Path(__file__).with_name("peak_kernels.rs")),
            "-o",
            str(args.output),
        ],
        check=True,
        timeout=120,
    )
    print(f"Set {_LIBRARY_ENV}={args.output.resolve()}")


if __name__ == "__main__":
    main()