# 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. """Native prediction for compatible fitted histogram regressors.""" from typing import Protocol from weakref import WeakKeyDictionary import numpy as np from .native import TREE_NODE_DTYPE, get_native class Predictor(Protocol): def predict(self, features: np.ndarray) -> np.ndarray: ... # Keep model lifetime and packed-tree lifetime aligned. A refit replaces _predictors. _PACKED: WeakKeyDictionary = WeakKeyDictionary() def predict(model: Predictor, features: np.ndarray) -> np.ndarray: """Preserve the model's normal path unless its numerical trees are supported.""" native = get_native() if native is None: return model.predict(features) from sklearn.ensemble import HistGradientBoostingRegressor from sklearn.pipeline import Pipeline if type(model) is Pipeline and isinstance( model.steps[-1][1], HistGradientBoostingRegressor ): transformed = ( model[:-1].transform(features) if len(model.steps) > 1 else features ) return predict(model.steps[-1][1], transformed) if not isinstance(model, HistGradientBoostingRegressor): return model.predict(features) if ( model._preprocessor is not None or model._loss.link.__class__.__name__ != "IdentityLink" ): return model.predict(features) packed = _PACKED.get(model) if packed is None or packed[0] is not model._predictors: roots, nodes, offset = [], [], 0 for stage in model._predictors: if len(stage) != 1 or stage[0].nodes["is_categorical"].any(): return model.predict(features) tree = stage[0].nodes roots.append(offset) packed_tree = np.empty(len(tree), dtype=TREE_NODE_DTYPE) packed_tree["value"] = tree["value"] packed_tree["threshold"] = tree["num_threshold"] packed_tree["feature"] = tree["feature_idx"] packed_tree["left"] = tree["left"] + offset packed_tree["right"] = tree["right"] + offset packed_tree["flags"] = tree["missing_go_to_left"] | (tree["is_leaf"] << 1) nodes.append(packed_tree) offset += len(tree) packed = ( model._predictors, np.asarray(roots, dtype=np.int32), np.ascontiguousarray(np.concatenate(nodes)), float(model._baseline_prediction[0, 0]), ) _PACKED[model] = packed values = np.ascontiguousarray(features, dtype=np.float64) if ( values.ndim != 2 or values.shape[1] != model.n_features_in_ or not len(values) or np.isinf(values).any() ): return model.predict(features) out = np.empty(len(values)) native.library.predict_compact_trees( len(values), values.shape[1], values, len(packed[1]), packed[1], packed[2], packed[3], out, ) return out