Recursive AI

Tree-ensemble operators (ai.onnx.ml)

All onemodel docs

TreeEnsembleRegressor and TreeEnsembleClassifier (domain ai.onnx.ml, opsets 1 to 3, including the *_as_tensor attributes of opset 3), TreeEnsemble (opset 5, with BRANCH_MEMBER) and ZipMap (opset 1). These are what scikit-learn (skl2onnx), XGBoost and LightGBM (onnxmltools) export, with their default options: string class labels and the ZipMap that ends a scikit-learn or LightGBM classifier are supported. A model's other operators in these exports are Cast and Identity (which already ran). The rest of ai.onnx.ml is not implemented.

The text is normative for the kernels. Semantics the ONNX text (Operators-ml.md) leaves open were settled by ONNX Runtime 1.31.1's output on crafted models; where ONNX Runtime contradicts the specification, the specification is followed and the difference is listed under "Differences from ONNX Runtime".

Inputs, outputs, types

  • Input X: float32 or float64, 1-D (read as one row, [1, F]) or 2-D [N, F]. The classifier also takes int32 and int64; the legacy regressor takes them as well (ONNX Runtime does not). float16 is not supported. A feature id >= F is an error at the first run that sees F.
  • Accumulation happens in the input's type: float32 for float32, float64 for float64 (int inputs use float32). Thresholds are compared as doubles.
  • Legacy regressor: Y is float32 [N, n_targets]. Opset 5 TreeEnsemble: Y has the input's type.
  • Legacy classifier: Y the labels [N] (int64 for classlabels_int64s, a string tensor for classlabels_strings), Z float32 scores [N, C].
  • Shapes, attribute lengths, node, tree and class ids and cycles are validated when the session is created, with sizes checked before anything is allocated; errors are SessionException naming the operator and the attribute. The number of targets is limited to 2^20.

Trees

A tree's root is the first node listed for it. Children are found by node id within the tree. Node modes BRANCH_LEQ, BRANCH_LT, BRANCH_GTE, BRANCH_GT, BRANCH_EQ, BRANCH_NEQ and LEAF (opset 5 also BRANCH_MEMBER, true when the feature value is in the node's membership set). A NaN feature takes the true branch when missing_value_tracks_true is set for that node, and otherwise follows IEEE comparison (every comparison false except BRANCH_NEQ).

Aggregation (regressor and opset 5)

For each target the leaf weights of the trees are combined in tree order, then vote order within a tree:

  • SUM: running sum from 0; AVERAGE: the sum divided by the number of trees; MIN, MAX: over the leaf votes. A target that received no vote keeps 0.
  • base_values (length n_targets, or absent) are added after aggregation, to a target only if it got a vote in that row, except that with one target they are always added.
  • post_transform NONE, SOFTMAX, LOGISTIC, SOFTMAX_ZERO and PROBIT are applied elementwise over the targets of a row (softmax over the row).

Classifier

C is the length of classlabels_int64s. Votes are summed per class in the same order.

  • Binary form (C = 2 and every vote is for class 0): s is class 0's sum, plus base_values[0] if class 0 was voted. The scores are [1-s, s] when every leaf weight is non-negative and [-s, s] otherwise. LOGISTIC gives [sigmoid(-s), sigmoid(s)]; SOFTMAX and SOFTMAX_ZERO leave the scores as they are. The label is class 1 when s > 0.5 (all weights non-negative) or s > 0.
  • Votes only for class 1 (C = 2): the label is class 1 when its score is above 0.5 (weights non-negative) or 0.
  • Otherwise: per-class sums; base_values (length C) are added to all classes and mark them scored. The label is the first class with the largest score among scored classes; a row where no class is scored gets label 0. SOFTMAX runs over all classes; SOFTMAX_ZERO leaves classes whose score is exactly 0 out of the sum and outputs 0 for them; LOGISTIC and PROBIT are elementwise.
  • With classlabels_strings the winning class is chosen as above and its string is written to Y; the scores are unchanged.

ZipMap

ZipMap takes float32 scores [N, C] and the attribute classlabels_int64s or classlabels_strings (exactly one, 1 to 2^20 entries, C of them) and makes a sequence of N maps from label to score, in the order the attribute lists the labels. Every map has the same keys. It only moves bits, so it is exact. A score tensor whose column count differs from the label count, whose rank is not 2 or whose type is not float32 is an error when the plan is made.

Strings and maps in a session

The tensor layer has no string type and no map type, and the numeric kernels never see them. A string tensor or a sequence of maps travels through a plan as one opaque rank-1 U8 tensor (the packed-value family of PackedValue, kinds StringTensor and MapSequence; the layout is internal and may change). TensorInfo.Kind says which: TensorInfoKind.StringTensor or TensorInfoKind.SequenceOfMaps.

  • Where they come from. A classifier with classlabels_strings (its output 0), ZipMap, a string graph input and a string initializer. A string initializer is held as a packed string tensor.
  • Where they go. Only Identity takes them (it is a view of its input). Any other operator that would receive one fails when the session is created with SessionErrorKind.UnsupportedOperator, naming the operator, rather than reading garbage. The check follows the values from where they enter through Identity nodes.
  • Size. The output size of a string-label classifier depends on which labels win, so that kernel allocates its outputs when it runs, from the run's arena. Steady-state runs allocate nothing from the heap in the numeric path; reading the result into string[] and dictionaries allocates, as any managed result does.
  • Strings are UTF-8; invalid bytes read back as U+FFFD. The readers check every length against the bytes that remain before allocating, refuse more than 2^29 strings or a key set of no keys, and throw FormatException for cut-short or inconsistent bytes and ArgumentException for a tensor that is not the kind asked for.

Reading them

ModelValues (public) makes and reads the tensors: Strings(values, shape), IsStrings, IsMaps, ReadStrings(value[, out shape]), ReadInt64Maps(value) and ReadStringMaps(value). The maps come back as one IReadOnlyDictionary<TKey, float> per row, enumerating in the model's class order (the order of ONNX Runtime's dictionaries); the rows share the keys. On the happy path Model.RunStrings<TIn>, RunInt64Maps<TIn> and RunStringMaps<TIn> run the model and return one named output; Run<TIn, TOut>(input, shape, outputName) does the same for numeric outputs. A call that names an output of another kind throws a SessionException that says which method reads it. Example: guide/tree-models.md.

Post transforms

SOFTMAX and LOGISTIC use the library's own polynomials for float32 (docs/exact-transcendentals.md). PROBIT is the inverse normal CDF computed in double with the BCL's logarithm, accurate to about 1e-15. ONNX Runtime's PROBIT is an approximation with up to 0.2% relative error in the tails, so oracle cases with PROBIT use a tolerance of 5e-3.

Exact mode and threads

Traversal is comparisons and sums in a fixed order, so fast and exact mode run the same code and give the same bits on every ISA, on one thread or many. Rows are processed in chunks of 32 (a constant), each chunk writing only its own rows. Exact mode refuses, at session creation and naming the operator, PROBIT (the BCL logarithm) and every opset 5 post_transform other than NONE (the opset 5 post transform has no float64 form that is the same everywhere). Steady-state runs allocate nothing.

Not supported

  • Other ai.onnx.ml operators (LabelEncoder, ArrayFeatureExtractor, Binarizer, the scalers, encoders, imputers, SVM and linear models) and string operators in the default domain. Models whose export puts one of these in front of the trees fail at session creation naming the operator.
  • float16 inputs; more than 2^20 targets or classes.
  • A string or map value consumed by anything but Identity (above).
  • The GPU package has no kernels for these operators; a session with Device = Gpu keeps them on the CPU, the node's reason being "not an ONNX-domain operator", and runs the same results. With RequireGpu it fails naming them.

Differences from ONNX Runtime 1.31.1

Found by running crafted models; each is a place where we follow the specification or the intended meaning.

  • Opset 5 post_transform numbering. The specification numbers it NONE 0, SOFTMAX 1, LOGISTIC 2, SOFTMAX_ZERO 3, PROBIT 4. ONNX Runtime applies LOGISTIC for 1 and SOFTMAX for 2. We follow the specification; the oracle cases feed ONNX Runtime the model with 1 and 2 exchanged.
  • Regressor with one target: ONNX Runtime drops a second vote for the same target from one leaf; we sum all votes, as the specification says.
  • Binary PROBIT: ONNX Runtime leaves the second score unset; we give [probit(s), -probit(s)].
  • Two classes with votes for both: ONNX Runtime labels 1 whenever class 1's score is positive, and some rows read uninitialised memory; we take the argmax.
  • No class scored: ONNX Runtime reports an error; we give label 0.
  • Opset 5 attribute tensors: ONNX Runtime wants them in the input's type, integral membership values and non-empty membership sets; we accept any numeric type and empty sets.

Checks

tools/ml_oracle.py builds the cases and runs ONNX Runtime 1.31.1 on them: testdata/ops-ml/cases.json.gz (227 cases: scikit-learn trees, forests and gradient boosting through skl2onnx with ZipMap off; XGBoost and LightGBM through onnxmltools; hand-built graphs for every mode, aggregate, post transform and opset) and testdata/ops-ml/default-exports.json.gz (210 cases: every classifier and regressor of the matrix below exported with the exporters' default options). The matrix: scikit-learn DecisionTree, RandomForest, ExtraTrees, GradientBoosting and HistGradientBoosting, classifiers (binary and multi-class, integer and string labels, with ZipMap as the default and without) and regressors; XGBoost classifiers (binary, multi-class) and regressor; LightGBM classifiers (binary, multi-class, integer and string labels, with and without ZipMap) and regressor; all on synthetic data, each at ml opsets 1 and 3 and with and without NaN rows. HistGradientBoosting* needs one adaptation: skl2onnx 1.20.0 hands booleans to an integer-list attribute, which the onnx package refuses, so the generator converts those to 0/1 while exporting.

MlOracleTests runs each case in both modes on every kernel path and on 1 and 4 threads: labels and strings equal, map keys equal in order, scores within the case tolerance, exact results bit-identical across paths and threads. EveryDefaultExportIsReadableThroughTheHappyPath reads every output of every classifier case through Model.Load and the accessor for its kind. The operators seen in the default exports are TreeEnsembleClassifier, TreeEnsembleRegressor, ZipMap, Cast (int64 labels) and Identity (string labels, LightGBM's renamed outputs).

Errors against ONNX Runtime (fast mode, one thread; scaled = max abs error / max abs reference value, at least 1e-3) by case group. The probabilities of ZipMap cases are the map values:

Case groupCasesMax abs errorMax scaled errorLabel outputs differing
cls_C3167.45E-0089.84E-0080
cls_C3 (PROBIT)44.16E-0042.36E-0040
cls_C5165.96E-0087.65E-0080
cls_C5 (PROBIT)41.67E-0037.65E-0040
cls_binary197.82E-0088.07E-0080
cls_double25.96E-0086.20E-0080
cls_float12.98E-0083.52E-0080
cls_forest15.96E-0086.01E-0080
cls_int3210.00E+0000.00E+0000
cls_int6410.00E+0000.00E+0000
cls_unvoted125.96E-0081.04E-0070
onnxmltools_LGBMClassifier87.45E-0088.90E-0080
onnxmltools_LGBMRegressor40.00E+0000.00E+0000
onnxmltools_XGBClassifier81.19E-0071.22E-0070
onnxmltools_XGBRegressor80.00E+0000.00E+0000
onnxmltools_default_LGBMClassifier int labels, ZipMap85.96E-0088.20E-0080
onnxmltools_default_LGBMClassifier int labels, no ZipMap85.96E-0088.20E-0080
onnxmltools_default_LGBMClassifier string labels, ZipMap85.96E-0088.20E-0080
onnxmltools_default_LGBMClassifier string labels, no ZipMap85.96E-0088.20E-0080
onnxmltools_default_LGBMRegressor20.00E+0000.00E+0000
onnxmltools_default_XGBClassifier int labels45.96E-0086.56E-0080
onnxmltools_default_XGBRegressor20.00E+0000.00E+0000
reg_AVERAGE50.00E+0000.00E+0000
reg_MAX50.00E+0000.00E+0000
reg_MIN50.00E+0000.00E+0000
reg_SUM50.00E+0000.00E+0000
reg_accumulation30.00E+0000.00E+0000
reg_double40.00E+0000.00E+0000
reg_empty10.00E+0000.00E+0000
reg_float10.00E+0000.00E+0000
reg_forest10.00E+0000.00E+0000
reg_input10.00E+0000.00E+0000
reg_leaf10.00E+0000.00E+0000
reg_mode120.00E+0000.00E+0000
reg_post45.96E-0087.97E-0080
reg_post (PROBIT)13.76E-0042.15E-0040
skl2onnx_DecisionTreeClassifier80.00E+0000.00E+0000
skl2onnx_DecisionTreeRegressor80.00E+0000.00E+0000
skl2onnx_GradientBoostingClassifier85.96E-0087.79E-0080
skl2onnx_GradientBoostingRegressor40.00E+0000.00E+0000
skl2onnx_RandomForestClassifier80.00E+0000.00E+0000
skl2onnx_RandomForestRegressor80.00E+0000.00E+0000
skl2onnx_default_DecisionTreeClassifier int labels, ZipMap80.00E+0000.00E+0000
skl2onnx_default_DecisionTreeClassifier int labels, no ZipMap80.00E+0000.00E+0000
skl2onnx_default_DecisionTreeClassifier string labels, ZipMap80.00E+0000.00E+0000
skl2onnx_default_DecisionTreeClassifier string labels, no ZipMap80.00E+0000.00E+0000
skl2onnx_default_DecisionTreeRegressor20.00E+0000.00E+0000
skl2onnx_default_ExtraTreesClassifier int labels, ZipMap80.00E+0000.00E+0000
skl2onnx_default_ExtraTreesClassifier int labels, no ZipMap80.00E+0000.00E+0000
skl2onnx_default_ExtraTreesClassifier string labels, ZipMap80.00E+0000.00E+0000
skl2onnx_default_ExtraTreesClassifier string labels, no ZipMap80.00E+0000.00E+0000
skl2onnx_default_ExtraTreesRegressor20.00E+0000.00E+0000
skl2onnx_default_GradientBoostingClassifier int labels, ZipMap85.96E-0088.43E-0080
skl2onnx_default_GradientBoostingClassifier int labels, no ZipMap85.96E-0088.43E-0080
skl2onnx_default_GradientBoostingClassifier string labels, ZipMap85.96E-0088.43E-0080
skl2onnx_default_GradientBoostingClassifier string labels, no ZipMap85.96E-0088.43E-0080
skl2onnx_default_GradientBoostingRegressor20.00E+0000.00E+0000
skl2onnx_default_HistGradientBoostingClassifier int labels, ZipMap85.96E-0088.10E-0080
skl2onnx_default_HistGradientBoostingClassifier int labels, no ZipMap85.96E-0088.10E-0080
skl2onnx_default_HistGradientBoostingClassifier string labels, ZipMap85.96E-0088.10E-0080
skl2onnx_default_HistGradientBoostingClassifier string labels, no ZipMap85.96E-0088.10E-0080
skl2onnx_default_HistGradientBoostingRegressor20.00E+0000.00E+0000
skl2onnx_default_RandomForestClassifier int labels, ZipMap80.00E+0000.00E+0000
skl2onnx_default_RandomForestClassifier int labels, no ZipMap80.00E+0000.00E+0000
skl2onnx_default_RandomForestClassifier string labels, ZipMap80.00E+0000.00E+0000
skl2onnx_default_RandomForestClassifier string labels, no ZipMap80.00E+0000.00E+0000
skl2onnx_default_RandomForestRegressor20.00E+0000.00E+0000
v5_f32135.96E-0088.07E-0080
v5_f32 (PROBIT)12.37E-0031.01E-0030
v5_f64135.23E-0088.39E-0080
v5_f64 (PROBIT)12.86E-0031.16E-0030
v5_set10.00E+0000.00E+0000

The table is reproducible with ONEMODEL_ML_REPORT=<file> set while running MlOracleTests. The largest errors are the PROBIT groups (ONNX Runtime's approximation); the rest are float32 rounding or zero, and every label, string and key order is equal. The two backend cases test_ai_onnx_ml_tree_ensemble_set_membership and _single_tree pass in both modes (docs/conformance.md); the pinned backend data and the onnx 1.23.2 case generator have no case for ZipMap.