PMML is still the only vendor-neutral format that survives a round-trip between data science (sklearn, XGBoost, LightGBM, Spark, R → PMML via standard converters) and production. pmmlruntime is a from-scratch Rust inference engine for that format — session-based like ONNX Runtime, tiny like tract, hardened like a browser XML parser.
Highlights
- Complete PMML 4.4 — 19 model types, full
DataDictionary/MiningSchema/Targets/Outputsemantics (see Coverage). - Session API —
PmmlEnv+Session+Batch. ImmutableArc<Ir>,Send + Sync, sharded by aCpuExecutionProvider. - Two layouts, one method —
HashMap<String, Value>for single rows,RecordBatch(Arrow) for columnar batches. Samesess.run(&batch as &dyn Batch). - Zero-copy, zero-alloc hot path —
FieldId/SymbolIdinterned once,&[Value]materialized per row in a stack buffer (≤64fields) or athread_local!bump buffer; noHashMapper row for Arrow. - Parallel by default —
rayonauto-shard on theCpuprovider.SIMD(widef64x4) for regression batches whenfeatures = ["simd"]. - Hardened XML —
quick-xml 0.37,MAX_DEPTH 512, 100 MB cap, DTD/XXE blocked, fuzzed (cargo fuzz),miriclean,proptestgenerators. - Embeds everywhere — pure Rust, optional
python(pyo3 0.22) andCABI (opaquePmmlEnv/PmmlSessionhandles). - Apache-2.0 — commercial-friendly. MSRV 1.78, stable toolchain,
no_std-ready core.
Installation
Rust
[]
= "0.1"
# optional SIMD for f64 batch
# pmmlruntime = { version = "0.1", features = ["simd"] }
# with SIMD
Python (extension-module, libpython only with python feature)
= { = "0.1", = ["python"] }
Prerequisites: Rust 1.78+ (rustup update), no JDK, no Python at runtime.
Quickstart
Rust — single row
use HashMap;
use ;
use Batch;
use Value;
Rust — Arrow batch (zero-copy)
use ;
use Batch;
use Arc;
use Float64Array;
use ;
use RecordBatch;
let env = new;
let sess = from_file?;
let schema = new;
let batch = try_new?;
// same `run` — provider detects Columnar, uses col_map + rayon + optional SIMD
let results = sess.run?.into_rows;
for row in &results
Unified PMML — LightGBM / XGBoost / sklearn, same code
After conversion there is no "LightGBM PMML" or "XGBoost PMML". Converters for LightGBM, XGBoost, sklearn and R all emit one PMML 4.4 MiningModel (usually Segmentation with multipleModelMethod="sum" or "modelChain" over TreeModel/RegressionModel stumps). The scorer never knows the origin.
# Train anywhere, score the same way
See crates/pmmlruntime/examples/score_file.rs — it prints the model kind (TreeModel vs MiningModel with N segments), handles CSV → RecordBatch via csv_str_to_record_batch, and writes predictedValue + Output fields.
Coverage
Models — 19/19
| Model | PMML element | Status |
|---|---|---|
| Tree | TreeModel |
✓ |
| Regression | RegressionModel |
✓ |
| Mining (ensemble / chain) | MiningModel + Segmentation |
✓ (majorityVote, weightedAverage, modelChain, selectFirst, selectAll, …) |
| Scorecard | Scorecard |
✓ (reason codes, pointsAbove/pointsBelow) |
| Clustering | ClusteringModel |
✓ (euclidean, squaredEuclidean) |
| Naive Bayes | NaiveBayesModel |
✓ (discrete PairCounts + continuous GaussianDistribution) |
| k-NN | NearestNeighborModel |
✓ (InlineTable instances) |
| SVM | SupportVectorMachineModel |
✓ (RBF exp(-γ‖x-sv‖²)) |
| Neural Network | NeuralNetwork |
✓ (layers → neurons, logistic/tanh/identity) |
| General Regression | GeneralRegressionModel |
✓ (PPMatrix/ParamMatrix, factors/covariates) |
| Association Rules | AssociationModel |
✓ |
| Rule Set | RuleSetModel |
✓ (ordered SimpleRule, defaultScore) |
| Text | TextModel |
✓ |
| Time Series | TimeSeriesModel |
✓ (ARIMA, ExponentialSmoothing, GARCH, StateSpace, Spectral) |
| Anomaly Detection | AnomalyDetectionModel |
✓ (iforest, clusterMeanDist) |
| Bayesian Network | BayesianNetworkModel |
✓ |
| Gaussian Process | GaussianProcessModel |
✓ |
| Sequence | SequenceModel |
✓ |
| Baseline (change detection) | BaselineModel |
✓ (zValue, CUSUM, chiSquare, …) |
Every model honors MiningSchema (active/predicted/supplementary), Targets (rescale/cast/default), and Output (20+ ResultFeatures: predictedValue, probability, confidence, entityId, reasonCode, decisionPath, …).
Transforms & expressions
Pooled, topologically sorted DerivedField + TransformationDictionary, compiled to a Vec<Op> bytecode VM:
Apply (80+ builtins via BuiltinId: arithmetic, trig, min/max/median, modulo/hypot, strings uppercase/lowercase/substring/matches/replace, dates via chrono, distributions normalCDF/erf via statrs/libm, …) · MapValues (single + multi-input hash lookup) · Discretize · NormContinuous/NormDiscrete · Lag (with Avg/Min/Max/Sum window) · TextIndex · aggregates (count/sum/avg/min/max) · DefineFunction stubs.
Spec references are pmml.xsd line-accurate (e.g., AnomalyDetectionModel 1718–1737, BaselineModel 3659–3815).
Architecture
bytes ──▶ RawPmml ──▶ Ir ──▶ Session::run(&dyn Batch)
(quick-xml, (lower + verify, (Value[FieldId] + Cpu provider)
hardened) Arc, topologically
sorted, Vec<Op>)
base— zero-costValue(Continuous(f64)/Discrete(SymbolId)/Missing),FieldId(u32)/SymbolId(u32),DataType/OpType,BumpArena,PmmlError.xml— cold path only:quick-xml 0.37→RawPmml.MAX_XML_SIZE 100 MB,MAX_DEPTH 512, DTD/XXE rejected.ir— optimizedIr:Arcimmutable,Vec<NodeIr>flat (root 0) for trees,DerivedFieldIrDAG withVec<Op>bytecode,Rodeointerning cold.lower(RawPmml) → Ir,verify_raw/verify_ir.engine— pure evaluation on&[Value]: 19 model evaluators +transform::vm+ optionalsimd(widef64x4).session— ergonomic runtime:PmmlEnv(cheapArcclone),Session::from_bytes/from_file,Session::run(&dyn Batch) → BatchResult,Batch/BatchCtx/ExecutionProvider::Cpu(rayon auto serial vs parallel),arrowhelpers (csv_str_to_record_batch,value_maps_to_record_batch).ffi/python—CABI (opaquePmmlEnv/PmmlSession,PmmlStatusCode) andpyo3 0.22placeholder (features = ["python"]).
Concurrency: Session is Send + Sync. Scoring is &self and uses a ≤64-field stack buffer (L1-hot, 1 KB) or a thread_local! heap buffer — no per-row allocation, safe to share one Session across threads.
Performance
| Path | Input | Notes |
|---|---|---|
Cold from_bytes |
Iris 2.9 KB → Ir → Session |
~68 µs (XML 0.37 + verify + lower) |
Hot run single row |
&HashMap<String, Value> |
~402 ns (stack Value[64], no alloc) |
| Batch 100 k rows | RecordBatch |
Arrow col_map + rayon sharding; simd regression f64x4 when features = ["simd"] |
Stack threshold 64 covers ~90% of fixtures (Iris 3, Diabetes 8, Shopping 22). Larger models spill to a thread_local Vec<Value> that only grows. Numbers are single-threaded on a desktop x86_64; treat them as order-of-magnitude, not guarantees. Run cargo test -- --nocapture for the fixture bench harness.
Security & Correctness
- XML hardening — depth, size, and entity caps enforced in
xml::reader;cargo test --test hardeningandcargo fuzzcoverfuzz_unmarshal(60 s, 1 M execs,rss_limit_mb=2048). - Fuzz + miri + proptest —
fuzz/fuzz_targets/fuzz_unmarshal.rs,cargo +nightly miri test -p pmmlruntime,proptestfor round-trip invariants (CI runs all three). - 52 PMML fixtures in
bench/pmml/(decision trees, gradient boosters, mining chains, anomaly/baseline, text/sequence/time-series, …) plusall_fixturesparity tests (unsupported markup →SKIP, notFAIL). - Pedantic clippy —
-W clippy::pedantic -D warningson workspace + all targets,rustfmtchecked.
API Overview
// Construct once (cold), share everywhere
let env = new;
let sess = from_bytes?;
let sess = from_file?;
// Introspect
sess.num_active_fields // MiningSchema active count
sess.field_id // Option<FieldId> — for Value[FieldId] fast path
sess.symbol_id // Option<SymbolId>
sess.string_to_value // DataType/OpType-aware Value
&sess.ir.field_names // FieldId → name
&sess.ir.symbol_names // SymbolId → string
&sess.ir.model // ModelIr::Tree | Mining | ...
// Score — one method, any layout
let out: = sess.run?.into_single.unwrap;
let rows: = sess.run?.into_rows;
let rows = sess.run?.into_rows;
let batch: RecordBatch = sess.run?.into_record_batch?;
Batchis object-safeSend + Sync: impls forHashMap<String, Value>,Vec<HashMap<_, _>>,[HashMap<_, _>],RecordBatch.BatchResult::Rows(Vec<HashMap<String, Value>>)today;.into_record_batch(schema)converts when you need Arrow output.SessionOptions { graph_optimization_level, intra_op_num_threads }— forwarded to theCpuprovider.
C ABI
PmmlEnv *env = NULL;
;
PmmlSession *sess = NULL;
;
// … scoring via PmmlRun* (planned)
;
;
Python
# "pmml-runtime" — InferenceSession planned
Examples
# Inspect any PMML (LightGBM / XGBoost / sklearn — same binary)
# Batch CSV → scored CSV
# input.csv: header row matching MiningSchema active fields, e.g. Petal.Length,Petal.Width
Developing
# miri (nightly)
# fuzz (nightly, 60 s)
Project layout:
crates/pmmlruntime/src/{base,xml,ir,engine,session,ffi,python}
bench/pmml/*.pmml # 52 fixtures
crates/pmmlruntime/examples/score_file.rs
crates/pmmlruntime/tests/ # all_fixtures, hardening, knn/nn/regression/svm/…
fuzz/fuzz_targets/fuzz_unmarshal.rs
License
Apache-2.0 — see LICENSE.
Acknowledgments
PMML spec by DMG. Design inspiration from JPMML-Evaluator and ONNX Runtime — the former for PMML evaluation semantics and completeness, the latter for the session/env/provider API (PmmlEnv/Session/Batch/ExecutionProvider). XML via quick-xml, Arrow via arrow-rs, numerics via statrs/libm, interning via lasso.