# 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()