Metadata-Version: 2.5
Name: parallel-inference-tuner
Version: 0.1.0
Summary: Find the fastest and most energy-efficient threads, processes and micro-batching for model inference on your machine: measures XGBoost, LightGBM, CatBoost, scikit-learn, ONNX Runtime or PyTorch models, detects container CPU limits and oversubscription, and simulates online serving against a latency target.
Project-URL: Homepage, https://www.ahmadzia.com/tools/parallel-inference-tuner
Project-URL: Documentation, https://www.ahmadzia.com/tools/parallel-inference-tuner
Project-URL: Source, https://github.com/MuhammadAhmadZia/parallel-inference-tuner
Project-URL: Issues, https://github.com/MuhammadAhmadZia/parallel-inference-tuner/issues
Project-URL: Changelog, https://github.com/MuhammadAhmadZia/parallel-inference-tuner/blob/main/CHANGELOG.md
Project-URL: Author, https://www.ahmadzia.com
Project-URL: Research, https://www.ahmadzia.com/research
Author-email: Muhammad Ahmad Zia <muhammad.zia@cs.uol.edu.pk>
License-Expression: MIT
License-File: LICENSE
Keywords: batching,energy,green-ai,inference,latency,lightgbm,micro-batching,multiprocessing,multithreading,onnxruntime,openmp,oversubscription,parallel-computing,throughput,xgboost
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: System :: Benchmark
Requires-Python: >=3.9
Requires-Dist: greeninfer>=0.1.0
Requires-Dist: numpy>=1.21
Provides-Extra: all
Requires-Dist: joblib>=1.1; extra == 'all'
Requires-Dist: lightgbm>=3.3; extra == 'all'
Requires-Dist: onnxruntime>=1.16; extra == 'all'
Requires-Dist: pandas>=1.3; extra == 'all'
Requires-Dist: scikit-learn>=1.0; extra == 'all'
Requires-Dist: threadpoolctl>=3.1; extra == 'all'
Requires-Dist: xgboost>=1.7; extra == 'all'
Provides-Extra: onnx
Requires-Dist: onnxruntime>=1.16; extra == 'onnx'
Provides-Extra: pandas
Requires-Dist: pandas>=1.3; extra == 'pandas'
Provides-Extra: test
Requires-Dist: pytest>=7; extra == 'test'
Requires-Dist: scikit-learn>=1.0; extra == 'test'
Requires-Dist: threadpoolctl>=3.1; extra == 'test'
Provides-Extra: threadpoolctl
Requires-Dist: threadpoolctl>=3.1; extra == 'threadpoolctl'
Description-Content-Type: text/markdown

# parallel-inference-tuner

<!-- badges -->
[![PyPI](https://img.shields.io/pypi/v/parallel-inference-tuner?color=3a7a4e&label=PyPI)](https://pypi.org/project/parallel-inference-tuner/) [![CI](https://github.com/MuhammadAhmadZia/parallel-inference-tuner/actions/workflows/ci.yml/badge.svg)](https://github.com/MuhammadAhmadZia/parallel-inference-tuner/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-0d2018)](LICENSE) [![Agent skill](https://img.shields.io/badge/agent%20skill-parallel--inference--tuner-c5dfc9)](skills/parallel-inference-tuner/SKILL.md) [![Guide](https://img.shields.io/badge/guide-ahmadzia.com-3a7a4e)](https://www.ahmadzia.com/tools/parallel-inference-tuner)

**Find the fastest and most energy-efficient way to run your model on your machine: how many threads, how many worker processes, and how big a batch.** It measures your model, measures the workers together, then simulates your real traffic against a latency target and tells you the settings.

```bash
pip install parallel-inference-tuner
parallel-inference-tuner model.json --data rows.csv --rate 300 --slo-ms 20
```

```
Time per call (ms) by threads and batch size:
  batch       1 thr      2 thr
      1       0.104      0.126
      8       0.244      0.255
     64       0.447      0.429
    512       2.115      1.195

Fastest single prediction: 1 thread(s), 0.10 ms per call.
Bulk scoring, highest throughput: 2 process(es) x 1 thread(s), batch 64: 276,327 rows/s.

All workers busy at once:
   1 proc x  2 thr, batch   64:      150,301 rows/s  0.553 mJ/row
   2 proc x  1 thr, batch   64:      276,327 rows/s  0.307 mJ/row

Online serving at 300 requests/s with p95 under 20 ms:
  Least energy: 2 worker(s) x 1 thread(s), micro-batches of up to 64, waiting at most 10 ms
    predicted p50 6.85 ms, p95 10.19 ms, p99 10.25 ms, 1.791 mJ per request
```

(A 300-tree XGBoost model on a 2-CPU cloud VM. Run it on your own hardware: the answer changes with the machine.)

## Why

Every tree library and runtime has its own threading defaults, and they are usually wrong for serving:

- **Threads for one prediction rarely help.** For a single row, starting and syncing threads costs more than the work. In the run above, 2 threads were slower than 1 for batches up to 8.
- **Processes often beat threads.** Two single-threaded workers did 276k rows/s against 150k for one worker with two threads, at nearly half the energy per row.
- **Containers hide their CPU limit.** `os.cpu_count()` returns the host's CPUs, not your container's quota. A library that sizes its thread pool from the host count runs far more threads than it gets CPU time for: an XGBoost report (issue #7653) measured 28 s with default threads against 0.3 s with one thread, in a one-CPU container on a 16-CPU host. Whether your library version handles this varies, so this tool reads the cgroup quota and affinity mask and measures what actually happens.
- **Oversubscription is silent.** Workers x threads above the usable CPUs makes everything slower. Gunicorn workers each running a default-threaded model is the classic case.
- **Batching is a latency trade.** Waiting a few milliseconds to group requests can multiply throughput and cut energy per request, but only up to your latency target. Testing every combination live would take hours; simulating it from measured service times takes seconds.

## What it does

1. **Reads the machine:** usable CPUs (affinity and cgroup v1/v2 quota), physical cores, hyper-threading, NUMA nodes.
2. **Measures the service-time curve:** seconds, CPU time and energy per call for each thread count and batch size (median of repeated timed loops, after warm-up).
3. **Measures workers together:** several worker processes running at once, each with its thread limit set before the model library loads, to capture memory-bandwidth and cache contention.
4. **Simulates online serving** with random (Poisson) arrivals, a shared queue, workers and micro-batching (max batch, max wait), using the measured curves and contention. The simulator reproduces M/D/1 queueing theory in its tests.
5. **Recommends** the fastest single-request setting, the best bulk-scoring layout, and the serving setups that meet your latency target with the least energy and with the lowest latency, plus the environment variables to set.

## Supported models

XGBoost (`.json`, `.ubj`), LightGBM (`.txt`), CatBoost (`.cbm`), scikit-learn and anything pickled with joblib or pickle (`.joblib`, `.pkl`), ONNX Runtime (`.onnx`), PyTorch (from a factory), or any object with `predict`. Threads are set through each library's own option (XGBoost `nthread`, LightGBM `num_threads`, CatBoost `thread_count`, scikit-learn `n_jobs`, ONNX Runtime `intra_op_num_threads`, PyTorch `set_num_threads`), through `threadpoolctl` for OpenMP and BLAS pools when installed, and through `OMP_NUM_THREADS` and the BLAS variables for worker processes.

ONNX Runtime sessions are created with thread spinning off: the ONNX Runtime docs note that spinning gives faster inference but uses more CPU and power.

Only load model files you trust: joblib and pickle files can run code when loaded. [model-file-guard](https://www.ahmadzia.com/tools/model-file-guard) checks them first.

## Options

```
--data FILE           Sample rows (.csv, .parquet, .npy); --drop COLUMNS removes the target
--threads 1,2,4,8     Thread counts to try (default: powers of 2 up to the usable CPUs)
--batches 1,8,64,512  Batch sizes to try (default: powers of 2 up to 1024)
--rate N --slo-ms MS  Plan online serving for N requests/s with the latency target
--quantile p95        p50, p95, p99 or mean for the target
--no-scaling          Skip the multi-process measurement
--oversubscribe       Also try twice as many processes as fit, to see the cost
--energy auto         rapl, cpu-time or auto; --tdp WATTS for the CPU-time model
--json, --md FILE
```

From Python:

```python
from parallel_inference_tuner import tune, format_text
report = tune("model.json", X_sample, rate=300, slo_ms=20)
print(format_text(report))
print(report["settings"])  # workers, threads_per_worker, max_batch, max_wait_ms, env
```

Worker processes load the model themselves, so give a file path or a `"package.module:function"` factory for the multi-process step. With a model object, only the single-process curve is measured.

## Energy

Energy comes from [greeninfer](https://www.ahmadzia.com/tools/greeninfer): RAPL package counters with idle power subtracted where they are readable (bare-metal Linux, usually as root since CVE-2020-8694), otherwise the Green Algorithms model (CPU time x TDP per logical core). The CPU-time model has no idle power, so in that mode waiting to fill a batch looks free; the report says so. Pass `--tdp` with your CPU's real TDP for better estimates.

## Limits

- The simulator assumes Poisson arrivals and one shared queue. Bursty traffic needs more headroom than it predicts.
- Contention is measured with every worker busy; at light load it is lower, so predictions err on the slow side.
- GPU inference is not covered.
- Short runs on busy machines are noisy. Close other work and use `--min-time 0.5 --repeats 5` for final numbers.

## SDG alignment

This tool supports **SDG target 7.3** (double the global rate of improvement in energy efficiency): the same model, on the same hardware, often runs at half the energy per prediction with better thread, process and batch settings. It also supports **target 9.4** (resource-efficient infrastructure), since a well-tuned server handles more traffic before another machine is needed.

## Sources

- ONNX Runtime. Thread management. https://onnxruntime.ai/docs/performance/tune-performance/threading.html
- scikit-learn. Parallelism, resource management and configuration (oversubscription, OMP_NUM_THREADS, threadpoolctl). https://scikit-learn.org/stable/computing/parallelism.html
- Linux kernel documentation. Control Group v2 (cpu.max) and CFS bandwidth control. https://docs.kernel.org/admin-guide/cgroup-v2.html
- XGBoost issue #7653: performance with default threads in CPU-limited containers. https://github.com/dmlc/xgboost/issues/7653
- Lannelongue L., Grealey J., Inouye M. (2021). Green Algorithms: quantifying the carbon footprint of computation. Advanced Science 8(12).
- Kleinrock L. (1975). Queueing Systems, Volume 1: Theory (M/D/1 waiting time, Pollaczek-Khinchine formula).

## About

Built by [Ahmad Zia](https://www.ahmadzia.com), who researches energy-efficient inference for gradient-boosted tree models and teaches parallel and distributed computing. MIT licensed.

<!-- ahmadzia-links -->
## Guide, help and author

- **Full guide with examples and FAQs:** [www.ahmadzia.com/tools/parallel-inference-tuner](https://www.ahmadzia.com/tools/parallel-inference-tuner)
- **Background reading:** [How much energy does an AI query use?](https://www.ahmadzia.com/blog/ai-energy-consumption-per-query)
- **All 30 free tools and agent skills:** [ahmadzia.com/tools](https://www.ahmadzia.com/tools) · [ahmadzia.com/skills](https://www.ahmadzia.com/skills)
- **Want it set up, fixed or tuned for your store?** [Book a free call](https://www.ahmadzia.com/contact)

Built by **[Ahmad Zia](https://www.ahmadzia.com)** (Muhammad Ahmad Zia), an AI consultant for ecommerce since 2020 and green AI researcher at the University of Lahore. [Research](https://www.ahmadzia.com/research) · [Google Scholar](https://scholar.google.com/citations?user=sqjdX2EAAAAJ&hl=en) · [ORCID](https://orcid.org/0000-0002-3208-6246) · [LinkedIn](https://www.linkedin.com/in/muhammad-ahmadzia/) · [GitHub](https://github.com/MuhammadAhmadZia)
<!-- /ahmadzia-links -->

## More AI cost control tools

- [llm-cost-shield](https://github.com/MuhammadAhmadZia/llm-cost-shield): Stop surprise LLM bills with per-user budgets, caching and cheap-model routing
- [right-size-model](https://github.com/MuhammadAhmadZia/right-size-model): Find the cheapest LLM that is good enough for each task, with a statistical test
- [green-batch-ai](https://github.com/MuhammadAhmadZia/green-batch-ai): Run bulk AI jobs at half price and on cleaner power

All 30 tools and agent skills: [github.com/MuhammadAhmadZia](https://github.com/MuhammadAhmadZia) · [ahmadzia.com/tools](https://www.ahmadzia.com/tools)
