CoolFace
Apppublic

s123hree/green-code-optimizer-a100

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
App README

🌱 Green-Code Optimizer

An RL agent that refactors Python code for energy efficiency, not readability β€” and tells you exactly how much COβ‚‚ it saves.

![HF Space](https://huggingface.co/spaces/s123hree/green-code-optimizer-a100) ![Repository](https://github.com/bcde123/Meta-Round2) ![Blog Post](https://github.com/bcde123/Meta-Round2/blob/main/blog_post.md)


🎯 The Problem

AI workloads are projected to consume 2–4 % of global electricity by 2030. Most of that goes to training, but inference at scale β€” the same algorithms running millions of times a day in production β€” is the silent giant. A single inefficient nested loop in a hot path, replicated across millions of executions, can add up to real COβ‚‚.

Meanwhile, almost every existing code-refactoring tool optimises for readability (line length, naming, type hints). None of them refactor for energy.

*What if we trained an RL agent whose only goal was to make Python cheaper to run β€” measured in CPU cycles, memory footprint, and ultimately grams of COβ‚‚?*

That's the Green-Code Optimizer.


πŸ’‘ The Pitch

Existing refactoring toolsGreen-Code Optimizer
Optimise for readabilityOptimise for energy
Style / naming / lintCPU time + peak memory
Subjective rulesMeasurable, runtime-grounded reward
Outputs cleaner codeOutputs cheaper code + a COβ‚‚ dashboard

The agent receives a negative reward for high peak memory and high execution time, and a positive reward for the opposite. It uses graphlet analysis to represent the program's control-flow structure, so it learns which structural patterns (nested loops, function calls inside loops, deep branching) are expensive β€” and swaps them for cheap alternatives (vectorised ops, comprehensions, hoisted invariants).


πŸ‘€ Concrete Example

A real corruption from the env (Level-1 episode):

Before β€” a list comprehension is exploded into an append-loop, and a 50-iteration energy-waste loop is injected at the top:

python
def get_priority_users(users):
    _energy_waste = []
    for _ in range(50):
        _energy_waste.append(list(range(100)))
    out = []
    for u in users:
        out.append(u.upper())
    return out

After β€” the agent's target refactor:

python
def get_priority_users(users):
    return [u.upper() for u in users]

Impact (at 10 000 runs/day): ~1.1 kg COβ‚‚/year saved per call site. With one trained agent and a few thousand call sites, you're talking about trees worth of carbon.


βš™οΈ How It Works

mermaid
flowchart LR
    A["Corrupted /<br/>energy-inefficient<br/>Python codebase"] --> B[Episode Generator]
    B --> C["RL Agent<br/>(Qwen-1.5B + LoRA)"]
    C -->|edits| D[Updated codebase]
    D --> E1[Graphlet Analyzer]
    D --> E2[CPU + Memory Profiler]
    D --> E3[Compliance / Test Gate]
    E1 --> R[GRPO Reward]
    E2 --> R
    E3 --> R
    R -->|policy update| C
    D --> F["COβ‚‚ Dashboard<br/>kg/year Β· trees Β· car-km"]

1. Episode Generation with Curriculum-Driven Corruption

Each episode loads a real Python codebase and applies energy-degrading corruptions that scale with the agent's skill:

Curriculum levelEnergy corruptionsReadability corruptionsActive rules
1 (warmup)1120
22260
33 (all)3100
4 (expert)3 (all, 2Γ— passes)4140

The CurriculumManager escalates the level once 3 consecutive 50-episode windows all average a reward > 0.7 β€” so the agent's own progress drives the difficulty.

2. Graphlet Analysis β€” environment/graphlet_analyzer.py

Parses each file into an AST and detects 4 classes of expensive control-flow graphlets:

GraphletCost weightExample
NestedLoop3.0for i: for j: ...
LoopWithCall1.5for x: f(x)
DeepBranch2.0if … if … if … (β‰₯ 3 deep)
RepeatedComprehension1.0Multiple list-comps in one fn

Lower total cost β†’ higher graphlet score (range [0, 1]).

3. Runtime Profiling β€” environment/track_c.py

Each candidate refactor is actually executed in a timeout-bounded subprocess profiler: CPU time via time.perf_counter, peak memory via tracemalloc. If a file cannot be safely executed, Track C falls back to compile-time profiling so training never hangs.

4. Composable Rubric β€” environment/rubrics.py

Following OpenEnv RFC 004, the reward is a tree of named, composable child rubrics β€” modeled on PyTorch's nn.Module. When openenv-core is installed we extend its Rubric base class directly; otherwise we provide a zero-dependency fallback shim with the same surface area.

GreenCodeRubric                       (root)
└─ Sequential                         ← short-circuits if any gate fails
   β”œβ”€ syntax_gate     {0,1}           ← reward = 0 if any file doesn't parse
   β”œβ”€ hack_gate       {0,1}           ← reward = -1 if test files are tampered with
   └─ WeightedSum                     ← soft signals
      β”œβ”€ green       (0.70)
      β”‚  β”œβ”€ graphlet (0.40) ∈ [0,1]
      β”‚  β”œβ”€ cpu      (0.35) ∈ [0,1]
      β”‚  └─ memory   (0.25) ∈ [0,1]
      └─ compliance  (0.30)

Each child is independently inspectable via rubric.named_rubrics(), so training infrastructure logs every component without modifying the rubric. Adding a new signal (e.g. a Big-O complexity penalty) is a 5-line subclass + WeightedSum weight tweak.

The rubric tree is also exposed at runtime via GET /rubric so judges can introspect the reward without touching server internals.

R = (syntax_gate ∧ hack_gate) Γ— (0.70Β·green + 0.30Β·compliance) βˆ’ P_efficiency
  • β€”Why this is hard to game β€” the Sequential short-circuits any soft reward when the syntax gate fails. Agents can't get points for "memory-efficient" code that doesn't compile.
  • β€”`P_efficiency` β€” 0.01 per file edited; held outside the rubric (it's a training-time minimal-edits nudge, not a property of the env).

5. COβ‚‚ Dashboard β€” environment/co2_calculator.py

CPU-time savings Γ— CPU TDP Γ— grid carbon intensity β†’ kg COβ‚‚/year, with real-world equivalents (tree-years, car-km). Live HTML dashboard at /dashboard/co2/{episode_id}.


πŸ“Š Evidence the Agent Actually Learns

We ran a 25-episode baseline comparison before any RL training, scoring policies on identical episodes:

PolicyMean rewardGreen scoreComplianceCOβ‚‚ saved/year
No-op (does nothing)0.2700.3860.000.42 kg
Oracle (cheats β€” sees the answer)0.5270.3920.840.83 kg
Trained agent (after fast A100 GRPO run)TBD β€” fill in after runTBDTBDTBD

The 96 % gap between no-op and oracle proves the env has a strong, learnable signal. Reproduce locally:

bash
python training/compare_baseline.py --num-episodes 20
# β†’ assets/baseline_vs_trained.png + .json

[image]

Training curves

training/train_grpo.py writes assets/training_curves.png and assets/log_history.json after the A100 GRPO run. Commit those files immediately after the final run so judges can verify the real loss/reward curves.


πŸ† Why This Wins (mapped to judging criteria)

CriterionWeightWhat we deliver
Environment Innovation40 %Graphlet-based control-flow analysis as a learnable structure prior; runtime-grounded reward (not subjective rules); COβ‚‚ dashboard converting reward into real-world impact; curriculum that escalates corruption intensity, not just rule count.
Storytelling & Presentation30 %Live /demo page with side-by-side before/after; rich HTML COβ‚‚ dashboard at /dashboard/co2/{id}; concrete worked example in this README.
Showing Improvement20 %Pre-training baseline vs. oracle ceiling already shipped (96 % spread proves signal); auto-saved loss + reward curves from train_grpo.py; baseline comparison reproducible in one command.
Reward & Pipeline Coherence10 %Multiplicative test-gate Γ— (0.70 green + 0.30 compliance) βˆ’ Peff. Hard gate prevents reward-hacking via broken code. Anti-cheat layer (`Phack`) penalises tampering with test infrastructure.

πŸ”— Submission Links

ResourceLink
πŸ€— HF Spacehttps://huggingface.co/spaces/s123hree/green-code-optimizer-a100
πŸ§‘β€πŸ’» Repositoryhttps://github.com/bcde123/Meta-Round2
πŸ“ Blog Posthttps://github.com/bcde123/Meta-Round2/blob/main/blog_post.md

🧩 OpenEnv Compatibility

This env follows the OpenEnv spec (RFC 001 + RFC 004).

  • β€”Manifest: `openenv.yaml`
  • β€”Server: uses openenv-core>=0.2.3 for the Rubric base class
  • β€”Gym-style API: POST /reset, POST /step, GET /state/{id}
  • β€”Rubric introspection: GET /rubric returns the named child tree
  • β€”Sync client: `client.py` β€” drop-in EnvClient, mirrors HTTPEnvClient
  • β€”Observation space: { files, violation_report, steps_remaining, curriculum_level }
  • β€”Action space: [read_file, edit_file, run_tests, check_compliance]
  • β€”Reward range: [-1.0, 1.0]
  • β€”Max episode length: 70 steps
python
# Three-line judge-friendly usage:
from client import GreenCodeEnv
env = GreenCodeEnv("https://s123hree-green-code-optimizer-a100.hf.space")
obs = env.reset(curriculum_level=2)        # gym-style reset
state = env.state()                         # gym-style state
print(env.rubric_tree())                    # introspect the reward

πŸ“š API

EndpointMethodDescription
/demoGET🌱 Start here β€” live before/after demo
/dashboard/co2/{episode_id}GETCOβ‚‚-savings dashboard (HTML for browsers, JSON otherwise)
/rubricGETRubric tree β€” named children + formula
/GETProject info
/health Β· /health/greenGETHealth checks
/docsGETSwagger UI
/resetPOSTStart a new episode (Gym API)
/stepPOSTSubmit an edit (Gym API)
/state/{episode_id}GETEpisode metadata (Gym API)
/inferPOSTRun trained agent (GPU)

πŸš€ Quickstart

Run the env locally

bash
git clone https://huggingface.co/spaces/s123hree/green-code-optimizer-a100
cd green-code-optimizer-a100
pip install -r requirements.txt
uvicorn server:app --host 0.0.0.0 --port 7860
# Visit http://localhost:7860/demo

Reproduce training (A100, deadline-safe)

The Space defaults to a fast final run: TRAIN_MAX_STEPS=80, TRAIN_NUM_GENERATIONS=2, TRAIN_NUM_EPISODES=80, LORA_RANK=8, and compile-mode green profiling. Increase these env vars only if you have extra time.

Reproduce baseline comparison (CPU, ~30 s)

bash
python training/compare_baseline.py --num-episodes 20

Smoke-test the deployed Space

bash
SPACE_URL=https://s123hree-green-code-optimizer-a100.hf.space \
  python test_deployment.py

πŸ›  Repository Layout

.
β”œβ”€β”€ server.py                    # FastAPI: /reset /step /state /rubric /demo /dashboard
β”œβ”€β”€ client.py                    # Sync EnvClient β€” mirrors OpenEnv HTTPEnvClient
β”œβ”€β”€ inference.py                 # Loads adapter from HF Hub, runs predictions
β”œβ”€β”€ openenv.yaml                 # OpenEnv manifest
β”œβ”€β”€ Dockerfile                   # HF Space image
β”œβ”€β”€ blog_post.md                 # Writeup (problem β†’ env β†’ rubric β†’ results)
β”œβ”€β”€ environment/
β”‚   β”œβ”€β”€ rubrics.py               # ⭐ Composable Rubric tree (RFC 004)
β”‚   β”œβ”€β”€ episode_generator.py     # Corruption pipeline + curriculum
β”‚   β”œβ”€β”€ track_a.py               # Code-quality evaluator
β”‚   β”œβ”€β”€ track_b.py               # Compliance checker
β”‚   β”œβ”€β”€ track_c.py               # Green-code evaluator (CPU + memory)
β”‚   β”œβ”€β”€ graphlet_analyzer.py     # Control-flow pattern detection
β”‚   β”œβ”€β”€ co2_calculator.py        # CPU-time β†’ kg COβ‚‚/year
β”‚   β”œβ”€β”€ rule_engine.py           # 150-rule cascading rule engine
β”‚   β”œβ”€β”€ ENGINEERING_STANDARDS.md # The 150 rules
β”‚   └── base_codebase/           # Original clean Python codebase
β”œβ”€β”€ training/
β”‚   β”œβ”€β”€ train_grpo.py            # GRPO trainer with auto-plotting
β”‚   β”œβ”€β”€ compare_baseline.py      # Baseline-vs-trained comparison
β”‚   └── verify_pipeline.py       # CPU-only pipeline sanity check
β”œβ”€β”€ notebooks/train_grpo.ipynb   # Colab-ready training notebook
└── assets/
    β”œβ”€β”€ baseline_vs_trained.png
    β”œβ”€β”€ baseline_vs_trained.json
    β”œβ”€β”€ system_architecture_diagram.png
    β”œβ”€β”€ architecture_pipeline.png
    └── co2_pipeline_diagram.png

🀝 Extending the Env

  • β€”New reward signal β†’ write a 5-line Rubric subclass and add it to the WeightedSum in environment/rubrics.py::build_green_rubric. Every leaf is auto-logged via named_rubrics().
  • β€”New graphlet patterns β†’ add to PATTERN_COSTS in environment/graphlet_analyzer.py.
  • β€”New energy-degrading corruptions β†’ add a method to EpisodeGenerator and append it to energy_corruptions list.
  • β€”Tune carbon constants for your region's grid β†’ environment/co2_calculator.py.
python
# Drop-in custom rubric example:
from environment.rubrics import Rubric, build_green_rubric, WeightedSum

class BigOPenalty(Rubric):
    def forward(self, action, observation) -> float:
        # ... your big-O analysis ...
        return score   # range [0, 1]

base = build_green_rubric()
base.green = WeightedSum(
    [base.green.graphlet, base.green.cpu, base.green.memory, BigOPenalty()],
    weights=[0.30, 0.30, 0.20, 0.20],
)

πŸ“œ License

Apache-2.0. Fork it, use it, save some carbon.


Built for the OpenEnv India Hackathon 2026 β€” Meta PyTorch.