# 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 native kernels; build explicitly, then set OCRIA_GROUNDING_NATIVE.""" import argparse import ctypes from functools import lru_cache import os from pathlib import Path import subprocess import numpy as np # Matches TreeNode in native_kernels.cpp: two doubles and four 32-bit integers. # Flags use bit 0 for missing-go-left and bit 1 for leaves. TREE_NODE_DTYPE = np.dtype( [ ("value", np.float64), ("threshold", np.float64), ("feature", np.int32), ("left", np.int32), ("right", np.int32), ("flags", np.int32), ], align=True, ) _LIBRARY_ENV = "OCRIA_GROUNDING_NATIVE" class NativeKernels: """Own a trusted shared library and its typed, contiguous-array interfaces.""" def __init__(self, path: str) -> None: self.library = ctypes.CDLL(path) double = np.ctypeslib.ndpointer(np.float64, flags="C_CONTIGUOUS") integer = np.ctypeslib.ndpointer(np.int32, flags="C_CONTIGUOUS") boolean = np.ctypeslib.ndpointer(np.bool_, flags="C_CONTIGUOUS") self.library.neighborhood.argtypes = [ ctypes.c_int, ctypes.c_int, double, double, integer, integer, double, ] self.library.pool_profiles.argtypes = [ ctypes.c_int, ctypes.c_int, double, integer, integer, integer, double, double, ] self.library.peak_component.argtypes = [ ctypes.c_int, ctypes.c_int, boolean, ctypes.c_int, boolean, ] self.library.peak_component_bounds.argtypes = [ *self.library.peak_component.argtypes, integer, ] self.library.predict_compact_trees.argtypes = [ ctypes.c_int, ctypes.c_int, double, ctypes.c_int, integer, np.ctypeslib.ndpointer(TREE_NODE_DTYPE, flags="C_CONTIGUOUS"), ctypes.c_double, double, ] self.library.component_boxes.argtypes = [ ctypes.c_int, ctypes.c_int, boolean, integer, ] self.library.component_boxes.restype = ctypes.c_int self.library.box_maxima.argtypes = [ ctypes.c_int, double, ctypes.c_int, integer, double, ] self.library.box_maxima.restype = None self.library.mass_boxes.argtypes = [ ctypes.c_int, ctypes.c_int, double, ctypes.c_int, double, double, ] self.library.mass_boxes.restype = None for name in ( "neighborhood", "pool_profiles", "peak_component", "peak_component_bounds", "predict_compact_trees", ): getattr(self.library, name).restype = None def neighborhood( self, positions: np.ndarray, lengths: list[int], owners: dict[int, int], valid: list[int], ) -> np.ndarray: """Return 19 contextual features per valid word, preserving unit indices.""" owner_array = np.full(len(positions), -1, dtype=np.int32) for u, owner in owners.items(): owner_array[u] = owner out = np.empty((len(valid), 19)) self.library.neighborhood( len(positions), len(valid), positions, np.asarray(lengths, dtype=np.float64), owner_array, np.asarray(valid, dtype=np.int32), out, ) return out def pool_profiles( self, positions: np.ndarray, owners: dict[int, int], valid: list[int], profiles: np.ndarray, ) -> np.ndarray: """Return seven pooled profile bins and a neighbor count per valid word.""" owner_array = np.full(len(positions), -1, dtype=np.int32) for u, owner in owners.items(): owner_array[u] = owner inverse = np.full(len(positions), -1, dtype=np.int32) inverse[valid] = np.arange(len(valid), dtype=np.int32) out = np.empty((len(valid), 8)) self.library.pool_profiles( len(positions), len(valid), positions, owner_array, np.asarray(valid, dtype=np.int32), inverse, profiles, out, ) return out def mass_boxes( self, density: np.ndarray, quantiles: list[float] ) -> list[list[float]]: """Compute cell-edge mass boxes while sharing the marginal reductions.""" density = np.ascontiguousarray(density, dtype=np.float64) levels = np.asarray(quantiles, dtype=np.float64) if density.ndim != 2 or 0 in density.shape or levels.ndim != 1: raise ValueError( "Expected a nonempty density and one-dimensional quantiles" ) out = np.empty((len(levels), 4)) self.library.mass_boxes(*density.shape, density, len(levels), levels, out) return out.tolist() def box_maxima(self, density: np.ndarray, bounds: np.ndarray) -> np.ndarray: """Reduce clipped nonempty cell-edge rectangles without per-box calls.""" density = np.ascontiguousarray(density, dtype=np.float64) bounds = np.ascontiguousarray(bounds, dtype=np.int32) if density.ndim != 2 or bounds.ndim != 2 or bounds.shape[1] != 4: raise ValueError("Expected a two-dimensional density and N x 4 bounds") limits = np.array([density.shape[1], density.shape[0]]) if ( np.any(bounds[:, :2] < 0) or np.any(bounds[:, 2:] > limits) or np.any(bounds[:, 2:] <= bounds[:, :2]) ): raise ValueError("Bounds must be clipped and nonempty") out = np.empty(len(bounds)) self.library.box_maxima(density.shape[1], density, len(bounds), bounds, out) return out def component_boxes(self, mask: np.ndarray) -> np.ndarray: """Return eight-connected component edges in row-major seed order.""" if mask.ndim != 2: raise ValueError("Component mask must be two-dimensional") mask = np.ascontiguousarray(mask, dtype=np.bool_) bounds = np.empty((mask.size, 4), dtype=np.int32) count = self.library.component_boxes(*mask.shape, mask, bounds) return bounds[:count] def peak_component_bounds( self, mask: np.ndarray, y: int, x: int ) -> tuple[np.ndarray, tuple[int, int, int, int]]: """Return the peak component and exclusive cell bounds in x/y order.""" out = np.zeros_like(mask) bounds = np.empty(4, dtype=np.int32) self.library.peak_component_bounds( *mask.shape, mask, int(y * mask.shape[1] + x), out, bounds ) return out, (int(bounds[0]), int(bounds[1]), int(bounds[2]), int(bounds[3])) def peak_component(self, mask: np.ndarray, y: int, x: int) -> np.ndarray: """Flood the true peak's eight-connected component in a boolean grid.""" out = np.zeros_like(mask) self.library.peak_component(*mask.shape, mask, int(y * mask.shape[1] + x), out) return out @lru_cache(maxsize=1) def get_native() -> NativeKernels | None: """Read the opt-in library path once; an invalid explicit path fails visibly.""" path = os.environ.get(_LIBRARY_ENV) return NativeKernels(path) if path else None def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", required=True, type=Path) parser.add_argument("--compiler", default="c++") args = parser.parse_args() source = Path(__file__).with_name("native_kernels.cpp") args.output.parent.mkdir(parents=True, exist_ok=True) # Disable fused arithmetic so feature rounding matches the NumPy reference. subprocess.run( [ args.compiler, "-O3", "-std=c++17", "-ffp-contract=off", "-shared", "-fPIC", str(source), "-o", str(args.output), ], check=True, timeout=120, ) print(f"Set {_LIBRARY_ENV}={args.output.resolve()}") if __name__ == "__main__": main()