timber

kossisoroyce更新放缓

把 XGBoost、LightGBM、scikit-learn、CatBoost 和 ONNX 模型一键编译成原生 C99 推理代码,省去 Python 运行时开销,推理速度最高提升 336 倍。

Ollama for classical ML models. AOT compiler that turns XGBoost, LightGBM, scikit-learn, CatBoost & ONNX models into native C99 inference code. One command to load, one command to serve. 336x faster than Python inference.

v0.6.0发布于 2026-04-16 16:06 UTC690star23fork同步于 2026-11-07 07:31 UTC

怎么上手

由 README 提炼,执行前请确认
pip install timber-compiler
timber serve https://yourhost.com/models/fraud_model.json
硬件要求按 README 说明

README 未说明显存要求;编译产物面向 x86_64、AArch64、ARM Cortex-M4/M7、ESP32、STM32 等目标,GPU 后端支持 CUDA(SM 7.5/8.6)、Apple Metal(M1+)与 OpenCL

支持 Apple Silicon需要 CUDA
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

把 XGBoost、LightGBM、sklearn 等经典 ML 模型编译成原生 C99 推理代码,一条命令即可加载并启动服务

把 XGBoost、LightGBM、scikit-learn、CatBoost 和 ONNX 模型一键编译成原生 C99 推理代码,省去 Python 运行时开销,推理速度最高提升 336 倍。

核心能力

  • 将训练好的模型编译为自包含的 C99 推理产物,运行时零依赖
  • 内置 Ollama 兼容 HTTP API,一条命令即可启动服务
  • 多遍优化:死叶消除、阈值量化、常量特征折叠、分支排序
  • 支持 XGBoost、LightGBM、sklearn、CatBoost、ONNX 及 URDF 输入
  • timber accel 可生成 AVX2/AVX-512/NEON/CUDA/Metal/FPGA/嵌入式目标代码

容易踩的坑

编译阶段依赖 gcc 或 clang 生成共享库;CatBoost 需先以 JSON 格式导出模型;默认服务端口为 11434,可能与已占用的 Ollama 冲突

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

4 个版本v0.6.0
  1. v0.6.0最新正式版2026-04-16 · 2026-04-16 16:06 UTC

    Added

    • timber.accel — TimberAccelerate merged into core (previously a separate timber-accelerate package, now ships with every pip install timber-compiler install):
      • SIMD codegen — AVX2Emitter, AVX512Emitter, NEONEmitter, SVEEmitter, RVVEmitter; injects vectorised timber_infer_simd() path into generated C; delegates timber_infer_single and timber_infer to SIMD variant at link time
      • GPU codegen — CUDA, Metal, OpenCL emitters
      • FPGA HLS — Xilinx Vitis HLS, Intel FPGA SDK emitters
      • Embedded — Cortex-M, ESP32, STM32 emitters (no-heap, static buffers, cross-compile prefix support)
      • WCET analysis — analyze_wcet(ir, arch, clock_mhz, safety_margin) for Cortex-M4/M7, x86_64, AArch64, RISC-V64; per-stage breakdown with advisory disclaimer
      • Safety transforms — deterministic_pass and constant_time_pass IR transforms
      • Certification reports — DO-178C, ISO 26262, IEC 62304 compliance report generation
      • Supply chain — Ed25519 artifact signing/verification, AES-256-GCM encryption/decryption, TPM integration hooks
      • Deployment — air-gapped bundle creator, C++ gRPC server generator, ROS 2 node generator, PX4 autopilot module generator, sensor preprocessing (radar, RF, telemetry)
      • 18 target profiles (TOML) bundled at timber/accel/targets/: AVX2, AVX512, NEON, SVE, RVV, CUDA SM75/SM86, Metal Apple M1, OpenCL generic, Cortex-M4/M7/ESP32/STM32, HLS Xilinx/Intel
      • 3 compliance profiles (TOML) bundled at timber/accel/compliance_profiles/: DO-178C, ISO 26262, IEC 62304
      • timber-accel CLI — 9 commands: compile, wcet, certify, sign, verify, encrypt, decrypt, bundle, serve-native

  2. v0.5.02026-03-13 · 2026-03-13 12:34 UTC
    查看更新说明

    Added

    • IsolationForestStage IR node — new PipelineStage subclass with flat-tree anomaly scoring; leaf values store pre-computed path-length contributions (depth + c(n_node_samples)) so C99 inference needs no log() at runtime; output = −anomaly_score − offset (positive → inlier)

    • NaiveBayesStage IR node — Gaussian Naive Bayes; stores per-class log-priors, means (theta), pre-computed log_var_const and inv_2var to eliminate log() and division at runtime; softmax output

    • GPRStage IR node — Gaussian Process Regressor (RBF kernel); stores training points, alpha vector, and pre-computed inv_2ls2 / amp2 constants; normalised output via y_train_mean / y_train_std

    • KNNStage IR node — k-Nearest Neighbours classifier or regressor (lookup table); supports Euclidean and Manhattan metrics; classifier outputs winning class index, regressor outputs averaged label vector

    • SVMStage.is_one_class — boolean flag added to SVMStage for OneClassSVM; serialisation and deserialisation updated; decision_function = sum(alpha_i × K) + intercept_

    • sklearn parsers for all 5 new primitives (timber/frontends/sklearn_parser.py):

      • _parse_isolation_forest — remap subsampled feature indices; BFS depth pre-computation; max_depth set on each Tree for correct C99 guard
      • _parse_one_class_svm — extracts _gamma, handles scale/auto/numeric gamma
      • _parse_naive_bayes — pre-computes log_var_const and inv_2var from GaussianNB.var_
      • _parse_gpr — walks ConstantKernel * RBF kernel tree; extracts length_scale and amplitude; safe scalar extraction from _y_train_mean / _y_train_std
      • _parse_knn — handles KNeighborsClassifier and KNeighborsRegressor; maps minkowski/l1/l2 aliases
    • C99 emitters for all 5 new primitives (timber/codegen/c99.py):

      • IsolationForest: iforest_traverse() with double-precision thresholds and path-lengths; exp2(−mean_path / c_max) anomaly score
      • Naive Bayes: log-likelihood accumulation + numerically stable softmax
      • GPR: RBF kernel matrix-vector product with double accumulator
      • k-NN: configurable distance metric; min-heap top-k; majority vote / mean aggregation
    • 119 nuclear tests (tests/test_primitives.py) covering IR round-trip, sklearn parsing field correctness, C99 code structure, compilation, and numerical accuracy vs. sklearn reference for all 5 primitives

    • URDF forward-kinematics frontend (timber/frontends/urdf_parser.py) — URDFParser parses URDF XML into a KinematicsStage IR; auto-detects base link and end-effector; supports all joint types (revolute, prismatic, continuous, fixed)

    • JointSpec IR node — new dataclass carrying joint name, type, axis, origin (xyz + rpy), parent/child links, and position limits; full JSON serialization round-trip

    • KinematicsStage IR node — new PipelineStage subclass holding a list[JointSpec], base_link, end_effector, and computed n_dof; full JSON serialization round-trip

    • C99 emitter: kinematics backend — C99Emitter.emit() dispatches KinematicsStage to:

      • timber_fk(q, T, ctx) — computes 4×4 row-major homogeneous transform from joint angles; max absolute error vs Python reference < 1 × 10⁻⁷
      • timber_infer_single delegates to timber_fk (same ABI as all other Timber stages, 16-element float output)
      • RPY origin transforms pre-computed at code-gen time as compile-time constants
      • Rodrigues rotation for revolute/continuous joints, prismatic translation for sliding joints
      • Helper functions (rodrigues, prismatic) emitted only when needed — zero unused-function warnings
      • TIMBER_N_DOF constant in header
    • timber serve robot.urdf — .urdf extension is now auto-detected; timber load and timber serve accept URDF files directly; serve panel shows N DOF · 16 outputs (4×4 transform) and pre-filled example curl command with zero-initialized joint angles

    • 49 kinematics tests (`tes

  3. v0.4.02026-03-04 · 2026-03-04 09:36 UTC
    查看更新说明

    Added

    • ONNX Linear/SVM/Normalizer/Scaler frontend — parse_onnx_model() now handles six additional ONNX ML opset operators beyond TreeEnsemble:
      • LinearClassifier — binary (sigmoid) and multiclass (softmax), with correct per-row weight extraction
      • LinearRegressor — identity activation, arbitrary output dimensionality
      • SVMClassifier — RBF and linear kernels, full support-vector matrix extraction
      • SVMRegressor — same kernel support as classifier
      • Normalizer — L1 / L2 / Max normalization as a NormalizerStage preprocessing step
      • Scaler — mean-shift / scale as a ScalerStage preprocessing step; fuses with downstream trees via pipeline fusion
    • LinearStage IR node — new PipelineStage subclass holding weights, biases, activation (none / sigmoid / softmax), n_classes, and multi_weights flag; full JSON serialization round-trip
    • SVMStage IR node — new PipelineStage subclass holding support-vector matrix, dual coefficients, rho, gamma, coef0, degree, and kernel type; full JSON serialization round-trip
    • NormalizerStage IR node — new PipelineStage subclass; full JSON serialization round-trip
    • C99 emitter: Linear and SVM backends — C99Emitter.emit() now dispatches LinearStage and SVMStage to dedicated emitters:
      • _emit_inference_linear — unrolled dot product, sigmoid (binary), softmax (multiclass), or identity (regression)
      • _emit_inference_svm — RBF kernel (exp(-γ·‖x−sv‖²)) or linear kernel, with tanh post-transform
      • All outputs are bounded to n_outputs to prevent any buffer overflow
    • Embedded deployment profiles — TargetSpec.for_embedded(profile) selects cross-compilation toolchains for four targets; the Makefile emitted by C99Emitter switches automatically:
      • cortex-m4 — arm-none-eabi-gcc -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard
      • cortex-m33 — arm-none-eabi-gcc -mcpu=cortex-m33 -mfpu=fpv5-sp-d16 -mfloat-abi=hard
      • rv32imf — riscv32-unknown-elf-gcc -march=rv32imf -mabi=ilp32f
      • rv64gc — riscv64-unknown-elf-gcc -march=rv64gc -mabi=lp64d
      • No -fPIC or -shared flags on embedded targets; produces .a static libraries instead of .so
    • LLVM IR backend (timber/codegen/llvm_ir.py) — new LLVMIREmitter supporting TreeEnsembleStage, LinearStage, and SVMStage; configurable target triple (x86_64, aarch64, cortex-m4, …); produces model.ll with SSA form, named traverse_tree_N per-tree functions, and the timber_infer_single entry point
    • Differential privacy module (timber/privacy/dp.py) — apply_dp_noise(outputs, cfg) injects calibrated noise into inference outputs; features:
      • Laplace mechanism: scale = sensitivity / epsilon
      • Gaussian mechanism: σ = √(2 ln(1.25/δ)) · sensitivity / epsilon
      • DPConfig — validates epsilon > 0, sensitivity > 0, delta ∈ (0,1) for Gaussian, mechanism name
      • DPReport — returns noise_scale, mechanism, n_outputs_noised, epsilon, delta
      • calibrate_epsilon(noise_level, sensitivity, mechanism) — invert the mechanism to find required ε
      • Input dtype preserved (float32/float64 round-trips exactly); optional output clipping via clip_outputs, output_min, output_max
      • Deterministic replay with seed parameter
    • bench command enhancements — richer reporting beyond latency:
      • --iters N flag for total timed iterations (default: 1 000)
      • P50 / P95 / P99 / P999 latency percentiles
      • Coefficient of variation (CV%) as a stability indicator
      • --report PATH writes a structured JSON report and a self-contained HTML file (no external dependencies) with a sortable results table and system-info block
      • _bench_report_html() helper for programmatic HTML generation
    • Nuclear-grade test suite (tests/test_nuclear.py) — 139 new tests (436 total passing) covering: IR layer, sklearn/ONNX parsers, numeric accuracy (C99 vs Python IR), all optimizer passes + idempotency + pipeline fusion mat
  4. v0.2.02026-03-03 · 2026-03-03 13:05 UTC
    查看更新说明

    Fixed

    • XGBoost 3.1+ multiclass base_score — XGBoost 3.1+ serializes per-class base scores as a comma-separated bracket string (e.g. '[-3.95E-2,1.97E-1,-1.57E-1]'). Timber previously discarded all but the first value and initialized all class accumulators to 0.0, producing systematic probability errors up to 7.5%. Now the full per-class vector is parsed and applied correctly.

    Added

    • per_class_base_scores: list[float] field on TreeEnsembleStage IR with full serialisation/deserialisation support
    • _parse_base_score_list() helper in xgboost_parser.py for robust base_score parsing across XGBoost versions
    • TIMBER_CLASS_BASE_SCORES[] static array emitted in model_data.c for multiclass models
    • Comprehensive documentation overhaul — all four docs pages expanded and llms.txt added at repo root
    • mkdocs.yml for docs site structure

    Changed

    • Version bumped from 0.1.0 → 0.2.0
    • README completely rewritten: live terminal demo, compiler pipeline diagram, full CLI and API reference tables, runtime comparison feature matrix, roadmap with status indicators

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Timber


    Timber takes a trained ML model — XGBoost, LightGBM, scikit-learn, CatBoost, ONNX (tree ensembles, linear models, SVMs, k-NN, Naive Bayes, GPR, Isolation Forest), or a URDF robot description — runs it through a multi-pass optimizing compiler, and emits a self-contained C99 inference artifact with zero runtime dependencies. A built-in HTTP server (Ollama-compatible API) lets you serve any model in one command.

    For hardware-accelerated or safety-critical deployments, the bundled timber accel backend emits AVX2/AVX-512/NEON/SVE/RVV SIMD, CUDA/Metal/OpenCL GPU, Xilinx/Intel FPGA HLS, and Cortex-M/ESP32/STM32 embedded variants — plus WCET analysis, DO-178C/ISO-26262/IEC-62304 certification reports, Ed25519 artifact signing, AES-256-GCM encryption, air-gapped deployment bundles, and ROS 2 / PX4 / gRPC server generators. Everything ships in one pip install.

    ~2 µs single-sample inference · ~336× faster than Python XGBoost · ~48 KB artifact · zero runtime dependencies


    See it in action

    Point Timber at any URL and it downloads, compiles, and serves in one command — no setup required.

    $ pip install timber-compiler
    $ timber serve https://raw.githubusercontent.com/kossisoroyce/timber/main/examples/breast_cancer_model.json
    
      ✓ Downloaded              breast_cancer_model.json
      ✓ Format detected         xgboost
      ✓ Parsed model            50 trees · 30 features · binary:logistic
      ✓ Optimized               3/5 passes applied
      ✓ Generated C99           169 lines
      ✓ Compiled binary         47.9 KB
    
      Serving    breast_cancer_model
      Endpoint   http://localhost:11434
      Framework  xgboost  ·  50 trees  ·  30 features
    
      POST  http://localhost:11434/api/predict
      GET   http://localhost:11434/api/models
      GET   http://localhost:11434/api/health
    

    Predict immediately:

    $ curl -s http://localhost:11434/api/predict \
        -H 'Content-Type: application/json' \
        -d '{"model": "breast_cancer_model", "inputs": [[1.799e+01, 1.038e+01, 1.228e+02, 1.001e+03, 0.1184, 0.2776, 0.3001, 0.1471, 0.2419, 0.07871, 1.095, 0.9053, 8.589, 153.4, 0.006399, 0.04904, 0.05373, 0.01587, 0.03003, 0.006193, 2.538e+01, 1.733e+01, 1.846e+02, 2.019e+03, 0.1622, 0.6656, 0.7119, 0.2654, 0.4601, 0.1189]]}'
    
    {"model": "breast_cancer_model", "outputs": [[0.9971]], "n_samples": 1}
    

    Or load from a local file and serve by name:

    $ timber load fraud_model.json --name fraud-detector
    $ timber serve fraud-detector
    

    Table of Contents


    Who is this for?

    Timber is built for teams that need fast, predictable, and portable inference:

    • Fraud & risk teams — run classical models in sub-millisecond transaction paths without Python overhead
    • Edge & IoT deployments — ship a ~48 KB C artifact to gateways, microcontrollers, or ARM Cortex-M targets
    • Regulated industries — finance, healthcare, and automotive teams that need deterministic, auditable inference artifacts
    • Platform & infra teams — eliminate the Python model-serving stack from your critical path entirely

    How it works

      ┌─────────────────────────────────────────────────────────┐
      │                     timber load                         │
      │                                                         │
      │  Model file  ──►  Parser  ──►  Timber IR  ──►  Optimizer│
      │  (.json/.pkl/                  (typed AST)   (dead-leaf  │
      │   .txt/.onnx)                               elim, quant, │
      │                                              branch-sort) │
      │                                     │                    │
      │                                     ▼                    │
      │                               C99 Emitter                │
      │                                     │                    │
      │                    ┌────────────────┼────────────────┐   │
      │                    ▼                ▼                ▼   │
      │               model.c         model.h        model_data.c│
      │               (inference)     (public API)   (tree data)  │
      │                    │                                     │
      │                    └──► gcc / clang ──► model.so         │
      └─────────────────────────────────────────────────────────┘
                                  │
                                  ▼
                          timber serve <name>
                       http://localhost:11434/api/predict
    

    The compiler pipeline:

    1. Parse — reads the native model format into a framework-agnostic Timber IR
    2. Optimize — dead-leaf elimination, threshold quantization, constant-feature folding, branch sorting
    3. Emit — generates deterministic, portable C99 with no dynamic allocation and no recursion
    4. Compile — gcc/clang produces a shared library loaded via ctypes
    5. Serve — an Ollama-compatible HTTP API wraps the binary for drop-in integration

    Quick Start

    pip install timber-compiler
    

    Serve any model directly from a URL — no pre-download step:

    timber serve https://yourhost.com/models/fraud_model.json
    

    Or load a local model and serve by name:

    timber load fraud_model.json --name fraud-detector
    timber serve fraud-detector
    

    Predict:

    curl -s http://localhost:11434/api/predict \
      -H "Content-Type: application/json" \
      -d '{"model": "fraud-detector", "inputs": [[1.2, 0.4, 3.1, 0.9]]}'
    
    {"model": "fraud-detector", "outputs": [[0.031]], "latency_us": 1.8}
    

    That's it. No model server configuration, no Python runtime in the hot path.

    Or serve a robot's forward kinematics from a URDF file:

    timber serve robot.urdf
    
    curl -s http://localhost:11434/api/predict \
      -H "Content-Type: application/json" \
      -d '{"model": "robot", "inputs": [[0.1, 0.2, 0.3, -0.4, 0.5, -0.6, 0.7]]}'
    
    {"model": "robot", "outputs": [[0.082, -0.982, 0.170, 0.310, 0.959, 0.031, -0.283, 0.053, 0.272, 0.187, 0.944, 1.180, 0.0, 0.0, 0.0, 1.0]], "latency_us": 65.0}
    

    Supported Formats

    FrameworkFile formatNotes
    XGBoost.jsonAll objectives; multiclass, binary, regression; XGBoost 3.1+ per-class base_score
    LightGBM.txt, .model, .lgbAll objectives including multiclass
    scikit-learn.pkl, .pickleGradientBoosting, RandomForest, ExtraTrees, DecisionTree, Linear/Logistic, SVM, OneClassSVM, IsolationForest, GaussianNB, KNeighborsClassifier/Regressor, GaussianProcessRegressor, Pipeline
    ONNX.onnxTreeEnsembleClassifier/Regressor, LinearClassifier/Regressor, SVMClassifier/Regressor, Normalizer, Scaler
    CatBoost.jsonJSON export (save_model(..., format='json'))
    URDF.urdfRobot description → forward kinematics; outputs 4×4 homogeneous transform; inputs are joint angles

    Hardware Acceleration & Safety (timber accel)

    Every pip install timber-compiler also installs the timber-accel CLI and the timber.accel Python package — no separate install, no paid tier.

    Target backends

    CategoryBackends
    SIMDAVX2, AVX-512, ARM NEON, ARM SVE, RISC-V V (RVV)
    GPUCUDA (SM 7.5 / 8.6), Apple Metal (M1+), OpenCL
    FPGA / HLSXilinx Vitis HLS, Intel FPGA SDK (OpenCL)
    EmbeddedARM Cortex-M4 / M7, ESP32, STM32 (no-heap, static buffers)

    18 target profiles ship as TOML files under timber/accel/targets/ — load one by name or point at a custom .toml.

    Safety & certification

    • WCET analysis (timber-accel wcet) — worst/average-case cycle counts per IR stage for Cortex-M4/M7, x86_64, AArch64, RISC-V64 with configurable safety margin; advisory output (not a replacement for aiT/RapiTime).
    • Deterministic & constant-time IR passes — eliminates data-dependent branches in generated C.
    • Certification reports (timber-accel certify) — structured JSON reports for DO-178C (levels A–D), ISO 26262 (ASIL A–D), IEC 62304 (classes A/B/C); heuristic static analysis plus optional embedded WCET block.

    Supply chain

    • Ed25519 signing & verification (timber-accel sign / verify) — per-artifact detached signatures; keypair generation built in.
    • AES-256-GCM encryption (timber-accel encrypt / decrypt) — symmetric protection for models in transit / on-disk.
    • TPM hooks — Linux TPM 2.0 and software emulator paths.
    • Air-gapped deployment bundles (timber-accel bundle) — tar.gz with model artifact, optional source, optional cert report, manifest for offline deployment.

    Deployment generators

    • C++ gRPC inference server (timber-accel serve-native) — wraps the compiled model in a gRPC (or plain HTTP) service you can drop into a production C++ stack.
    • ROS 2 node package — launch file + rclpy node that calls the compiled model on a ROS topic.
    • PX4 autopilot module — PX4-style uORB module skeleton for flight-controller deployment.
    • Sensor preprocessing — radar, RF, and telemetry front-ends (C callable from compiled code).

    Quick examples

    # Compile with AVX2 SIMD and sign the output
    timber-accel compile --model fraud.pkl --target x86_64_avx2_simd --sign --out ./dist
    
    # WCET for a Cortex-M4 flight controller at 168 MHz
    timber-accel wcet --model anomaly.pkl --arch cortex-m4 --clock-mhz 168
    
    # DO-178C Level B certification report with embedded WCET
    timber-accel certify --model model.pkl --profile do_178c --include-wcet -o cert.json
    
    # Air-gapped deployment bundle
    timber-accel bundle --model model.pkl --include-cert -o deploy.tar.gz
    

    Full CLI reference: timber-accel --help · Docs: docs/accel.md

    Advisory notice — WCET, MISRA-C, and certification features are heuristic / regex-based and explicitly documented as advisory only. For safety-critical certification, use certified tooling (LDRA, Polyspace, Astrée, aiT, RapiTime) and verify independently with a qualified DER.


    Performance

    Benchmarks run on Apple M2 Pro · 16 GB RAM · macOS · XGBoost binary classifier · 50 trees · max depth 4 · 30 features (sklearn breast_cancer) · 10,000 timed iterations after 1,000 warmup.

    RuntimeSingle-sample latencyThroughputSpeedup vs Python
    Timber (native C)~2 µs~500,000 / sec336×
    ONNX Runtime~80–150 µs~10,000 / sec~5×
    Treelite (compiled)~10–30 µs~50,000 / sec~20×
    Python XGBoost~670 µs~1,500 / sec1× (baseline)
    Python scikit-learn~900 µs~1,100 / sec0.7×

    Latency is in-process (not HTTP round-trip). Network overhead adds ~50–200 µs depending on your stack.

    Reproduce these numbers

    python benchmarks/run_benchmarks.py --output benchmarks/results.json
    python benchmarks/render_table.py   --input  benchmarks/results.json
    

    See benchmarks/ for full methodology, hardware capture script, and optional ONNX Runtime / Treelite / lleaves comparisons.


    Runtime Comparison

    TimberPython servingONNX RuntimeTreelitelleaves
    Latency~2 µs100s of µs–ms~100 µs~10–30 µs~50 µs
    Runtime depsNonePython + frameworkONNX Runtime libsTreelite runtimePython + LightGBM
    Artifact size~48 KB50–200+ MB processMBsMB-scalePython env
    Formats5 (trees + linear + SVM)Each framework onlyONNX onlyGBDTsLightGBM only
    C exportYes (C99)NoNoYesNo
    LLVM IR exportYesNoNoNoNo
    Edge / embeddedYes (Cortex-M4/M33, RISC-V)NoPartialPartialNo
    MISRA-C outputYesNoNoNoNo
    Differential privacyYesNoNoNoNo

    API Reference

    Timber's server exposes an Ollama-compatible REST API on http://localhost:11434 by default.

    EndpointMethodBody / ParamsDescription
    /api/predictPOST{"model": str, "inputs": [[float]]}Run inference
    /api/generatePOSTsame as /api/predictOllama alias
    /api/modelsGET—List all loaded models
    /api/model/:nameGET—Model metadata & schema
    /api/healthGET—Health check

    Example — batch inference:

    curl -s http://localhost:11434/api/predict \
      -H "Content-Type: application/json" \
      -d '{
        "model": "fraud-detector",
        "inputs": [
          [1.2, 0.4, 3.1, 0.9],
          [0.1, 2.3, 1.0, 4.4]
        ]
      }'
    

    CLI Reference

    timber — compiler + inference server

    timber load     <path> --name <name>   Compile and register a model
    timber serve    <name> [--port N]      Start the inference server
    timber list                            List registered models
    timber inspect  <name>                 Show model IR summary and schema
    timber validate <name>                 Run numerical validation against source
    timber bench    <name>                 Benchmark latency and throughput
    timber pull     <url>  --name <name>   Download and compile from URL
    timber remove   <name>                 Remove a model from the registry
    

    timber-accel — acceleration, safety, deployment

    timber-accel compile      Compile with SIMD/GPU/HLS/embedded target + optional safety transforms
    timber-accel wcet         Worst-case execution time analysis (Cortex-M4/M7, x86_64, AArch64, RISC-V64)
    timber-accel certify      Generate DO-178C / ISO 26262 / IEC 62304 certification report
    timber-accel sign         Ed25519-sign an artifact (generates keypair on demand)
    timber-accel verify       Verify an Ed25519 signature
    timber-accel encrypt      AES-256-GCM encrypt a model artifact
    timber-accel decrypt      AES-256-GCM decrypt a model artifact
    timber-accel bundle       Create an air-gapped deployment tar.gz
    timber-accel serve-native Generate a C++ gRPC / HTTP inference server
    

    Examples

    Runnable end-to-end examples live in examples/:

    python examples/quickstart_xgboost.py   # trains, compiles, and benchmarks
    python examples/quickstart_lightgbm.py
    python examples/quickstart_sklearn.py
    

    Each script trains a model, saves it, runs timber load, and validates predictions against the source framework.


    Limitations

    • ONNX — supports TreeEnsemble, LinearClassifier/Regressor, SVMClassifier/Regressor, Normalizer, Scaler; other operators (e.g., neural network layers) are not yet supported
    • CatBoost — requires JSON export (save_model(..., format='json')); native binary format not supported
    • scikit-learn — major estimators and Pipeline wrappers are supported; uncommon custom estimators may require a custom front-end
    • Pickle — follow standard pickle security hygiene; only load artifacts from trusted sources
    • XGBoost — JSON model format is the primary path; binary booster format is not supported
    • LLVM IR — currently emitted as text (.ll); requires a local LLVM/Clang installation to produce native code from it
    • MISRA-C — the built-in compliance checker covers the rules most relevant to generated code; it is not a substitute for a certified static analysis tool

    Roadmap

    StatusItem
    ✅XGBoost, LightGBM, scikit-learn, CatBoost, ONNX front-ends
    ✅Multi-pass IR optimizer (dead-leaf, quantization, branch sort, scaler fusion)
    ✅C99 emitter with WebAssembly target
    ✅Ollama-compatible HTTP inference server with multi-worker FastAPI
    ✅PyPI packaging with OIDC trusted publishing
    ✅ONNX Linear/SVM/Normalizer/Scaler operator support
    ✅ARM Cortex-M4/M33 and RISC-V rv32imf/rv64gc embedded deployment profiles
    ✅MISRA-C:2012 compliant output mode with built-in compliance checker
    ✅LLVM IR backend with configurable target triples
    ✅Differential privacy (Laplace + Gaussian) inference mode
    ✅Richer bench reports: P50/P95/P99/P999, CV%, JSON + HTML output
    ✅URDF forward-kinematics frontend — robot FK as a compiled C function
    ✅5 new sklearn primitives: IsolationForest, OneClassSVM, GaussianNB, GPR, k-NN
    ✅SIMD codegen (AVX2, AVX-512, NEON, SVE, RVV) via timber.accel
    ✅GPU codegen (CUDA, Metal, OpenCL) via timber.accel
    ✅FPGA HLS codegen (Xilinx Vitis, Intel FPGA SDK) via timber.accel
    ✅WCET analysis and DO-178C / ISO 26262 / IEC 62304 certification reports
    ✅Ed25519 signing, AES-256-GCM encryption, air-gapped deployment bundles
    ✅ROS 2 / PX4 / gRPC server code generators
    🔄Remote model registry (timber pull from hosted model library)
    🔲Neural network operator support (MLPClassifier)
    🔲ONNX export path (Timber IR → ONNX)
    🔲Rust backend emitter

    Development

    git clone https://github.com/kossisoroyce/timber.git
    cd timber
    pip install -e ".[dev]"
    pytest tests/ -v                    # 650+ tests (core + accel)
    ruff check timber/                  # linting
    

    The test suite covers: parsers (sklearn, ONNX, XGBoost, LightGBM, CatBoost, URDF), IR layer (serialization, deep_copy, all stage types including the 5 new primitives), optimizer passes (correctness, idempotency, pipeline fusion math), C99/WASM/MISRA-C/LLVM IR emitters (compile + numeric accuracy), differential privacy (statistical correctness, all dtypes), timber.accel (WCET analysis, SIMD codegen, Ed25519 signing, certification reports, SIMD/GPU/HLS target profiles), and full end-to-end pipelines.

    See CONTRIBUTING.md for the full development guide.


    Citation

    If you use Timber in research or production, please cite the accompanying technical paper:

    @misc{royce2026timber,
      title        = {Timber: Compiling Classical Machine Learning Models to Native Inference Binaries},
      author       = {Kossiso Royce},
      year         = {2026},
      howpublished = {GitHub repository and technical paper},
      institution  = {Electricsheep Africa},
      url          = {https://github.com/kossisoroyce/timber}
    }
    

    The full paper is available at paper/timber_paper.pdf.


    Community & Governance

    Bugs and feature requests: open an issue. Questions: start a discussion.


    Support the Project

    Timber is developed and maintained by Electricsheep Africa. If Timber saves your team engineering time, consider supporting continued development:

    Buy Me A Coffee

    We're also building a hosted library of compiled models — if you have high-performance models you'd like to contribute, get in touch.


    License

    Apache-2.0 — see LICENSE for the full text.