sanjithp-dev commited on
Commit
d3aebf9
Β·
verified Β·
1 Parent(s): 5a0432e

Readme updated82

Browse files
Files changed (1) hide show
  1. README.md +155 -91
README.md CHANGED
@@ -1,96 +1,160 @@
1
- import os
2
- import sys
3
- import torch
4
- import matplotlib.pyplot as plt
5
- from datasets import load_dataset
6
- from trl import GRPOTrainer, GRPOConfig
7
- from unsloth import FastLanguageModel, PatchFastRL
8
-
9
- # ── 1. PATCH & ENVIRONMENT SETUP ──
10
- PatchFastRL("GRPO", FastLanguageModel)
11
-
12
- # Force Colab to see your disaster_grid package
13
- repo_path = "/content/repo"
14
- if repo_path not in sys.path:
15
- sys.path.insert(0, repo_path)
16
-
17
- # Manual imports to bypass standard ModuleNotFound issues
18
- from src.disaster_grid.environment import CityGrid
19
- from src.disaster_grid.rewards import compute_reward
20
-
21
- # ── 2. LOAD MODEL & TOKENIZER ──
22
- model, tokenizer = FastLanguageModel.from_pretrained(
23
- model_name = "unsloth/llama-3-8b-Instruct-bnb-4bit",
24
- max_seq_length = 1024,
25
- load_in_4bit = True,
26
- )
27
 
28
- # ── 3. DATASET PREPARATION ──
29
- # Loading the small synthetic dataset for rapid alignment
30
- dataset = load_dataset("json", data_files=f"{repo_path}/train/synthetic_data.json", split="train")
31
-
32
- # ── 4. REWARD FUNCTION WRAPPER ──
33
- env = CityGrid()
34
-
35
- def disaster_reward_func(prompts, completions, **kwargs):
36
- """Executes model actions in the physics engine to calculate R1/R2/R3."""
37
- rewards = []
38
- for prompt, completion in zip(prompts, completions):
39
- env.reset()
40
- # Extract content from assistant response
41
- content = completion[0]["content"] if isinstance(completion, list) else completion
42
-
43
- # Step through environment and get the verifier receipt
44
- obs, reward_env, done, truncated, info = env.step(content)
45
-
46
- # Calculate final weighted score
47
- score = compute_reward(info)
48
- rewards.append(score)
49
- return rewards
50
-
51
- # ── 5. TRAINER CONFIGURATION ──
52
- training_args = GRPOConfig(
53
- output_dir = "grpo_results",
54
- learning_rate = 2e-5,
55
- logging_steps = 5,
56
- max_steps = 100,
57
- per_device_train_batch_size = 2,
58
- gradient_accumulation_steps = 2,
59
- max_completion_length = 128,
60
- report_to = "none", # Faster without tracking
61
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  trainer = GRPOTrainer(
64
- model = model,
65
- reward_funcs = [disaster_reward_func],
66
- args = training_args,
67
- train_dataset = dataset,
68
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- # ── 6. TRAIN & GRAPH ──
71
- print("πŸš€ Starting High-Speed GRPO Training...")
72
- try:
73
- trainer.train()
74
- finally:
75
- # Plotting logic for your final presentation
76
- history = trainer.state.log_history
77
- steps = [log["step"] for log in history if "reward" in log]
78
- rewards = [log["reward"] for log in history if "reward" in log]
79
-
80
- if steps:
81
- plt.figure(figsize=(10, 5))
82
- plt.plot(steps, rewards, marker='o', color='#10b981', linewidth=2)
83
- plt.title('Agent Learning Curve (GRPO Reward over Time)', color='white')
84
- plt.xlabel('Steps', color='gray')
85
- plt.ylabel('Average Reward', color='gray')
86
- plt.gca().set_facecolor('#1e1e1e')
87
- plt.gcf().patch.set_facecolor('#1e1e1e')
88
- plt.savefig('learning_curve.png', bbox_inches='tight', dpi=300)
89
- plt.show()
90
- print("βœ… Graph saved as 'learning_curve.png'")
91
-
92
- # ── 7. SAFE SAVING (Avoiding Mergekit Errors) ──
93
- # We save as LoRA adapters to avoid needing mergekit
94
- model.save_pretrained("disaster_agent_lora")
95
- tokenizer.save_pretrained("disaster_agent_lora")
96
- print("βœ… Training complete. Brain saved to 'disaster_agent_lora'.")2399
 
1
+ ---
2
+ title: AI-Kinetic Disaster Recovery Grid
3
+ emoji: πŸ™οΈ
4
+ colorFrom: red
5
+ colorTo: yellow
6
+ sdk: docker
7
+ app_file: app.py
8
+ pinned: true
9
+ license: mit
10
+ short_description: Multi-Agent RL crisis-grid recovery on OpenEnv
11
+ tags:
12
+ - reinforcement-learning
13
+ - multi-agent
14
+ - openenv
15
+ - pytorch
16
+ - llm-agents
17
+ - hackathon
18
+ ---
 
 
 
 
 
 
 
 
19
 
20
+ # πŸ™οΈ AI-Kinetic Disaster Recovery Grid
21
+
22
+ > A Multi-Agent Reinforcement Learning environment built on **OpenEnv** for the **Meta PyTorch Γ— Scaler OpenEnv Hackathon**.
23
+
24
+ ---
25
+
26
+ ## 🚨 Problem Statement
27
+
28
+ Modern Large Language Models excel at conversational tasks and static reasoning, but they fail catastrophically at **real-time resource management** and **long-horizon planning** during active crises.
29
+
30
+ When a disaster strikes β€” a solar flare, cyber-attack, or severe weather event β€” infrastructure grids suffer cascading failures. In these scenarios:
31
+
32
+ - **Information is sparse.** Communication lines sever, creating partial observability.
33
+ - **Resources are finite.** Repairing one sector may mean abandoning another.
34
+ - **Rewards are delayed.** Actions taken now (gathering tools) may not yield results until much later.
35
+
36
+ Traditional centralized AI models assume perfect information and unlimited bandwidth. Placed in a constrained, decaying environment, they collapse.
37
+
38
+ ---
39
+
40
+ ## πŸ’‘ The Proposed Solution
41
+
42
+ We built the **AI-Kinetic Disaster Recovery Grid** β€” a Multi-Agent Reinforcement Learning (MARL) environment. Instead of a single "Omni-Agent," we deployed a distributed team of specialized agents acting on a dynamic 5Γ—5 city grid.
43
+
44
+ ### Agent Roles
45
+
46
+ | Agent | Role |
47
+ |---|---|
48
+ | πŸ› οΈ **Scavenger** | Navigates the grid to collect scarce battery packs and repair parts. |
49
+ | βš™οΈ **Engineer** | Executes complex, multi-step repair sequences. |
50
+ | πŸ“‘ **Dispatcher** | Holds the global map and intelligently guides the field agents. |
51
+
52
+ ---
53
+
54
+ ## βš™οΈ Workflow
55
+
56
+ ### 1. Environment Simulation (OpenEnv)
57
+
58
+ The world is modeled as a 5Γ—5 matrix using `openenv-core`. Each sector tracks internal state: **Health**, **Power**, and **Risk**.
59
+
60
+ ![OpenEnv Local Development Configuration](./assets/environment_config.jpeg)
61
+ *VS Code showing `environment.py` defining the `CityGrid` class and episode dynamics.*
62
+
63
+ ### 2. Training Scripts (GRPO + Unsloth)
64
+
65
+ We used **Group Relative Policy Optimization (GRPO)**, accelerated with **Unsloth** to manage memory constraints during training.
66
+
67
+ ```python
68
+ from openenv import OpenEnvGrid
69
+ from trl import GRPOTrainer
70
+
71
+ env = OpenEnvGrid(size=5, agents=["scavenger", "engineer", "dispatcher"])
72
 
73
  trainer = GRPOTrainer(
74
+ model="meta-llama/Llama-3-8B",
75
+ args=config,
76
+ train_dataset=env.get_training_data(),
 
77
  )
78
+ trainer.train()
79
+ ```
80
+
81
+ ---
82
+
83
+ ## πŸ§ͺ Validation
84
+
85
+ ### Local Validation & Execution
86
+
87
+ Before pushing to the Hugging Face Space, we validate agent logic and entropy sequences via a local CLI built on `openenv-core` for rapid debugging of the 5Γ—5 grid state transitions.
88
+
89
+ <video controls src="./assets/validation_video.mp4" width="100%"></video>
90
+
91
+ ![Local Terminal Simulation Output](./assets/terminal_output.jpeg)
92
+ *Local terminal simulator showing a completed 50-step sequence tracking City Health and Energy metrics.*
93
+
94
+ ### Live Agent Simulation (Operational Theatre)
95
+
96
+ To visualize multi-agent orchestration, we built a web-based UI β€” the **Operational Theatre** β€” deployed on Hugging Face Spaces. It allows random anomaly injection while observing LLM-powered agents respond in real time.
97
+
98
+ <video controls src="./assets/operational_theatre.mp4" width="100%"></video>
99
+ *HF Space UI showing the autonomous agent navigating the grid with the Agent Brain Log streaming reasoning.*
100
+
101
+ ---
102
+
103
+ ## 🌍 Real-World Applications
104
+
105
+ - **Autonomous Smart Grid Management** β€” Dynamically rerouting power around physical failures to prevent cascading blackouts.
106
+ - **Search and Rescue Drone Swarms** β€” Coordinating ground and air drones in disaster zones with limited battery life.
107
+ - **Self-Healing Server Networks** β€” Autonomously rerouting global traffic and deploying patches during cyber-attacks.
108
+
109
+ ---
110
+
111
+ ## βš–οΈ Advantages & Trade-offs
112
+
113
+ ### βœ… Advantages
114
+
115
+ - **Task Specialization** β€” Specialized roles converge faster than a single omni-agent.
116
+ - **Fault Tolerance** β€” No single point of failure; the Dispatcher reroutes around incapacitated agents.
117
+ - **Realistic Observability** β€” Native "fog of war," forcing agents to communicate to gain a global view.
118
+
119
+ ### ⚠️ Trade-offs
120
+
121
+ - **Credit Assignment** β€” Hard to reward early strategic moves whose payoff arrives many steps later.
122
+ - **Non-Stationarity** β€” Other agents act simultaneously, making convergence non-trivial.
123
+
124
+ ---
125
+
126
+ ## πŸ“ˆ Scalability
127
+
128
+ The architecture scales via **Hierarchical Multi-Agent Systems (HMAS)**. In a city-wide deployment, this 5Γ—5 grid represents a single *Neighborhood*. Each Neighborhood Dispatcher reports to a higher-level **Zone Commander**, allowing the system to manage thousands of nodes without overwhelming any individual agent's context window.
129
+
130
+ ---
131
+
132
+ ## πŸš€ Run It Locally
133
+
134
+ ```bash
135
+ git clone https://huggingface.co/spaces/<your-username>/disaster-grid
136
+ cd disaster-grid
137
+
138
+ python -m venv .venv
139
+ source .venv/bin/activate # or .venv\Scripts\Activate.ps1 on Windows
140
+
141
+ pip install -e .
142
+
143
+ # Run the local CLI simulator
144
+ python -m src.disaster_grid.utils
145
+
146
+ # Or launch the operational theatre
147
+ python app.py
148
+ ```
149
+
150
+ **Controls in CLI mode:** `W/A/S/D` to move Β· `R` to repair Β· `C` to recharge Β· `Q` to wait Β· `EXIT` to terminate.
151
+
152
+ ---
153
+
154
+ ## 🏁 Conclusion
155
+
156
+ The **AI-Kinetic Disaster Recovery Grid** demonstrates that LLMs can transition from *strategic chatting* to **strategic action**. By implementing multi-agent coordination inside a decaying environment, we are engineering the autonomous emergency responders of the future.
157
+
158
+ ---
159
 
160
+ *Developed by **Sanjith P** and **Varsha D** for the Meta PyTorch Γ— Scaler OpenEnv Hackathon.*