Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

RL Agent Recommendation Uncertainty

This repository provides agent-agnostic epistemic uncertainty scoring for Grid2Op recommendations. It collects an agent's rollout behavior, trains an Evidential Neural Network (ENN) on observation/action pairs, and adds calibrated uncertainty KPIs to the agent's recommendations.

Compatible agents expose:

agent.act(obs, reward, done)

Everything is run through one entry point, main.py (workflows in src/workflows/), together with recommendation_uncertainty.py, training/, and app/. The original workflow is available only in Git history; see Legacy Workflow.

Quick Links

Installation

Use Python 3.9 or 3.10. The pinned Grid2Op, TensorFlow, Ray, and Torch versions do not support newer Python versions and should not be upgraded independently.

conda create -n enn_uq python=3.10 -y
conda activate enn_uq
pip install -r requirements.txt

Active Workflow

Pre-trained agent assets and ENN artifacts are distributed separately in the project release archives. Extract them into the repository root so the following directories exist:

assets/<ENV_NAME>/
artifacts/<ENV_NAME>/<AGENT_NAME>/
environment/<ENV_NAME>

Main Commands

All commands go through main.py; python main.py <command> --help lists the options of each one.

  • python main.py (or python main.py status): show which artifacts exist, which training stages would run, and whether the demo is ready. Read-only.
  • python main.py demo: load pretrained artifacts and run the full operating-mode chain live: ENN recommendation uncertainty KPIs -> multi-line, one-hour-ahead failure forecasts -> per-line rule explanations. Explanations are added automatically when failure_forecast/explainability/rules/ exists (--rules-dir PATH to use another directory, --no-explain to turn them off). Missing or invalid rules only produce a warning; the HGB probabilities and predictions are identical with or without explanations. The demo does not train models and needs neither failure_forecast_rows.csv, failure_classifier_oof.npz, nor an LLM configuration or key. Per-line results (with explanation fields) are in kpis["failure_forecasts"].
  • python main.py train: use .env settings to collect training data and train all ENN and failure-forecast artifacts. Valid artifacts are reused, and selected stages can be forced when needed.
  • python main.py train --profile [PATH]: the same, plus SHAP ranking and LLM rule distillation, with every option taken from one JSON profile (default src/llm_config.json; see src/explainability/README.md).
  • python main.py smoke: run every training stage with a tiny configuration under artifacts_smoke/, leaving normal artifacts untouched. This verifies integration, not model quality; if the tiny failure dataset contains only one class, the test may add explicitly marked synthetic failure rows.

The workflow uses:

  • training/collect_rollouts.py and training/train_enn.py for ENN training.
  • recommendation_uncertainty.py to score an agent's selected action.
  • app/main.py to serve recommendations and KPIs through FastAPI.

Generated ENN data is stored under:

artifacts/<ENV_NAME>/<AGENT_NAME>/
|-- rollouts/
|   |-- observations.npy
|   |-- labels.npy
|   `-- actions.npy
`-- model/
    |-- enn_<AGENT_NAME>.pth
    |-- scaler_params.json
    |-- enn_meta.json
    `-- enn_pctile_calib.npz

Supported Grid2Op Environment

The default environment is ai4realnet_small, sourced from the Grid2Op scenario repository. The scenario directory must resolve to:

<ENV_LOCATION>/<ENV_NAME>

With the default configuration, this is environment/ai4realnet_small/.

Curriculum Agent

The default policy is a pre-trained CurriculumAgent for ai4realnet_small. Its release archive must provide:

assets/ai4realnet_small/
|-- model/
`-- actions/

To retrain the policy for a changed environment or action space, run:

python training/train_curriculumagent.py

The trained package is written to assets/<ENV_NAME>/.

Configuration

Create a local configuration file:

cp .env.example .env

On Windows PowerShell:

Copy-Item .env.example .env

Configuration precedence is: environment variables, .env, then defaults in project_config.py. The main path and identity settings are:

ENV_NAME=ai4realnet_small
ENV_LOCATION=environment
AGENT_NAME=curriculum
AGENT_FACTORY=
ASSETS_DIR=assets
ARTIFACTS_DIR=artifacts

Training parameters, episode limits, thresholds, and seeds are documented in .env.example. Relative paths are resolved from the repository root. To use a different policy, set AGENT_FACTORY=module:function; the factory receives the Grid2Op environment and returns an agent with an act method.

Pipeline

Run the full training pipeline with the values configured in .env:

python main.py train

Valid artifacts are reused automatically. Force individual stages when needed:

python main.py train --force-stage enn
python main.py train --force-stage forecast --force-stage classifier
python main.py train --force-stage all

Available stages are enn-data, enn, forecast, failure-rows, classifier, explainability, and all. Run python main.py train --help for all options, or python main.py status to see what would run. The preflight table states why each stage runs, e.g. train (rows will be re-collected).

Supplied models are never replaced implicitly. In operating mode the trained models are present but their training inputs (rollouts/observations.npy, labels.npy, failure_forecast_rows.csv) may not be. If a valid ENN bundle or failure classifier would be retrained without an explicit --force-stage (for its own stage or an upstream one), train stops after the preflight table, before any stage runs or any *.provenance.json is written:

# rows missing, valid classifier present -> stops; to rebuild deliberately:
python main.py train --force-stage failure-rows

Existing explanation rules (failure_forecast/explainability/rules/) are reused by train --profile; they are regenerated only with --force-stage explainability (or all), or when the same run retrains the classifier they were distilled from.

ENN Training

To train only the uncertainty model:

python training/collect_rollouts.py --agent-name curriculum --episodes 50
python training/train_enn.py --agent-name curriculum

See training/TRAINING.md for artifact formats, training options, and failure-forecast stages.

API

Run the API locally:

uvicorn app.main:app --host 0.0.0.0 --port 8000

Or build and run it with Docker:

docker build -t curriculum-agent-api .
docker run --env-file .env -p 8000:8000 curriculum-agent-api

Available endpoints:

GET  /health
GET  /diagnostics
GET  /docs
POST /api/v1/recommendation

Before requesting a recommendation, confirm that /diagnostics reports artifact_validation.ok: true and services.can_load: true. In Swagger at http://localhost:8000/docs, execute POST /api/v1/recommendation with:

{
  "event": {},
  "context": {}
}

An empty context uses env.reset() for a smoke test. A successful response is a list of recommendation dictionaries containing actions and kpis. The KPI object includes the uncertainty percentage, total and action percentiles, and uncertainty/confidence levels.

See Docker Instructions and app/API.md for operational details and the complete request/response contract.

Tests

Run the synthetic test suite:

python -m unittest discover -s tests -v

These tests cover ENN inference, uncertainty KPIs, the FastAPI contract, and failure-forecast behavior without requiring trained weights or a live Grid2Op environment.

Project Structure

.
|-- app/                         FastAPI service and recommendation formatter
|-- artifacts/                   Generated rollouts and trained models
|-- assets/                      Trained policy model and action set
|-- curriculumagent/             CurriculumAgent implementation
|-- environment/                 Local Grid2Op scenarios
|-- src/                         Shared agent, data, and ENN modules
|   `-- workflows/               demo, train, smoke, and status commands
|-- tests/                       Synthetic unit and API tests
|-- training/                    Data collection and training scripts
|-- project_config.py            Shared environment configuration
|-- main.py                      Single entry point (status/demo/train/smoke)
`-- recommendation_uncertainty.py

Legacy Workflow

The original tutor-data ENN pipeline is no longer present in the working tree. Its latest retained snapshot is commit 08781bf from 14 August 2026. Inspect the snapshot without changing the current checkout with:

git show --stat --oneline 08781bf
git show 08781bf:run_pipeline.py

The optional LLM rule-distillation integration lives in src/explainability/; it can annotate smoke predictions without changing the active classifier result. See src/explainability/README.md.

Run the disposable end-to-end smoke workflow with explanations using:

python main.py smoke --llm-config path\to\llm_config.json

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages