Metadata-Version: 2.5
Name: greeninfer
Version: 0.1.0
Summary: Measure latency, throughput, energy, CO2 and cost per prediction for gradient-boosted tree models (XGBoost, LightGBM, CatBoost, scikit-learn) and any model with a predict method.
Project-URL: Homepage, https://www.ahmadzia.com/tools/greeninfer
Project-URL: Documentation, https://www.ahmadzia.com/tools/greeninfer
Project-URL: Source, https://github.com/MuhammadAhmadZia/greeninfer
Project-URL: Issues, https://github.com/MuhammadAhmadZia/greeninfer/issues
Project-URL: Changelog, https://github.com/MuhammadAhmadZia/greeninfer/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: benchmark,carbon,catboost,energy,gbdt,green-ai,inference,latency,lightgbm,mlops,sustainable-ai,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: numpy>=1.21
Provides-Extra: all
Requires-Dist: catboost>=1.1; extra == 'all'
Requires-Dist: joblib>=1.1; extra == 'all'
Requires-Dist: lightgbm>=3.3; extra == 'all'
Requires-Dist: pandas>=1.3; extra == 'all'
Requires-Dist: scikit-learn>=1.0; extra == 'all'
Requires-Dist: xgboost>=1.7; extra == 'all'
Provides-Extra: catboost
Requires-Dist: catboost>=1.1; extra == 'catboost'
Provides-Extra: lightgbm
Requires-Dist: lightgbm>=3.3; extra == 'lightgbm'
Provides-Extra: pandas
Requires-Dist: pandas>=1.3; extra == 'pandas'
Provides-Extra: sklearn
Requires-Dist: joblib>=1.1; extra == 'sklearn'
Requires-Dist: scikit-learn>=1.0; extra == 'sklearn'
Provides-Extra: test
Requires-Dist: pytest>=7; extra == 'test'
Requires-Dist: scikit-learn>=1.0; extra == 'test'
Provides-Extra: xgboost
Requires-Dist: xgboost>=1.7; extra == 'xgboost'
Description-Content-Type: text/markdown

# greeninfer

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

**Latency, energy, CO2 and cost per prediction for gradient-boosted tree models.** Training gets the attention, but a model in production is called millions of times. greeninfer measures what each prediction really costs, so you can pick the model, batch size and settings that are fast, cheap and light on energy.

```bash
pip install greeninfer
```

Works with **XGBoost, LightGBM, CatBoost, scikit-learn** and anything with a `.predict()` method or any Python callable.

## Quick start

```python
from greeninfer import benchmark

res = benchmark(
    {"xgb_500": xgb_model, "lgbm_200": lgbm_model},
    X_test,
    batch_sizes=(1, 32, 1024),   # single-row serving vs small vs large batches
    usd_per_hour=0.10,           # your machine price, for $ per million predictions
    grid_g_per_kwh=475,          # grid carbon intensity where the model runs
)
print(res.summary())
res.to_csv("results/inference_bench.csv")
```

```
model               batch    p50 ms    p95 ms    us/row      rows/s      J/1k     Wh/1M   gCO2/1M      $/1M
-----------------------------------------------------------------------------------------------------------
xgb_300                 1     0.081     0.168    110.53        9048     4.648     1.291     0.613    0.0031
xgb_300              1024     2.609     3.184      2.58      386941     0.110     0.030     0.014    0.0001
lgbm_300                1     0.036     0.062     42.79       23369     3.594     0.998     0.474    0.0012
lgbm_300             1024     9.402     9.899      9.16      109155     0.773     0.215     0.102    0.0003

Energy method: cpu-time-estimate. Grid intensity: 475.0 gCO2/kWh.
```

(Example run: 300-tree models on synthetic data, single thread, a 2-core cloud VM. Notice how single-row serving costs 15 to 40 times more energy per prediction than large batches, and how the ranking of the two libraries flips with batch size. Your hardware and models will give different numbers.)

## What it reports

For every model and batch size:

| Column | Meaning |
|---|---|
| `latency_ms_p50/p95/p99/mean` | Time per predict call |
| `us_per_row`, `rows_per_sec` | Per-prediction cost and throughput |
| `joules_per_1k`, `wh_per_1m` | Energy per 1,000 and per 1 million predictions |
| `g_co2_per_1m` | Grams of CO2 per million predictions at your grid intensity |
| `usd_per_1m` | Machine cost per million predictions (if `usd_per_hour` is set) |
| `energy_method` | `rapl` (measured) or `cpu-time-estimate` (modelled) |
| `repeats`, `us_per_row_min/max`, `joules_per_1k_min/max` | Each value is the median of several independent timed runs (3 by default); min and max show the run-to-run spread |
| `joules_per_1k_gross`, `idle_watts` | With RAPL: package energy before idle power was subtracted, and the idle power measured |
| `threads` | Prediction threads, if you set them |

Plus model facts (trees, boosting rounds, serialized size) and the environment (CPU, core count, CPU frequency governor, thread environment variables, why RAPL was or was not used, library versions) so results are reproducible.

## How energy is measured

- **RAPL (measured):** on Linux machines that expose `/sys/class/powercap/intel-rapl:*`, greeninfer reads the CPU package energy counters before and after the timed loop, including counter wrap-around. RAPL counts the whole package, so before each model greeninfer measures idle power for `idle_seconds` (2 s by default) and subtracts it: `joules_per_1k` is the energy the inference adds, `joules_per_1k_gross` the raw reading. Since the PLATYPUS disclosure (CVE-2020-8694), Linux lets only root read the counters; if they exist but cannot be read, the summary says so instead of silently falling back.
- **CPU-time estimate (everywhere else, including Google Colab):** energy = CPU seconds used by the process x (TDP / logical cores), optionally plus memory power (0.3725 W per GB, `memory_gb=`). This is the Green Algorithms model (Lannelongue, Grealey and Inouye, *Advanced Science*, 2021). Default TDP is 85 W; pass your CPU's real TDP with `tdp_watts=`. It is comparable between runs on the same machine, not an absolute measurement.
- **Data centre overhead:** `pue=` multiplies energy and CO2 by the facility's Power Usage Effectiveness (1.0 on a laptop; cloud providers publish theirs).
- **Grid:** the default is the world average, 473 gCO2e/kWh (Ember data as used by CO2.js). Pass your country's or cloud region's value with `grid_g_per_kwh=` (Ember and Electricity Maps publish them).

The method used is always printed and saved with the results. Report it in papers.

## Command line

```bash
greeninfer bench --model model.json --model model.txt --data test.csv --drop target \
  --batch-sizes 1,32,1024 --repeats 5 --threads 1 --usd-per-hour 0.10 --grid 399 --csv results.csv --json results.json
```

| Option | Meaning |
|---|---|
| `--model` | Saved model, repeat to compare: `.json`/`.ubj` (XGBoost), `.txt` (LightGBM), `.cbm` (CatBoost), `.joblib`/`.pkl` (scikit-learn) |
| `--data` | CSV of features. Non-numeric columns are ignored. |
| `--drop` | Columns to remove, such as the target |
| `--batch-sizes` | Comma-separated, default `1,32,1024` |
| `--seconds` | Minimum timed seconds per batch size (default 2) |
| `--energy` | `auto`, `rapl` or `cpu-time` |
| `--tdp` | CPU TDP in watts for the estimate |
| `--grid` | gCO2 per kWh |
| `--repeats` | Independent timed runs per batch size (default 3, median reported) |
| `--threads` | Prediction threads for the model library |
| `--idle-seconds` | RAPL only: idle measurement to subtract (default 2, 0 = off) |
| `--memory-gb` | Add memory power to the CPU-time estimate |
| `--pue` | Data-centre PUE (default 1.0) |
| `--usd-per-hour` | Machine price |
| `--csv`, `--json` | Save results |

Only load `.joblib` or `.pkl` files you trust: they can run code when loaded.

## Google Colab

`examples/colab_quickstart.ipynb` trains small XGBoost and LightGBM models on a public dataset that needs no login, benchmarks them, and saves everything to Google Drive so a disconnect does not lose your results.

## Good practice for fair comparisons

- Run all models in the same session on the same machine, and close other heavy programs.
- Set thread counts explicitly (`n_threads=` or `--threads`) and report them. Single-row latency often gets worse with many threads, because waking a thread pool costs more than predicting one row.
- Fix the CPU frequency if you can (the `performance` governor); the governor is saved with the results. Turbo and power-saving modes add noise.
- Use the same rows for every model. Report p95, not just the mean.
- Keep `repeats` at 3 or more and report the spread; the summary warns when repeats differ by more than 10%.
- Report the energy method, idle subtraction, PUE and grid intensity with any energy or CO2 number.

## Sustainable Development Goals

This tool supports **SDG target 9.4** (upgrade infrastructure and industries for resource efficiency and cleaner technologies) and **target 7.3** (improve energy efficiency): inference, not training, is where most of a deployed model's energy goes, and choosing the right model, batch size and thread count can cut it severalfold at the same accuracy. It also supports **target 9.5** (enhance scientific research): measured, repeated and fully documented energy numbers make green-ML results reproducible and comparable across papers.

## Cite

If you use greeninfer in research, please cite the software (a `CITATION.cff` is included) and mention the energy method.

## About

Built by Muhammad Ahmad Zia (University of Lahore), who researches energy-efficient inference for tree ensembles in e-commerce and health. Website: [ahmadzia.com](https://www.ahmadzia.com). MIT licensed.

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

- **Full guide with examples and FAQs:** [www.ahmadzia.com/tools/greeninfer](https://www.ahmadzia.com/tools/greeninfer)
- **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)

**Research behind this tool**

- Bin-reduction GBDT training and inference energy on 100,000 drug reviews, JCBI 2026: [doi:10.56979/1102/2026/1477](https://doi.org/10.56979/1102/2026/1477)

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 green AI research tools

- [green-ai-research-kit](https://github.com/MuhammadAhmadZia/green-ai-research-kit): Design, run and report green AI experiments that survive peer review

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