Metadata-Version: 2.5
Name: green-ai-research-kit
Version: 0.1.0
Summary: Design, run and report green AI experiments: randomised repeated designs, crash-safe resumable runs (Colab and Google Drive friendly), robust statistics (bootstrap intervals, ratio of medians, Mann-Whitney with Holm), drift checks, Pareto fronts, LaTeX tables, a methods paragraph and an energy-reporting checklist.
Project-URL: Homepage, https://www.ahmadzia.com/tools/green-ai-research-kit
Project-URL: Documentation, https://www.ahmadzia.com/tools/green-ai-research-kit
Project-URL: Source, https://github.com/MuhammadAhmadZia/green-ai-research-kit
Project-URL: Issues, https://github.com/MuhammadAhmadZia/green-ai-research-kit/issues
Project-URL: Changelog, https://github.com/MuhammadAhmadZia/green-ai-research-kit/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: benchmarking,colab,energy,experiment-design,green-ai,inference,latex,reproducibility,research,statistics,sustainable-ai
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: System :: Benchmark
Requires-Python: >=3.9
Provides-Extra: bench
Requires-Dist: greeninfer>=0.1.0; extra == 'bench'
Requires-Dist: numpy>=1.21; extra == 'bench'
Requires-Dist: pandas>=1.3; extra == 'bench'
Provides-Extra: scipy
Requires-Dist: scipy>=1.7; extra == 'scipy'
Provides-Extra: test
Requires-Dist: pytest>=7; extra == 'test'
Description-Content-Type: text/markdown

# green-ai-research-kit

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

**Run green AI experiments the way reviewers expect: randomised and repeated, safe from Colab disconnects, with proper statistics, LaTeX tables, a methods paragraph and an energy-reporting checklist.**

```bash
pip install "green-ai-research-kit[bench,scipy]"
```

Energy results are easy to get wrong. CPUs heat up and slow down, turbo budgets run out, cloud VMs share hardware with strangers, and a single run tells you almost nothing about the next one. Henderson et al. (JMLR 2020) sampled 100 NeurIPS 2019 papers: none reported carbon, and only one reported any energy figure. This kit handles the parts that make energy and latency results trustworthy, so you can spend your time on the research question.

| Step | What the kit does | Why it matters |
|---|---|---|
| Design | Every combination of your factors, repeated, in a **fresh random order each round** | Spreads heating, turbo and background load evenly over all configurations instead of punishing whichever ran last (Kalibera and Jones, ISMM 2013) |
| Run | Saves **each result the moment it exists** (one line per run, flushed to disk) and **skips finished runs** when you rerun | A Colab disconnect costs you one run, not the experiment. Point the results file at Google Drive |
| Measure | Plugs into [greeninfer](https://www.ahmadzia.com/tools/greeninfer) for latency and energy (Intel RAPL counters with idle power subtracted, or a CPU-time estimate), or runs any function you write | You can benchmark anything, not only tree models |
| Analyse | Medians with **bootstrap 95% intervals**, the **ratio of medians** against a baseline with its own interval, **Mann-Whitney U** p-values with **Holm** correction, a **drift check** against run order, and a **Pareto front** for two metrics | Energy and latency samples are skewed with outliers, so means and t-tests mislead |
| Warn | Tells you when your design **cannot** show a significant difference, whatever the effect | With 3 repeats, the smallest possible two-sided Mann-Whitney p-value is 0.1 |
| Report | Markdown and **LaTeX (booktabs)** tables, a **methods paragraph** filled with your machine, versions and settings, and a **reporting checklist** | Reviewers ask for the CPU, the measurement method, idle handling, repetitions, spread, PUE and grid intensity |

## Quick start: the command line

You need a CSV of input rows and one or more saved models (XGBoost `.json`, LightGBM `.txt`, CatBoost `.cbm`, or scikit-learn `.joblib`).

**Step 1. Run the experiment.** This compares two models at batch sizes 1 and 1024, five times each, in shuffled order:

```bash
green-ai-research-kit bench \
  --models xgb=xgb.json,lgbm=lgbm.txt \
  --data test.csv --drop target \
  --batches 1,1024 --threads 1 --repeats 5 \
  --out results/results.jsonl
```

It writes three files next to each other:

- `results.plan.csv`: the shuffled plan (kept so a rerun follows the same order)
- `results.jsonl`: one line per finished run
- `results.environment.json`: CPU, cores, platform, library versions, governor, turbo, RAPL status

If it stops for any reason, run the **same command again**. Finished runs are skipped.

**Step 2. Analyse it.**

```bash
green-ai-research-kit analyze results/results.jsonl \
  --by model,batch --metric joules_per_1k --unit J \
  --baseline model=xgb,batch=1 \
  --metric2 latency_ms_p50 \
  --grid 400 --grid-source "Ember 2024 world average" \
  --md results/report.md --latex results/table.tex
```

`report.md` holds the methods paragraph, the results table, the comparison with the baseline, the Pareto front, any warnings and the checklist. `table.tex` is ready to paste into a paper (it needs `\usepackage{booktabs}`).

Metrics greeninfer records for each run: `joules_per_1k`, `latency_ms_p50`, `latency_ms_p95`, `us_per_row`. Use `--maximize2` when the second metric is better when higher, such as accuracy.

## Quick start: Google Colab with Google Drive

Open [`examples/colab_experiment.ipynb`](examples/colab_experiment.ipynb) in Colab. It walks through a full experiment (XGBoost, LightGBM and a random forest on the public Adult census dataset, no login needed) and saves the data, models, plan, results, report, LaTeX table and plot to `MyDrive/green_research/`. After a disconnect, press **Runtime > Run all** again and it continues where it stopped.

Colab has no RAPL counters, so energy there is an estimate (CPU time x TDP per core). The methods paragraph says this for you. For measured energy, run the same commands on a Linux machine with an Intel or AMD CPU as root.

## Quick start: Python, with your own measurement

The runner works with any function that takes a configuration and returns numbers. Here is an LLM-quantisation experiment as an example:

```python
from green_research import plan, run, load_results, summarize, compare, power_warnings, table_latex

runs = plan({"model": ["q4", "q8", "fp16"], "prompt_len": [128, 2048]}, repeats=5, seed=42)

def measure(cfg):
    # your code: load the model, generate, read an energy meter
    return {"joules": ..., "tokens_per_s": ..., "accuracy": ...}

run(runs, measure, "/content/drive/MyDrive/quant/results.jsonl", cooldown_s=10)

rows = load_results("/content/drive/MyDrive/quant/results.jsonl")
summary = summarize(rows, ["model", "prompt_len"], "joules")
comparison = compare(rows, ["model", "prompt_len"], "joules", {"model": "fp16", "prompt_len": "128"})
print(power_warnings(summary, len(comparison)))
print(table_latex(summary, ["model", "prompt_len"], "joules", "J"))
```

Things to know:

- Every metric you return is stored with an `m_` prefix (`m_joules`). The analysis functions find it with or without the prefix.
- If your function raises an error, the run is saved with the error message and the experiment continues. Failed runs are left out of the statistics and counted in the report. Pass `stop_on_error=True` to stop instead.
- `cooldown_s` pauses between runs so the CPU or GPU can return to a steady temperature.
- Plans are reproducible: the same factors, repeats and seed give the same order.

## How the statistics work

| Output | Method |
|---|---|
| Centre | Median of the repeats |
| 95% CI | Percentile bootstrap, 2,000 resamples, fixed seed |
| Comparison | Ratio of medians (configuration / baseline) with a bootstrap interval, resampling each group separately |
| p-value | Two-sided Mann-Whitney U (with SciPy installed, its exact test for small groups without ties; otherwise the normal approximation with tie and continuity corrections) |
| Many comparisons | Holm-Bonferroni adjustment |
| "Significant" | Holm-adjusted p < 0.05 **and** the ratio's interval excludes 1 |
| Spread | Standard deviation, coefficient of variation, and outliers beyond 1.5 x IQR |
| Drift | Spearman correlation between run order and the result, per configuration; flagged at 0.6 or more with at least 5 runs |
| Pareto front | Configurations no other configuration beats on both metrics |

**How many repeats?** The smallest two-sided Mann-Whitney p-value with *n* runs in each group is 2 / C(2n, n): 0.1 for 3 runs, 0.029 for 4, 0.008 for 5. Holm multiplies the smallest p by the number of comparisons. The kit checks this and tells you the number of repeats you need. Five repeats is the minimum we recommend; use more when you compare many configurations.

## Reporting checklist

The report ticks off what it can find and leaves the rest for you:

- Processor model; cores and threads; operating system; Python and library versions
- How energy was measured (RAPL counters or an estimate) and what it covers
- Whether idle power was subtracted
- CPU frequency governor and turbo state; thread settings
- Number of repetitions and run order; spread of results
- Data-centre PUE (if converting to facility energy); grid carbon intensity with its source and year
- Total compute used by the experiments themselves

Based on Henderson et al. (2020) and the Green Algorithms reporting guidance (Lannelongue, Grealey and Inouye, 2021).

## Sustainable Development Goals

| Target | How this tool contributes |
|---|---|
| **9.5** Enhance scientific research and upgrade technological capabilities | Gives researchers, including those on free tools like Colab, a rigorous and reproducible way to measure and report the energy of AI methods |
| **12.6** Encourage companies to adopt sustainable practices and integrate sustainability information into their reporting | The methods paragraph and checklist make energy and carbon reporting the default in AI papers and technical reports |
| **13.3** Improve education and awareness on climate change mitigation | Makes the energy cost of AI choices measurable and comparable, so the greener option can be shown, not assumed |

## References

- Henderson, P., Hu, J., Romoff, J., Brunskill, E., Jurafsky, D. and Pineau, J. (2020). Towards the Systematic Reporting of the Energy and Carbon Footprints of Machine Learning. *Journal of Machine Learning Research*, 21(248), 1-43.
- Kalibera, T. and Jones, R. (2013). Rigorous Benchmarking in Reasonable Time. *ISMM 2013*, ACM.
- Lannelongue, L., Grealey, J. and Inouye, M. (2021). Green Algorithms: Quantifying the Carbon Footprint of Computation. *Advanced Science*, 8(12), 2100707.
- Holm, S. (1979). A Simple Sequentially Rejective Multiple Test Procedure. *Scandinavian Journal of Statistics*, 6(2), 65-70.

## Citing

If the kit helps your research, please cite it (see `CITATION.cff`) and the measurement tool you used.

## Licence

MIT. Built by [Ahmad Zia](https://www.ahmadzia.com), who works on green and efficient AI inference.

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

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

- [greeninfer](https://github.com/MuhammadAhmadZia/greeninfer): Measure latency, energy, CO2 and cost per prediction for tree models

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