Treelite

repository·mainline·Indexed 21 days ago

https://github.com/dmlc/treelite

A 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.

Tokens
20.8K
Snippets
54
Records
86
Agent score
71%

What's inside treelite

  1. What is Treelite?

    mainline
    Treelite 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.
  2. Treelite C API functional interfaces

    mainline

    The 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.
  3. What is the General Tree Inference Library (GTIL)?

    mainline
    GTIL 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.
  4. Handling Multi-target and Multi-class Models in v4

    mainline

    In 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_scores are shaped using the largest number of classes (max_num_class), and extra elements are padded with 0.
    • 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.
  5. Rules for using TreeAccessor.set_field safely

    mainline

    When using treelite.model.TreeAccessor.set_field to 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's dtype matches the model specification (e.g., use np.int32 for num_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 (like node_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.

  6. Understand the Treelite Serialization Format v3

    mainline

    The 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., float or double).
    • LeafOutputType: The type used for leaf values (e.g., uint32_t or float).

    Allowed combinations:

    • float threshold / uint32_t leaf
    • float threshold / float leaf
    • double threshold / uint32_t leaf
    • double threshold / double leaf
  7. What are postprocessor functions in Treelite

    mainline

    When 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:

    1. Element-wise: Applied to each individual score in the margin score vector independently.
    2. Row-wise: Applied across all scores in a single row (typically used for multiclass classification to ensure probabilities sum to 1).
  8. Use the ModelBuilder to specify custom tree ensembles

    mainline
    If you are using a tree library that is not directly supported by Treelite (unlike XGBoost or scikit-learn), you can use the treelite.model_builder.ModelBuilder class to specify decision tree ensembles programmatically. This allows you to manually define the structure and parameters of your model.
  9. Query and modify model fields using Accessors (Advanced)

    mainline

    For advanced users, Treelite provides HeaderAccessor and TreeAccessor to query and modify the internal fields of a treelite.Model object.

    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.

  10. Treelite Serialization Format v4 Overview

    mainline

    The 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.