kavin57447 commited on
Commit
ee3dfa7
·
1 Parent(s): 1c86d42

Add LLM RL training with Gemma 7B + LoRA

Browse files
app.py CHANGED
@@ -1,7 +1,8 @@
1
  """
2
- Cloud Arena — Mathematical Model RL Training on HF Spaces
3
- This is the MATHEMATICAL model (MaskablePPO + MLP), NOT the LLM model.
4
- The LLM model (cell5_ppo.py) is a SEPARATE system.
 
5
  """
6
 
7
  import os
@@ -11,25 +12,17 @@ import numpy as np
11
  os.makedirs("./models", exist_ok=True)
12
  os.makedirs("./outputs", exist_ok=True)
13
 
14
- # Global state
15
- training_state = {"model": None, "callback": None, "status": "idle"}
16
 
 
17
 
18
- def run_training(timesteps):
19
  from cloud_arena.training import train_model
20
- training_state["status"] = "training"
21
  try:
22
- ts = int(timesteps)
23
- model, callback, _ = train_model(total_timesteps=ts)
24
- training_state["model"] = model
25
- training_state["callback"] = callback
26
- training_state["status"] = "done"
27
-
28
  from cloud_arena.visualization import generate_dashboard
29
  img_path = generate_dashboard(callback, "outputs/dashboard.png")
30
-
31
  summary = (
32
- f"✅ Training Complete\n"
33
  f"Episodes: {len(callback.episode_rewards)}\n"
34
  f"Final Phase: {callback.current_level}\n"
35
  f"EMA Win Rate: {callback.ema_win_rate*100:.1f}%\n"
@@ -37,11 +30,10 @@ def run_training(timesteps):
37
  )
38
  return summary, img_path
39
  except Exception as e:
40
- training_state["status"] = "error"
41
  return f"❌ Error: {e}", None
42
 
43
 
44
- def run_evaluation():
45
  from cloud_arena.evaluation import evaluate_model
46
  try:
47
  results = evaluate_model()
@@ -50,47 +42,68 @@ def run_evaluation():
50
  sec = np.mean(results["security_score"])
51
  sav = np.mean(results["savings_pct"])
52
  return (
53
- f"Win Rate: {wr:.1f}%\n"
54
- f"Cost Score: {cost:.3f}\n"
55
- f"Security: {sec:.3f}\n"
56
- f"Savings: {sav:.1f}%"
57
  )
58
  except Exception as e:
59
  return f"❌ Error: {e}"
60
 
61
 
62
- def run_bosses():
63
- from cloud_arena.evaluation import run_boss_fights, BOSS_NAMES
 
 
64
  try:
65
- scores = run_boss_fights()
66
- lines = [f"{BOSS_NAMES[k]}: {v:.1f}%" for k, v in scores.items()]
67
- overall = np.mean(list(scores.values()))
68
- lines.append(f"\nOverall: {overall:.1f}%")
69
- return "\n".join(lines)
 
 
 
 
 
 
 
 
 
 
70
  except Exception as e:
71
- return f"❌ Error: {e}"
 
 
72
 
 
73
 
74
  with gr.Blocks(title="Cloud Arena RL") as demo:
75
- gr.Markdown("# ☁️ Cloud Arena — Mathematical Model RL")
76
- gr.Markdown("MaskablePPO training on a multi-objective cloud ops environment.")
77
 
78
- with gr.Tab("Train"):
 
79
  ts_input = gr.Number(value=500000, label="Total Timesteps")
80
- train_btn = gr.Button("🚀 Start Training", variant="primary")
81
- train_output = gr.Textbox(label="Status", lines=6)
82
- train_img = gr.Image(label="Dashboard")
83
- train_btn.click(run_training, inputs=ts_input, outputs=[train_output, train_img])
84
-
85
- with gr.Tab("Evaluate"):
86
- eval_btn = gr.Button("📊 Run Evaluation")
87
- eval_output = gr.Textbox(label="Results", lines=8)
88
- eval_btn.click(run_evaluation, outputs=eval_output)
89
-
90
- with gr.Tab("Boss Fights"):
91
- boss_btn = gr.Button("⚔️ Run Boss Fights")
92
- boss_output = gr.Textbox(label="Boss Scores", lines=8)
93
- boss_btn.click(run_bosses, outputs=boss_output)
 
 
 
 
 
 
 
94
 
95
  if __name__ == "__main__":
96
  demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Base())
 
1
  """
2
+ Cloud Arena — RL Training on HF Spaces
3
+ Two SEPARATE models:
4
+ 1. Mathematical Model (MaskablePPO + MLP) tab "Math RL"
5
+ 2. LLM Model (LLaMA 3.1 8B + REINFORCE + LoRA) — tab "LLM RL"
6
  """
7
 
8
  import os
 
12
  os.makedirs("./models", exist_ok=True)
13
  os.makedirs("./outputs", exist_ok=True)
14
 
 
 
15
 
16
+ # ── Mathematical Model Training ──────────────────────────────────────────────
17
 
18
+ def run_math_training(timesteps):
19
  from cloud_arena.training import train_model
 
20
  try:
21
+ model, callback, _ = train_model(total_timesteps=int(timesteps))
 
 
 
 
 
22
  from cloud_arena.visualization import generate_dashboard
23
  img_path = generate_dashboard(callback, "outputs/dashboard.png")
 
24
  summary = (
25
+ f"✅ Math Model Training Complete\n"
26
  f"Episodes: {len(callback.episode_rewards)}\n"
27
  f"Final Phase: {callback.current_level}\n"
28
  f"EMA Win Rate: {callback.ema_win_rate*100:.1f}%\n"
 
30
  )
31
  return summary, img_path
32
  except Exception as e:
 
33
  return f"❌ Error: {e}", None
34
 
35
 
36
+ def run_math_evaluation():
37
  from cloud_arena.evaluation import evaluate_model
38
  try:
39
  results = evaluate_model()
 
42
  sec = np.mean(results["security_score"])
43
  sav = np.mean(results["savings_pct"])
44
  return (
45
+ f"Win Rate: {wr:.1f}%\nCost Score: {cost:.3f}\n"
46
+ f"Security: {sec:.3f}\nSavings: {sav:.1f}%"
 
 
47
  )
48
  except Exception as e:
49
  return f"❌ Error: {e}"
50
 
51
 
52
+ # ── LLM Model Training ───────────────────────────────────────────────────────
53
+
54
+ def run_llm_training(model_name, num_iterations, steps_per_episode):
55
+ from cloud_arena.llm_training import train_llm
56
  try:
57
+ all_rewards, full_log, graph_path, log_text = train_llm(
58
+ model_name=model_name,
59
+ num_iterations=int(num_iterations),
60
+ steps_per_episode=int(steps_per_episode),
61
+ )
62
+ delta = all_rewards[-1] - all_rewards[0]
63
+ summary = (
64
+ f"✅ LLM Training Complete\n"
65
+ f"Model: {model_name}\n"
66
+ f"Pre-training reward: {all_rewards[0]:+.3f}\n"
67
+ f"Post-training reward: {all_rewards[-1]:+.3f}\n"
68
+ f"Δ Change: {delta:+.3f}\n\n"
69
+ f"─── Full Log ───\n{log_text}"
70
+ )
71
+ return summary, graph_path
72
  except Exception as e:
73
+ import traceback
74
+ return f"❌ Error: {e}\n{traceback.format_exc()}", None
75
+
76
 
77
+ # ── Gradio UI ─────────────────────────────────────────────────────────────────
78
 
79
  with gr.Blocks(title="Cloud Arena RL") as demo:
80
+ gr.Markdown("# ☁️ Cloud Arena — RL Training Space")
81
+ gr.Markdown("Two separate RL systems: **Mathematical Model** (MaskablePPO) and **LLM Model** (LLaMA + LoRA)")
82
 
83
+ with gr.Tab("🧮 Math RL"):
84
+ gr.Markdown("### Mathematical Model — MaskablePPO (MLP Neural Network)")
85
  ts_input = gr.Number(value=500000, label="Total Timesteps")
86
+ train_btn = gr.Button("🚀 Start Math Training", variant="primary")
87
+ math_output = gr.Textbox(label="Status", lines=6)
88
+ math_img = gr.Image(label="Dashboard")
89
+ train_btn.click(run_math_training, inputs=ts_input, outputs=[math_output, math_img])
90
+
91
+ gr.Markdown("---")
92
+ eval_btn = gr.Button("📊 Evaluate Math Model")
93
+ eval_output = gr.Textbox(label="Eval Results", lines=6)
94
+ eval_btn.click(run_math_evaluation, outputs=eval_output)
95
+
96
+ with gr.Tab("🧠 LLM RL"):
97
+ gr.Markdown("### LLM Model — Gemma 7B + REINFORCE + LoRA")
98
+ gr.Markdown("> ⚠️ Requires `HF_TOKEN` secret set in Space settings + accepted model license")
99
+ llm_model = gr.Textbox(value="google/gemma-7b-it", label="Model Name")
100
+ llm_iters = gr.Number(value=10, label="Training Iterations")
101
+ llm_steps = gr.Number(value=5, label="Steps per Episode")
102
+ llm_btn = gr.Button("🚀 Start LLM Training", variant="primary")
103
+ llm_output = gr.Textbox(label="Training Log", lines=15)
104
+ llm_img = gr.Image(label="Results")
105
+ llm_btn.click(run_llm_training, inputs=[llm_model, llm_iters, llm_steps],
106
+ outputs=[llm_output, llm_img])
107
 
108
  if __name__ == "__main__":
109
  demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Base())
cloud_arena/llm_environment.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # CELL 3 — Cloud FinOps Environment (Final Fixed Version)
3
+ #
4
+ # ALL loopholes closed:
5
+ # 1. CHECK_DEPENDENCIES after cap → hesitation penalty (not 0.0)
6
+ # This kills the "+0.200 every episode" passive policy
7
+ # 2. W_HESITATION = 0.10 — strong enough to force action
8
+ # 3. Win bonus +2.0 — rewards completing the goal, not just steps
9
+ # 4. RESIZE guaranteed to reduce cost (uniform 0.40-0.65)
10
+ # 5. MIN_DELETABLE_COST_RATIO = 0.35 — win is always reachable
11
+ # 6. Stronger semantic veto — also catches high-dependency temp nodes
12
+ # ============================================================
13
+
14
+ import numpy as np
15
+ import gymnasium as gym
16
+ from gymnasium import spaces
17
+ from enum import IntEnum
18
+ import random
19
+
20
+ random.seed(42)
21
+ np.random.seed(42)
22
+
23
+ # ─── Action Space ─────────────────────────────────────────────────────────────
24
+
25
+ class Action(IntEnum):
26
+ NOOP = 0
27
+ CHECK_DEPENDENCIES = 1
28
+ RESIZE = 2
29
+ STOP = 3
30
+ DELETE = 4
31
+
32
+ NUM_ACTIONS = len(Action)
33
+
34
+ # ─── Constants ────────────────────────────────────────────────────────────────
35
+
36
+ N_RESOURCES = 6
37
+ OBS_PER_RES = 5
38
+ OBS_DIM = N_RESOURCES * OBS_PER_RES + 2 # = 32
39
+
40
+ PROD_NAMES = [
41
+ "storage-prod-db", "core-auth-router", "primary-k8s-master",
42
+ "billing-db-01", "payment-gateway-prod", "prod-cache-redis",
43
+ "prod-elb-frontend", "rds-prod-main", "main-api-prod",
44
+ "prod-cosmos-db", "primary-gke-cluster", "prod-spanner-db",
45
+ ]
46
+ TEMP_NAMES = [
47
+ "worker-node-temp", "test-frontend-ui", "sandbox-db-04",
48
+ "batch-processor-temp", "dev-cache-redis", "temp-worker-88",
49
+ "staging-api-v2", "dev-log-collector", "temp-ecs-task",
50
+ "dev-gke-node", "test-bigquery-scratch", "sandbox-spanner-dev",
51
+ ]
52
+
53
+ # ─── Cloud Resource ───────────────────────────────────────────────────────────
54
+
55
+ class CloudResource:
56
+ def __init__(self, name, cost_per_hr, cpu_pct, dependencies, is_prod):
57
+ self.name = name
58
+ self.cost_per_hr = cost_per_hr
59
+ self.cpu_pct = cpu_pct
60
+ self.dependencies = dependencies
61
+ self.is_prod = is_prod
62
+ self.active = True
63
+
64
+ def to_obs_array(self):
65
+ return np.array([
66
+ self.cpu_pct / 100.0,
67
+ self.cost_per_hr / 5.0,
68
+ len(self.dependencies) / 14.0,
69
+ float(self.is_prod),
70
+ float(self.active),
71
+ ], dtype=np.float32)
72
+
73
+
74
+ # ─── Resource Generator ───────────────────────────────────────────────────────
75
+
76
+ def generate_resources(n=N_RESOURCES):
77
+ """
78
+ Creates a randomised pool of cloud resources per episode.
79
+
80
+ Guarantees:
81
+ 1. One production trap with low CPU (looks deletable but isn't)
82
+ 2. Temp resources account for >= 35% of total cost
83
+ so the 20% savings win condition is always reachable
84
+ """
85
+ resources = []
86
+
87
+ # Guaranteed prod trap — low CPU makes it look safe to delete
88
+ prod_name = random.choice(PROD_NAMES)
89
+ resources.append(CloudResource(
90
+ name = prod_name,
91
+ cost_per_hr = round(random.uniform(0.5, 3.0), 2),
92
+ cpu_pct = random.randint(2, 12),
93
+ dependencies = random.sample(TEMP_NAMES, k=random.randint(2, 4)),
94
+ is_prod = True,
95
+ ))
96
+
97
+ # Fill remaining slots with random mix
98
+ for _ in range(n - 1):
99
+ is_prod = random.random() < 0.30 # 30% chance prod
100
+ name_pool = PROD_NAMES if is_prod else TEMP_NAMES
101
+ dep_count = random.randint(1, 5) if is_prod else random.randint(0, 3)
102
+ resources.append(CloudResource(
103
+ name = random.choice(name_pool),
104
+ cost_per_hr = round(random.uniform(0.8, 4.0), 2),
105
+ cpu_pct = random.randint(1, 95),
106
+ dependencies = random.sample(TEMP_NAMES, k=min(dep_count, len(TEMP_NAMES))),
107
+ is_prod = is_prod,
108
+ ))
109
+
110
+ # ── Guarantee minimum deletable cost ratio ────────────────────────────
111
+ # Raises temp resource costs until they represent >= 35% of total.
112
+ # Without this guarantee, some episodes are mathematically unwinnable.
113
+ MIN_RATIO = 0.35
114
+ for _ in range(10): # iterate up to 10x to converge
115
+ total = sum(r.cost_per_hr for r in resources)
116
+ temp_total = sum(r.cost_per_hr for r in resources if not r.is_prod)
117
+ if total > 0 and (temp_total / total) < MIN_RATIO:
118
+ for r in resources:
119
+ if not r.is_prod:
120
+ r.cost_per_hr = round(r.cost_per_hr * 1.3, 2)
121
+ else:
122
+ break
123
+
124
+ return resources
125
+
126
+
127
+ # ─── Core Environment (OpenEnv dict API) ─────────────────────────────────────
128
+
129
+ class AWSCostEnv:
130
+ """
131
+ Cloud FinOps Optimisation Environment — OpenEnv dict API.
132
+ Wrap with SB3Adapter for stable-baselines3 PPO training.
133
+
134
+ REWARD FORMULA
135
+ --------------
136
+ Savings : clip(delta_cost_pct × W_SAVINGS, -5, +5)
137
+ Win bonus: +W_WIN_BONUS when savings >= target (one-time)
138
+ NOOP : -W_HESITATION per step
139
+ Tool : +W_TOOL per new node checked (capped at W_TOOL_EPISODE_CAP)
140
+ After cap → -W_HESITATION (closes passive policy loophole)
141
+ Veto : PENALTY_VETO (semantic guardrail blocked the action)
142
+ Crash : PENALTY_CRASH, episode ends immediately
143
+
144
+ KEY LOOPHOLE FIXES
145
+ ------------------
146
+ Fix 1 — CHECK after cap returns -W_HESITATION not 0.0
147
+ Prevents "+0.200 every episode" passive exploit
148
+ Fix 2 — RESIZE guaranteed to reduce cost (0.40-0.65 multiplier)
149
+ Prevents zero-saving resize farming
150
+ Fix 3 — Tool cap resets every episode via reset()
151
+ Fix 4 — Semantic veto also catches high-dependency temp nodes
152
+ Fix 5 — Min deletable ratio guarantee makes win always reachable
153
+ """
154
+
155
+ # ── Reward weights (do not change without updating Cell 4 too) ──────────
156
+ W_SAVINGS = 20.0
157
+ W_HESITATION = 0.10 # raised: strong enough to force decisive action
158
+ W_TOOL = 0.20
159
+ W_TOOL_EPISODE_CAP = 0.60 # max tool reward per episode (3 uses)
160
+ W_WIN_BONUS = 2.0 # one-time bonus for completing the goal
161
+ PENALTY_CRASH = -10.0
162
+ PENALTY_VETO = -0.50
163
+ MAX_STEPS = 100
164
+
165
+ def __init__(self, n_resources=N_RESOURCES, target_savings=0.20):
166
+ self.n_resources = n_resources
167
+ self.target_savings = target_savings
168
+ self.resources = []
169
+ self.baseline_cost = 0.0
170
+ self.current_cost = 0.0
171
+ self.current_step = 0
172
+ self.nodes_investigated_this_episode = set()
173
+ self.total_tool_reward_this_episode = 0.0
174
+
175
+ # ── Private helpers ──────────────────────────────────────────────────────
176
+
177
+ def _resource_from_action(self, action_idx):
178
+ idx = (action_idx - 2) % self.n_resources
179
+ return self.resources[idx % len(self.resources)]
180
+
181
+ def _has_dependency_violation(self, resource):
182
+ """True if deleting this resource breaks any other active resource."""
183
+ for other in self.resources:
184
+ if other.active and other.name != resource.name:
185
+ if resource.name in other.dependencies:
186
+ return True
187
+ return False
188
+
189
+ def _calc_cost(self):
190
+ return sum(r.cost_per_hr for r in self.resources if r.active)
191
+
192
+ def _get_obs(self):
193
+ obs = []
194
+ for r in self.resources:
195
+ obs.extend(r.to_obs_array())
196
+ budget_used = (
197
+ 1.0 - (self.current_cost / self.baseline_cost)
198
+ if self.baseline_cost > 0 else 0.0
199
+ )
200
+ steps_left = 1.0 - (self.current_step / self.MAX_STEPS)
201
+ obs.extend([budget_used, steps_left])
202
+ return np.array(obs, dtype=np.float32)
203
+
204
+ def _get_internal_state(self):
205
+ """Human-readable state dict for OpenEnv /state endpoint."""
206
+ return {
207
+ "step": self.current_step,
208
+ "baseline_cost": self.baseline_cost,
209
+ "current_cost": self.current_cost,
210
+ "savings_pct": round(
211
+ (1 - self.current_cost / self.baseline_cost) * 100, 2
212
+ ) if self.baseline_cost > 0 else 0.0,
213
+ "resources": [{
214
+ "name": r.name,
215
+ "active": r.active,
216
+ "is_prod": r.is_prod,
217
+ "cost_per_hr": r.cost_per_hr,
218
+ "cpu_pct": r.cpu_pct,
219
+ "dependencies": r.dependencies,
220
+ } for r in self.resources]
221
+ }
222
+
223
+ def _semantic_veto(self, name: str, dep_count: int) -> bool:
224
+ """
225
+ Semantic guardrail — returns True if action should be blocked.
226
+
227
+ Two veto triggers:
228
+ 1. Name contains production keywords (primary check)
229
+ 2. High dependency count on any resource (structural safety net)
230
+ Even temp-named nodes with 5+ deps get vetoed
231
+ This catches the edge case that caused the -31.800 crash
232
+
233
+ In production: replace with call to fine-tuned Llama inference endpoint.
234
+ """
235
+ name_lower = name.lower()
236
+ prod_keywords = [
237
+ "prod", "primary", "main", "core",
238
+ "billing", "payment", "rds", "master"
239
+ ]
240
+ # Primary: semantic name check
241
+ if any(kw in name_lower for kw in prod_keywords):
242
+ return True
243
+ # Secondary: structural safety net — high deps = critical regardless of name
244
+ if dep_count >= 5:
245
+ return True
246
+ return False
247
+
248
+ # ── Lifecycle ─────────────────────────────────────────────────────────────
249
+
250
+ def reset(self):
251
+ """Reset environment for a new episode. Returns OpenEnv dict."""
252
+ self.current_step = 0
253
+ self.nodes_investigated_this_episode = set()
254
+ self.total_tool_reward_this_episode = 0.0
255
+ self.resources = generate_resources(self.n_resources)
256
+ self.baseline_cost = self._calc_cost()
257
+ self.current_cost = self.baseline_cost
258
+ return {
259
+ "observation": self._get_obs(),
260
+ "info": {
261
+ "msg": "Episode reset",
262
+ "baseline_cost": self.baseline_cost,
263
+ }
264
+ }
265
+
266
+ def step(self, action):
267
+ """
268
+ Execute one environment step.
269
+
270
+ Args:
271
+ action : int, one of Action enum values (0-4)
272
+
273
+ Returns:
274
+ dict with keys: observation, state, reward, done, info
275
+ """
276
+ self.current_step += 1
277
+ truncated = self.current_step >= self.MAX_STEPS
278
+
279
+ # ── 1. NOOP — hesitation penalty ──────────────────────────────────
280
+ if action == Action.NOOP:
281
+ return {
282
+ "observation": self._get_obs(),
283
+ "state": self._get_internal_state(),
284
+ "reward": float(-self.W_HESITATION),
285
+ "done": bool(truncated),
286
+ "info": {"msg": "Hesitation penalty", "win": False,
287
+ "savings_pct": round(
288
+ (1 - self.current_cost / self.baseline_cost) * 100, 2)}
289
+ }
290
+
291
+ target = self._resource_from_action(action)
292
+
293
+ # ── 2. CHECK_DEPENDENCIES ─────────────────────────────────────────
294
+ # LOOPHOLE FIX: After cap is reached, return hesitation penalty
295
+ # instead of 0.0. This kills the passive "+0.200 every episode" policy.
296
+ if action == Action.CHECK_DEPENDENCIES:
297
+ under_cap = self.total_tool_reward_this_episode < self.W_TOOL_EPISODE_CAP
298
+ new_node = target.name not in self.nodes_investigated_this_episode
299
+
300
+ if new_node and under_cap:
301
+ # Valid tool use — reward it
302
+ self.nodes_investigated_this_episode.add(target.name)
303
+ self.total_tool_reward_this_episode += self.W_TOOL
304
+ tool_reward = self.W_TOOL
305
+ msg = f"Checked {target.name}"
306
+ else:
307
+ # Cap reached or node already checked — penalise like NOOP
308
+ tool_reward = -self.W_HESITATION
309
+ msg = "Tool cap reached — penalised"
310
+
311
+ return {
312
+ "observation": self._get_obs(),
313
+ "state": self._get_internal_state(),
314
+ "reward": float(tool_reward),
315
+ "done": bool(truncated),
316
+ "info": {"msg": msg, "win": False,
317
+ "savings_pct": round(
318
+ (1 - self.current_cost / self.baseline_cost) * 100, 2)}
319
+ }
320
+
321
+ # ── 3. SEMANTIC + STRUCTURAL GUARDRAIL ────────────────────────────
322
+ # Blocks dangerous actions using name keywords AND dependency count.
323
+ # Dependency count fix closes the edge case that caused -31.800 crash.
324
+ danger = action in (Action.STOP, Action.DELETE)
325
+ if danger and self._semantic_veto(target.name, len(target.dependencies)):
326
+ return {
327
+ "observation": self._get_obs(),
328
+ "state": self._get_internal_state(),
329
+ "reward": float(self.PENALTY_VETO),
330
+ "done": bool(truncated),
331
+ "info": {"msg": f"SEMANTIC VETO on {target.name}",
332
+ "win": False,
333
+ "savings_pct": round(
334
+ (1 - self.current_cost / self.baseline_cost) * 100, 2)}
335
+ }
336
+
337
+ # ── 4. EXECUTE ACTION ─────────────────────────────────────────────
338
+ prev_cost = self.current_cost
339
+
340
+ if action == Action.RESIZE:
341
+ if target.active:
342
+ old_cost = target.cost_per_hr
343
+ # LOOPHOLE FIX: 0.40-0.65 multiplier guarantees meaningful reduction
344
+ target.cost_per_hr = round(
345
+ target.cost_per_hr * random.uniform(0.40, 0.65), 2
346
+ )
347
+ # Extra safety: if somehow no reduction, penalise
348
+ if target.cost_per_hr >= old_cost:
349
+ target.cost_per_hr = round(old_cost * 0.50, 2)
350
+
351
+ elif action in (Action.STOP, Action.DELETE):
352
+ # ── 5. STRUCTURAL DEPENDENCY CHECK ────────────────────────────
353
+ if self._has_dependency_violation(target):
354
+ return {
355
+ "observation": self._get_obs(),
356
+ "state": self._get_internal_state(),
357
+ "reward": float(self.PENALTY_CRASH),
358
+ "done": True,
359
+ "info": {
360
+ "msg": f"CATASTROPHIC FAILURE: {target.name}",
361
+ "win": False,
362
+ "savings_pct": round(
363
+ (1 - self.current_cost / self.baseline_cost) * 100, 2)
364
+ }
365
+ }
366
+ target.active = False
367
+
368
+ # ── 6. FINANCIAL REWARD ───────────────────────────────────────────
369
+ self.current_cost = self._calc_cost()
370
+ delta_pct = (prev_cost - self.current_cost) / self.baseline_cost
371
+ savings_reward = float(np.clip(delta_pct * self.W_SAVINGS, -5.0, 5.0))
372
+
373
+ # ── 7. WIN CONDITION + BONUS ──────────────────────────────────────
374
+ total_saved = (
375
+ (self.baseline_cost - self.current_cost) / self.baseline_cost
376
+ )
377
+ is_win = total_saved >= self.target_savings
378
+
379
+ # One-time win bonus — rewards completing the goal
380
+ if is_win:
381
+ savings_reward += self.W_WIN_BONUS
382
+
383
+ is_done = bool(is_win or truncated)
384
+
385
+ return {
386
+ "observation": self._get_obs(),
387
+ "state": self._get_internal_state(),
388
+ "reward": savings_reward,
389
+ "done": is_done,
390
+ "info": {
391
+ "msg": "Win!" if is_win else "Action Successful",
392
+ "win": is_win,
393
+ "savings_pct": round(total_saved * 100, 2),
394
+ }
395
+ }
396
+
397
+
398
+ # ─── SB3 Adapter (Gymnasium wrapper for PPO) ─────────────────────────────────
399
+
400
+ class SB3Adapter(gym.Env):
401
+ """
402
+ Wraps AWSCostEnv (OpenEnv dict API) into the Gymnasium 5-tuple API
403
+ that stable-baselines3 PPO expects.
404
+
405
+ terminated = agent achieved the savings target (win)
406
+ truncated = MAX_STEPS reached without winning
407
+ """
408
+ metadata = {"render_modes": []}
409
+
410
+ def __init__(self):
411
+ super().__init__()
412
+ self.core = AWSCostEnv()
413
+ self.action_space = spaces.Discrete(NUM_ACTIONS)
414
+ self.observation_space = spaces.Box(
415
+ low=-np.inf, high=np.inf, shape=(OBS_DIM,), dtype=np.float32
416
+ )
417
+
418
+ def reset(self, seed=None, options=None):
419
+ super().reset(seed=seed)
420
+ result = self.core.reset()
421
+ return result["observation"], result["info"]
422
+
423
+ def step(self, action):
424
+ result = self.core.step(action)
425
+ terminated = result["done"] and result["info"].get("win", False)
426
+ truncated = result["done"] and not result["info"].get("win", False)
427
+ return (
428
+ result["observation"],
429
+ result["reward"],
430
+ terminated,
431
+ truncated,
432
+ result["info"],
433
+ )
434
+
435
+ def render(self):
436
+ pass
437
+
438
+
cloud_arena/llm_training.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # LLM RL Training — LLaMA 3.1 8B + REINFORCE + LoRA
3
+ # This is the LLM model, SEPARATE from the mathematical model.
4
+ # Uses AWSCostEnv (llm_environment.py), NOT CloudArenaEnv.
5
+ # ============================================================
6
+
7
+ import os
8
+ import re
9
+ import json
10
+ import time
11
+ import warnings
12
+ import numpy as np
13
+ import torch
14
+ import torch.nn.functional as F
15
+ import matplotlib
16
+ matplotlib.use("Agg")
17
+ import matplotlib.pyplot as plt
18
+
19
+ warnings.filterwarnings("ignore", category=UserWarning)
20
+ warnings.filterwarnings("ignore", category=FutureWarning)
21
+
22
+ from cloud_arena.llm_environment import SB3Adapter, Action, AWSCostEnv
23
+
24
+ # ─── Constants ────────────────────────────────────────────────────────────────
25
+
26
+ ACTION_NAMES = {0: "NOOP", 1: "CHECK_DEPS", 2: "RESIZE", 3: "STOP", 4: "DELETE"}
27
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
28
+
29
+
30
+ def format_prompt(state_dict):
31
+ resources_text = ""
32
+ for r in state_dict["resources"]:
33
+ status = "ACTIVE" if r["active"] else "STOPPED"
34
+ tag = "PRODUCTION" if r["is_prod"] else "Temporary"
35
+ resources_text += (
36
+ f" - {r['name']} [{status}] ({tag}): "
37
+ f"Cost=${r['cost_per_hr']:.2f}/hr, CPU={r['cpu_pct']}%, "
38
+ f"Deps={len(r['dependencies'])}\n"
39
+ )
40
+ savings_pct = state_dict.get("savings_pct", 0.0)
41
+ return (
42
+ f"You are a Cloud FinOps AI. Reduce cloud cost by >=20% without breaking production.\n\n"
43
+ f"Actions: 0=NOOP, 1=CHECK_DEPS, 2=RESIZE, 3=STOP, 4=DELETE\n\n"
44
+ f"Resources:\n{resources_text}\n"
45
+ f"Baseline: ${state_dict['baseline_cost']:.2f}/hr | "
46
+ f"Current: ${state_dict['current_cost']:.2f}/hr | "
47
+ f"Savings: {savings_pct:.1f}%\n\n"
48
+ f"Rules:\n"
49
+ f"- Never delete/stop prod resources or those with >=5 deps\n"
50
+ f"- Temp resources with 0-1 deps are safe to delete\n"
51
+ f"- RESIZE is always safe\n\n"
52
+ f"REASONING:"
53
+ )
54
+
55
+
56
+ def extract_action_and_reasoning(response_text):
57
+ reasoning = response_text.strip()
58
+ action = 2
59
+ action_match = re.search(r'ACTION:\s*(\d)', response_text, re.IGNORECASE)
60
+ if action_match:
61
+ parsed = int(action_match.group(1))
62
+ if 0 <= parsed <= 4:
63
+ action = parsed
64
+ else:
65
+ digit_matches = re.findall(r'\b([0-4])\b', response_text[-50:])
66
+ if digit_matches:
67
+ action = int(digit_matches[-1])
68
+ return action, reasoning
69
+
70
+
71
+ def policy_gradient_step(model, tokenizer, prompt, response_text, reward, optimizer):
72
+ full_text = prompt + response_text
73
+ encodings = tokenizer(full_text, return_tensors="pt", truncation=True, max_length=512).to(DEVICE)
74
+ prompt_encodings = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
75
+ prompt_len = prompt_encodings["input_ids"].shape[1]
76
+
77
+ outputs = model(**encodings, labels=encodings["input_ids"])
78
+ logits = outputs.logits[:, prompt_len-1:-1, :]
79
+ targets = encodings["input_ids"][:, prompt_len:]
80
+
81
+ if targets.shape[1] == 0 or logits.shape[1] == 0:
82
+ return 0.0
83
+
84
+ min_len = min(logits.shape[1], targets.shape[1])
85
+ logits = logits[:, :min_len, :]
86
+ targets = targets[:, :min_len]
87
+
88
+ log_probs = F.log_softmax(logits, dim=-1)
89
+ token_log_probs = log_probs.gather(2, targets.unsqueeze(-1)).squeeze(-1)
90
+ avg_log_prob = token_log_probs.mean()
91
+
92
+ loss = -reward * avg_log_prob
93
+ optimizer.zero_grad()
94
+ loss.backward()
95
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
96
+ optimizer.step()
97
+ return loss.item()
98
+
99
+
100
+ def run_episode(model, tokenizer, env, is_training=False, optimizer=None,
101
+ steps_per_episode=5, max_new_tokens=128):
102
+ obs, info = env.reset()
103
+ state_dict = env.core._get_internal_state()
104
+ done = False
105
+ episode_reward = 0.0
106
+ step_count = 0
107
+ reasoning_log = []
108
+ losses = []
109
+
110
+ while not done and step_count < steps_per_episode:
111
+ prompt = format_prompt(state_dict)
112
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
113
+ input_ids = inputs["input_ids"].to(DEVICE)
114
+
115
+ with torch.no_grad():
116
+ gen_outputs = model.generate(
117
+ input_ids, max_new_tokens=max_new_tokens,
118
+ do_sample=True, temperature=0.7, top_p=0.95,
119
+ pad_token_id=tokenizer.pad_token_id,
120
+ )
121
+
122
+ response_ids = gen_outputs[0][input_ids.shape[1]:]
123
+ response_text = tokenizer.decode(response_ids, skip_special_tokens=True)
124
+ action, reasoning = extract_action_and_reasoning(response_text)
125
+
126
+ next_obs, reward, terminated, truncated, next_info = env.step(action)
127
+ done = terminated or truncated
128
+ episode_reward += reward
129
+
130
+ reasoning_log.append({
131
+ "step": step_count + 1,
132
+ "reasoning": reasoning[:300],
133
+ "action": action,
134
+ "action_name": ACTION_NAMES.get(action, "UNKNOWN"),
135
+ "reward": round(reward, 4),
136
+ "message": next_info.get("msg", ""),
137
+ })
138
+
139
+ if is_training and optimizer is not None:
140
+ loss = policy_gradient_step(model, tokenizer, prompt, response_text, reward, optimizer)
141
+ losses.append(loss)
142
+
143
+ obs = next_obs
144
+ state_dict = env.core._get_internal_state()
145
+ step_count += 1
146
+
147
+ return episode_reward, reasoning_log
148
+
149
+
150
+ def train_llm(model_name="google/gemma-7b-it",
151
+ num_iterations=10, steps_per_episode=5, learning_rate=5e-5,
152
+ progress_callback=None):
153
+ """
154
+ Full LLM RL training pipeline. Returns (all_rewards, full_log, graph_path).
155
+ """
156
+ hf_token = os.environ.get("HF_TOKEN")
157
+
158
+ from transformers import AutoModelForCausalLM, AutoTokenizer
159
+ from peft import get_peft_model, LoraConfig, TaskType
160
+
161
+ log_lines = []
162
+ def log(msg):
163
+ print(msg)
164
+ log_lines.append(msg)
165
+ if progress_callback:
166
+ progress_callback("\n".join(log_lines))
167
+
168
+ log(f"🖥️ Device: {DEVICE}")
169
+ log(f"🧠 Model: {model_name}")
170
+ log(f"🔁 Iterations: {num_iterations}")
171
+ log("📦 Loading model and tokenizer...")
172
+
173
+ tokenizer = AutoTokenizer.from_pretrained(model_name, token=hf_token)
174
+ model = AutoModelForCausalLM.from_pretrained(
175
+ model_name, torch_dtype=torch.bfloat16, token=hf_token,
176
+ ).to(DEVICE)
177
+
178
+ lora_config = LoraConfig(
179
+ r=16, lora_alpha=16,
180
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
181
+ lora_dropout=0.0, bias="none",
182
+ task_type=TaskType.CAUSAL_LM,
183
+ )
184
+ model = get_peft_model(model, lora_config)
185
+
186
+ if tokenizer.pad_token is None:
187
+ tokenizer.pad_token = tokenizer.eos_token
188
+
189
+ trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
190
+ total = sum(p.numel() for p in model.parameters())
191
+ log(f"✅ Model loaded. Trainable: {trainable:,} / {total:,} params")
192
+
193
+ optimizer = torch.optim.AdamW(
194
+ filter(lambda p: p.requires_grad, model.parameters()), lr=learning_rate
195
+ )
196
+ env = SB3Adapter()
197
+
198
+ all_rewards = []
199
+ full_log = []
200
+
201
+ # Pre-training eval
202
+ log("\n▶ PRE-TRAINING EVAL")
203
+ model.eval()
204
+ pre_reward, pre_log_data = run_episode(model, tokenizer, env, steps_per_episode=steps_per_episode)
205
+ all_rewards.append(pre_reward)
206
+ full_log.append({"phase": "pre-training", "reward": pre_reward, "reasoning": pre_log_data})
207
+ log(f" Reward: {pre_reward:+.3f}")
208
+
209
+ # Training
210
+ log(f"\n▶ TRAINING ({num_iterations} iterations)")
211
+ model.train()
212
+ for i in range(num_iterations):
213
+ reward, train_log_data = run_episode(
214
+ model, tokenizer, env, is_training=True, optimizer=optimizer,
215
+ steps_per_episode=steps_per_episode,
216
+ )
217
+ all_rewards.append(reward)
218
+ full_log.append({"phase": f"training-{i+1}", "reward": reward, "reasoning": train_log_data})
219
+ log(f" Iter {i+1}/{num_iterations}: reward={reward:+.3f}")
220
+
221
+ # Post-training eval
222
+ log("\n▶ POST-TRAINING EVAL")
223
+ model.eval()
224
+ post_reward, post_log_data = run_episode(model, tokenizer, env, steps_per_episode=steps_per_episode)
225
+ all_rewards.append(post_reward)
226
+ full_log.append({"phase": "post-training", "reward": post_reward, "reasoning": post_log_data})
227
+ log(f" Reward: {post_reward:+.3f}")
228
+
229
+ delta = all_rewards[-1] - all_rewards[0]
230
+ log(f"\n✅ DONE | Pre: {all_rewards[0]:+.3f} → Post: {all_rewards[-1]:+.3f} | Δ={delta:+.3f}")
231
+
232
+ # Save log
233
+ with open("outputs/llm_training_log.json", "w") as f:
234
+ json.dump(full_log, f, indent=2, default=str)
235
+
236
+ # Generate graph
237
+ graph_path = _generate_graph(all_rewards, num_iterations, model_name)
238
+
239
+ return all_rewards, full_log, graph_path, "\n".join(log_lines)
240
+
241
+
242
+ def _generate_graph(all_rewards, num_iterations, model_name):
243
+ labels = ["Before"] + [f"Iter {i+1}" for i in range(num_iterations)] + ["After"]
244
+ colors = ["#ef4444"] + ["#3b82f6"] * num_iterations + ["#22c55e"]
245
+
246
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6), facecolor="#0e1117")
247
+ for ax in [ax1, ax2]:
248
+ ax.set_facecolor("#0e1117")
249
+ ax.tick_params(colors="#e6e6e6")
250
+ ax.grid(axis="y", alpha=0.1, color="white")
251
+ for s in ['top','right']:
252
+ ax.spines[s].set_visible(False)
253
+ for s in ['left','bottom']:
254
+ ax.spines[s].set_color('#333')
255
+
256
+ ax1.bar(range(len(all_rewards)), all_rewards, color=colors, edgecolor="white", lw=1.5, width=0.6)
257
+ ax1.set_xticks(range(len(labels)))
258
+ ax1.set_xticklabels(labels, fontsize=8, color="#e6e6e6", rotation=45)
259
+ ax1.set_title(f"LLM RL: {model_name.split('/')[-1]}", color="#e6e6e6", fontsize=13, fontweight="bold")
260
+ ax1.set_ylabel("Reward", color="#e6e6e6")
261
+
262
+ comp = [all_rewards[0], all_rewards[-1]]
263
+ ax2.bar(["Before", "After"], comp, color=["#ef4444", "#22c55e"], edgecolor="white", lw=2, width=0.5)
264
+ ax2.set_title("Before vs After", color="#e6e6e6", fontsize=13, fontweight="bold")
265
+ ax2.set_ylabel("Reward", color="#e6e6e6")
266
+
267
+ plt.tight_layout()
268
+ path = "outputs/llm_training_results.png"
269
+ plt.savefig(path, dpi=200, bbox_inches="tight", facecolor="#0e1117")
270
+ plt.close()
271
+ return path
requirements.txt CHANGED
@@ -1,5 +1,4 @@
1
- # ── Mathematical Model RL Dependencies ONLY ──
2
- # DO NOT add transformers/peft/trl here — those belong to the LLM model
3
  gymnasium>=0.29.0
4
  stable-baselines3>=2.3.0
5
  sb3-contrib>=2.3.0
@@ -7,3 +6,10 @@ numpy>=1.24.0
7
  torch>=2.0.0
8
  matplotlib>=3.7.0
9
  gradio>=4.0.0
 
 
 
 
 
 
 
 
1
+ # ── Mathematical Model RL ──────────────────────────────────
 
2
  gymnasium>=0.29.0
3
  stable-baselines3>=2.3.0
4
  sb3-contrib>=2.3.0
 
6
  torch>=2.0.0
7
  matplotlib>=3.7.0
8
  gradio>=4.0.0
9
+
10
+ # ── LLM Model RL (LLaMA 3.1 8B + LoRA) ───────────────────
11
+ transformers>=4.40.0
12
+ peft>=0.10.0
13
+ accelerate>=0.30.0
14
+ bitsandbytes>=0.43.0
15
+ sentencepiece