Treelite
repository·mainline·Indexed 21 days ago
https://github.com/dmlc/treeliteA universal model exchange and serialization format for decision tree forests, designed to enable C++ applications to store and exchange tree-based models efficiently on disk or over a network. It supports multiple serialization formats (v3 and v4), various postprocessor functions for regression and classification, and provides installation options via PyPI, Conda, or source compilation.
What's inside treelite
- Treelite is a universal model exchange and serialization format specifically designed for decision tree forests. It allows for efficient representation and deployment of tree-based models.
What is Treelite?
mainlineTreelite is a universal model exchange and serialization format designed specifically for decision tree forests. It is intended to be a lightweight library that allows C++ applications to exchange and store decision tree models on disk or across a network.Treelite C API functional interfaces
mainlineThe Treelite C API is organized into several functional interfaces depending on the task:
- Model loader interface: Functions to load decision tree ensemble models from various supported file formats.
- Model loader interface for scikit-learn models: Specialized functions to load models directly from scikit-learn model objects.
- Model builder interface: Functions to incrementally build decision tree ensemble models.
- Model manager interface: Functions for managing model lifecycles.
- Serializer: Functions for serializing and deserializing models.
- Getters and setters for the model object: Accessor functions to retrieve or modify model properties.
- General Tree Inference Library (GTIL): Interface for tree inference operations.
What is the General Tree Inference Library (GTIL)?
mainlineGTIL is a reference implementation of a prediction runtime for all Treelite models. It is designed to provide universal coverage for all tree ensemble models representable as Treelite objects. Its primary goals are code legibility (making it accessible to first-time contributors) and ensuring correct prediction outputs as a baseline reference implementation.What is the ModelBuilder?
mainlineThetreelite.model_builder.ModelBuilderclass is a programmatic tool used to construct decision tree ensembles. It is primarily used when you need to load or define models from tree libraries that do not have native Treelite support.Handling Multi-target and Multi-class Models in v4
mainlineIn v4, multi-target and multi-class models are handled using a specific shaping heuristic to ensure compatibility with vector-leaf outputs:
- Leaf Vector Shape: The shape is defined as
(num_target, max(num_class)). - Padding: If different targets have different numbers of classes, the leaf vectors and
base_scoresare shaped using the largest number of classes (max_num_class), and extra elements are padded with0. - Implication: If one target has significantly more classes than others, it may result in wasted space due to padding. This follows the same method used by
sklearn.ensemble.RandomForestClassifier.
- Leaf Vector Shape: The shape is defined as
Rules for using TreeAccessor.set_field safely
mainlineWhen using
treelite.model.TreeAccessor.set_fieldto modify tree structures, follow these rules to prevent errors and silent crashes:- Always use NumPy arrays: Even when setting a scalar field, pass a NumPy array (e.g.,
np.array([val])). - Match the correct
dtype: Ensure the array'sdtypematches the model specification (e.g., usenp.int32fornum_feature). - Match array length to
num_nodes: Most tree fields must be arrays of length exactly equal to the number of nodes in the tree. Providing a shorter array will likely cause undefined behavior. - Update all related fields when adding nodes: If you manually increase the number of nodes by updating
num_nodes, you must also update every other field in the tree (likenode_type,cleft,cright,leaf_value, etc.) to match the new node count.
Best Practice: Avoid changing the number of nodes if possible. Operations like re-numbering feature IDs or changing leaf outputs are significantly safer than structural changes.
- Always use NumPy arrays: Even when setting a scalar field, pass a NumPy array (e.g.,
Understand the Treelite Serialization Format v3
mainlineThe Treelite Serialization Format v3 is a binary format used to represent tree-based models. A serialized model consists of a header, global model parameters, and a sequence of trees. Each tree contains a collection of nodes, leaf vectors, and optional categorical data.
Model Configuration Types The model's precision is determined by two template parameters:
ThresholdType: The type used for split thresholds (e.g.,floatordouble).LeafOutputType: The type used for leaf values (e.g.,uint32_torfloat).
Allowed combinations:
floatthreshold /uint32_tleaffloatthreshold /floatleafdoublethreshold /uint32_tleafdoublethreshold /doubleleaf
What are postprocessor functions in Treelite
mainlineWhen predicting with tree ensemble models, Treelite sums the margin scores from individual trees. A postprocessor function (also known as a link function) is applied to this sum to transform the raw margin scores into the final prediction format (e.g., probabilities or raw values).
Postprocessors are categorized into two types:
- Element-wise: Applied to each individual score in the margin score vector independently.
- Row-wise: Applied across all scores in a single row (typically used for multiclass classification to ensure probabilities sum to 1).
Use the ModelBuilder to specify custom tree ensembles
mainlineIf you are using a tree library that is not directly supported by Treelite (unlike XGBoost or scikit-learn), you can use thetreelite.model_builder.ModelBuilderclass to specify decision tree ensembles programmatically. This allows you to manually define the structure and parameters of your model.Query and modify model fields using Accessors (Advanced)
mainlineFor advanced users, Treelite provides
HeaderAccessorandTreeAccessorto query and modify the internal fields of atreelite.Modelobject.Warning: Unsafe Operation Modifying fields via accessors is an unsafe operation. Treelite does not validate the values assigned to fields, and setting invalid values (e.g., an array of incorrect length for
num_nodes) may cause undefined behavior. Always verify field constraints against the model specification (e.g.,serialization/v4) before modification.Treelite Serialization Format v4 Overview
mainlineThe Treelite v4 serialization format is designed for high-performance model deployment with the following key features:
- Multi-target support: First-class support for models with multiple targets.
- Boosting from the average: Supports scikit-learn style initialization where a base estimator (fitted from class distribution or average label) is used as the initial learner.
- Fixed-width integer types: Uses explicit widths (e.g.,
int32_t) for predictable cross-platform serialization.
Important Implementation Note: Always use little-endian byte order when reading or writing scalars and arrays.