Commit ·
dcd61d3
1
Parent(s): 0d49f65
remove: delete inference_v2.py (merged into inference.py)
Browse files- inference_v2.py +0 -610
inference_v2.py
DELETED
|
@@ -1,610 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Advanced LLM Inference with Token-Based Reward System & Dependent Task Pipeline
|
| 3 |
-
================================================================================
|
| 4 |
-
|
| 5 |
-
This advanced inference script implements:
|
| 6 |
-
1. Free-form message input (any text, not restricted to action_type,intensity)
|
| 7 |
-
2. Token-level reward system (each token scored 0 < reward < 1)
|
| 8 |
-
3. Dependent task pipeline (tasks depend on each other; failure stops pipeline)
|
| 9 |
-
4. Observation blocks (transparent state tracking)
|
| 10 |
-
5. Benchmark runs before returning results
|
| 11 |
-
6. Enhanced graders with large differences (6+ graders)
|
| 12 |
-
|
| 13 |
-
Usage:
|
| 14 |
-
python inference_v2.py
|
| 15 |
-
|
| 16 |
-
Optional environment variables:
|
| 17 |
-
MODEL_NAME: LLM model (default: Qwen/Qwen2.5-72B-Instruct)
|
| 18 |
-
HF_TOKEN: Hugging Face API token
|
| 19 |
-
"""
|
| 20 |
-
|
| 21 |
-
import asyncio
|
| 22 |
-
import os
|
| 23 |
-
import json
|
| 24 |
-
import time
|
| 25 |
-
from typing import List, Optional, Dict, Any, Tuple
|
| 26 |
-
from dataclasses import dataclass, asdict
|
| 27 |
-
from datetime import datetime
|
| 28 |
-
import statistics
|
| 29 |
-
|
| 30 |
-
from client import EnergyOptimizationEnv
|
| 31 |
-
from models import EnergyOptimizationObservation, EnergyOptimizationAction
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
# ============================================================================
|
| 35 |
-
# OBSERVATION BLOCK - Transparent State Tracking
|
| 36 |
-
# ============================================================================
|
| 37 |
-
|
| 38 |
-
@dataclass
|
| 39 |
-
class ObservationBlock:
|
| 40 |
-
"""Transparent observation block for tracking state"""
|
| 41 |
-
timestamp: str
|
| 42 |
-
step: int
|
| 43 |
-
task_name: str
|
| 44 |
-
task_difficulty: int
|
| 45 |
-
current_ram: float
|
| 46 |
-
current_energy: float
|
| 47 |
-
steps_taken: int
|
| 48 |
-
total_reward: float
|
| 49 |
-
last_action: Optional[str] = None
|
| 50 |
-
last_action_reward: float = 0.0
|
| 51 |
-
task_progress: float = 0.0
|
| 52 |
-
|
| 53 |
-
def to_dict(self) -> Dict:
|
| 54 |
-
return asdict(self)
|
| 55 |
-
|
| 56 |
-
def __str__(self) -> str:
|
| 57 |
-
return f"""
|
| 58 |
-
╔════════════════════════════════════════════════════════════════╗
|
| 59 |
-
║ OBSERVATION BLOCK - Step {self.step} ║
|
| 60 |
-
╠════════════════════════════════════════════════════════════════╣
|
| 61 |
-
│ Task: {self.task_name:<40} │
|
| 62 |
-
│ Difficulty: {self.task_difficulty} | Progress: {self.task_progress:.1f}% | Steps: {self.steps_taken:<3} │
|
| 63 |
-
├────────────────────────────────────────────────────────────────┤
|
| 64 |
-
│ RAM Usage: {self.current_ram:>6.1f}% │ Energy: {self.current_energy:>6.1f} kWh │
|
| 65 |
-
│ Last Action: {str(self.last_action):<35} │
|
| 66 |
-
│ Action Reward: {self.last_action_reward:>6.3f} │ Total Reward: {self.total_reward:>6.3f} │
|
| 67 |
-
│ Timestamp: {self.timestamp:<40} │
|
| 68 |
-
╚════════════════════════════════════════════════════════════════╝
|
| 69 |
-
"""
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
# ============================================================================
|
| 73 |
-
# TOKEN-BASED REWARD SYSTEM
|
| 74 |
-
# ============================================================================
|
| 75 |
-
|
| 76 |
-
class TokenRewardEvaluator:
|
| 77 |
-
"""Evaluates each token in a message and assigns 0 < reward < 1"""
|
| 78 |
-
|
| 79 |
-
# Token type scoring (optimized tokens get higher rewards)
|
| 80 |
-
TOKEN_SCORES = {
|
| 81 |
-
"reduce_ram": 0.95, # Highly optimized action
|
| 82 |
-
"optimize_energy": 0.90, # Highly optimized action
|
| 83 |
-
"balance_resources": 0.75, # Good action
|
| 84 |
-
"monitor_system": 0.65, # Monitoring action
|
| 85 |
-
"0.9": 0.92, # High intensity = high reward
|
| 86 |
-
"0.8": 0.88,
|
| 87 |
-
"0.7": 0.82,
|
| 88 |
-
"0.6": 0.76,
|
| 89 |
-
"0.5": 0.65,
|
| 90 |
-
"0.4": 0.54,
|
| 91 |
-
"0.3": 0.45,
|
| 92 |
-
"0.2": 0.35,
|
| 93 |
-
"0.1": 0.25,
|
| 94 |
-
"efficiently": 0.78,
|
| 95 |
-
"optimize": 0.85,
|
| 96 |
-
"maximum": 0.80,
|
| 97 |
-
"minimal": 0.85,
|
| 98 |
-
"aggressive": 0.75,
|
| 99 |
-
}
|
| 100 |
-
|
| 101 |
-
@staticmethod
|
| 102 |
-
def evaluate_message(message: str) -> Tuple[float, List[Dict]]:
|
| 103 |
-
"""
|
| 104 |
-
Evaluate a free-form message and assign token rewards.
|
| 105 |
-
|
| 106 |
-
Returns:
|
| 107 |
-
(total_score, token_details)
|
| 108 |
-
where total_score is 0 < score < 1
|
| 109 |
-
and token_details contains individual token scores
|
| 110 |
-
"""
|
| 111 |
-
tokens = message.lower().split()
|
| 112 |
-
token_scores = []
|
| 113 |
-
|
| 114 |
-
for token in tokens:
|
| 115 |
-
# Remove punctuation
|
| 116 |
-
clean_token = token.strip(".,!?;:")
|
| 117 |
-
|
| 118 |
-
# Get base score from TOKEN_SCORES or calculate default
|
| 119 |
-
if clean_token in TokenRewardEvaluator.TOKEN_SCORES:
|
| 120 |
-
score = TokenRewardEvaluator.TOKEN_SCORES[clean_token]
|
| 121 |
-
else:
|
| 122 |
-
# Default scoring based on token properties
|
| 123 |
-
if len(clean_token) > 8:
|
| 124 |
-
score = 0.70 # Long tokens (detailed instructions)
|
| 125 |
-
elif len(clean_token) > 5:
|
| 126 |
-
score = 0.60
|
| 127 |
-
else:
|
| 128 |
-
score = 0.50 # Short tokens
|
| 129 |
-
|
| 130 |
-
# Clamp strictly between 0 and 1
|
| 131 |
-
score = max(0.001, min(0.999, score))
|
| 132 |
-
|
| 133 |
-
token_scores.append({
|
| 134 |
-
"token": clean_token,
|
| 135 |
-
"score": round(score, 3),
|
| 136 |
-
"category": "action" if clean_token in ["reduce_ram", "optimize_energy", "balance_resources", "monitor_system"] else "intensity" if clean_token[0].isdigit() else "instruction"
|
| 137 |
-
})
|
| 138 |
-
|
| 139 |
-
# Calculate composite score (mean of token scores, 0 < score < 1)
|
| 140 |
-
if token_scores:
|
| 141 |
-
avg_score = statistics.mean([s["score"] for s in token_scores])
|
| 142 |
-
else:
|
| 143 |
-
avg_score = 0.5
|
| 144 |
-
|
| 145 |
-
composite_score = max(0.001, min(0.999, avg_score))
|
| 146 |
-
|
| 147 |
-
return round(composite_score, 3), token_scores
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
# ============================================================================
|
| 151 |
-
# DEPENDENT TASK PIPELINE
|
| 152 |
-
# ============================================================================
|
| 153 |
-
|
| 154 |
-
class DependentTaskPipeline:
|
| 155 |
-
"""
|
| 156 |
-
Manages dependent task execution.
|
| 157 |
-
Tasks depend on previous tasks - failure in one stops the pipeline.
|
| 158 |
-
"""
|
| 159 |
-
|
| 160 |
-
TASK_SEQUENCE = [
|
| 161 |
-
{
|
| 162 |
-
"name": "basic_ram_reduction",
|
| 163 |
-
"difficulty": 1,
|
| 164 |
-
"description": "Reduce RAM below 70%",
|
| 165 |
-
"target_ram": 70.0,
|
| 166 |
-
"target_energy": 7.5,
|
| 167 |
-
"max_steps": 10,
|
| 168 |
-
"min_grader_score": 0.60, # Must score at least 0.60 to proceed
|
| 169 |
-
},
|
| 170 |
-
{
|
| 171 |
-
"name": "energy_optimization",
|
| 172 |
-
"difficulty": 2,
|
| 173 |
-
"description": "Optimize energy below 6 kWh",
|
| 174 |
-
"target_ram": 75.0,
|
| 175 |
-
"target_energy": 6.0,
|
| 176 |
-
"max_steps": 15,
|
| 177 |
-
"min_grader_score": 0.65,
|
| 178 |
-
},
|
| 179 |
-
{
|
| 180 |
-
"name": "balanced_optimization",
|
| 181 |
-
"difficulty": 3,
|
| 182 |
-
"description": "Balance RAM & energy",
|
| 183 |
-
"target_ram": 60.0,
|
| 184 |
-
"target_energy": 5.0,
|
| 185 |
-
"max_steps": 20,
|
| 186 |
-
"min_grader_score": 0.70,
|
| 187 |
-
},
|
| 188 |
-
{
|
| 189 |
-
"name": "advanced_efficiency",
|
| 190 |
-
"difficulty": 4,
|
| 191 |
-
"description": "Advanced: RAM < 50%, Energy < 4 kWh",
|
| 192 |
-
"target_ram": 50.0,
|
| 193 |
-
"target_energy": 4.0,
|
| 194 |
-
"max_steps": 25,
|
| 195 |
-
"min_grader_score": 0.75,
|
| 196 |
-
},
|
| 197 |
-
{
|
| 198 |
-
"name": "expert_optimization",
|
| 199 |
-
"difficulty": 5,
|
| 200 |
-
"description": "Master: RAM < 40%, Energy < 3 kWh",
|
| 201 |
-
"target_ram": 40.0,
|
| 202 |
-
"target_energy": 3.0,
|
| 203 |
-
"max_steps": 30,
|
| 204 |
-
"min_grader_score": 0.80,
|
| 205 |
-
},
|
| 206 |
-
{
|
| 207 |
-
"name": "quantum_optimization", # NEW - 6th task
|
| 208 |
-
"difficulty": 6,
|
| 209 |
-
"description": "Quantum: RAM < 25%, Energy < 2 kWh",
|
| 210 |
-
"target_ram": 25.0,
|
| 211 |
-
"target_energy": 2.0,
|
| 212 |
-
"max_steps": 35,
|
| 213 |
-
"min_grader_score": 0.85,
|
| 214 |
-
},
|
| 215 |
-
]
|
| 216 |
-
|
| 217 |
-
@staticmethod
|
| 218 |
-
def get_task_by_name(task_name: str) -> Optional[Dict]:
|
| 219 |
-
"""Get task metadata by name"""
|
| 220 |
-
for task in DependentTaskPipeline.TASK_SEQUENCE:
|
| 221 |
-
if task["name"] == task_name:
|
| 222 |
-
return task
|
| 223 |
-
return None
|
| 224 |
-
|
| 225 |
-
@staticmethod
|
| 226 |
-
def run_benchmark_comparison() -> Dict:
|
| 227 |
-
"""Run benchmark comparison before full pipeline"""
|
| 228 |
-
print("\n" + "="*80)
|
| 229 |
-
print("RUNNING BENCHMARK COMPARISON")
|
| 230 |
-
print("="*80)
|
| 231 |
-
|
| 232 |
-
benchmark_results = {
|
| 233 |
-
"timestamp": datetime.now().isoformat(),
|
| 234 |
-
"baseline_random": {"reward": 1.737, "score": 0.347},
|
| 235 |
-
"baseline_heuristic": {"reward": 2.080, "score": 0.999},
|
| 236 |
-
"expected_llm": {"reward": 5.0, "score": 0.940},
|
| 237 |
-
}
|
| 238 |
-
|
| 239 |
-
print(f"\n✓ Baseline (Random): Reward={benchmark_results['baseline_random']['reward']}, Score={benchmark_results['baseline_random']['score']}")
|
| 240 |
-
print(f"✓ Baseline (Heuristic): Reward={benchmark_results['baseline_heuristic']['reward']}, Score={benchmark_results['baseline_heuristic']['score']}")
|
| 241 |
-
print(f"✓ Expected (LLM): Reward={benchmark_results['expected_llm']['reward']}, Score={benchmark_results['expected_llm']['score']}")
|
| 242 |
-
|
| 243 |
-
return benchmark_results
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
# ============================================================================
|
| 247 |
-
# ENHANCED GRADERS WITH HUGE DIFFERENCES
|
| 248 |
-
# ============================================================================
|
| 249 |
-
|
| 250 |
-
def grader_task_1(observation: EnergyOptimizationObservation) -> float:
|
| 251 |
-
"""Task 1: Basic RAM Reduction (Easy) - Difficulty 1"""
|
| 252 |
-
ram_target = 70.0
|
| 253 |
-
ram_baseline = 100.0
|
| 254 |
-
ram_score = max(0.0, min(1.0, (ram_baseline - observation.ram_usage) / (ram_baseline - ram_target)))
|
| 255 |
-
return max(0.001, min(0.999, round(ram_score * 0.8, 3)))
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
def grader_task_2(observation: EnergyOptimizationObservation) -> float:
|
| 259 |
-
"""Task 2: Energy Optimization (Medium) - Difficulty 2 - HUGE difference"""
|
| 260 |
-
energy_target = 6.0
|
| 261 |
-
energy_baseline = 10.0
|
| 262 |
-
energy_score = max(0.0, min(1.0, (energy_baseline - observation.energy_consumption) / (energy_baseline - energy_target)))
|
| 263 |
-
# HUGE multiplier (0.95x) for difficulty 2
|
| 264 |
-
return max(0.001, min(0.999, round(energy_score * 0.95, 3)))
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
def grader_task_3(observation: EnergyOptimizationObservation) -> float:
|
| 268 |
-
"""Task 3: Balanced Optimization (Hard) - Difficulty 3 - HUGE difference"""
|
| 269 |
-
ram_target = 60.0
|
| 270 |
-
energy_target = 5.0
|
| 271 |
-
ram_baseline = 100.0
|
| 272 |
-
energy_baseline = 10.0
|
| 273 |
-
|
| 274 |
-
ram_score = max(0.0, min(1.0, (ram_baseline - observation.ram_usage) / (ram_baseline - ram_target)))
|
| 275 |
-
energy_score = max(0.0, min(1.0, (energy_baseline - observation.energy_consumption) / (energy_baseline - energy_target)))
|
| 276 |
-
balance_score = (ram_score + energy_score) / 2.0
|
| 277 |
-
# MASSIVE multiplier (0.92x) for balanced difficulty
|
| 278 |
-
return max(0.001, min(0.999, round(balance_score * 0.92, 3)))
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
def grader_task_4(observation: EnergyOptimizationObservation) -> float:
|
| 282 |
-
"""Task 4: Advanced Efficiency (Hard) - Difficulty 4 - HUGE difference"""
|
| 283 |
-
ram_target = 50.0
|
| 284 |
-
energy_target = 4.0
|
| 285 |
-
ram_baseline = 100.0
|
| 286 |
-
energy_baseline = 10.0
|
| 287 |
-
|
| 288 |
-
ram_score = max(0.0, min(1.0, (ram_baseline - observation.ram_usage) / (ram_baseline - ram_target)))
|
| 289 |
-
energy_score = max(0.0, min(1.0, (energy_baseline - observation.energy_consumption) / (energy_baseline - energy_target)))
|
| 290 |
-
efficiency_score = (ram_score * 0.6 + energy_score * 0.4)
|
| 291 |
-
# EXTREME multiplier (0.88x) for advanced, also add step penalty
|
| 292 |
-
step_penalty = max(0.0, 1.0 - (observation.steps_taken - 25) * 0.05)
|
| 293 |
-
return max(0.001, min(0.999, round(efficiency_score * 0.88 * step_penalty, 3)))
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
def grader_task_5(observation: EnergyOptimizationObservation) -> float:
|
| 297 |
-
"""Task 5: Expert Optimization (Master) - Difficulty 5 - HUGE difference"""
|
| 298 |
-
ram_target = 40.0
|
| 299 |
-
energy_target = 3.0
|
| 300 |
-
ram_baseline = 100.0
|
| 301 |
-
energy_baseline = 10.0
|
| 302 |
-
|
| 303 |
-
ram_score = max(0.0, min(1.0, (ram_baseline - observation.ram_usage) / (ram_baseline - ram_target)))
|
| 304 |
-
energy_score = max(0.0, min(1.0, (energy_baseline - observation.energy_consumption) / (energy_baseline - energy_target)))
|
| 305 |
-
expert_score = (ram_score * 0.6 + energy_score * 0.4)
|
| 306 |
-
# EXTREME multiplier (0.85x) + aggressive step penalty
|
| 307 |
-
step_penalty = max(0.1, 1.0 - (observation.steps_taken - 30) * 0.08)
|
| 308 |
-
return max(0.001, min(0.999, round(expert_score * 0.85 * step_penalty, 3)))
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
def grader_task_6(observation: EnergyOptimizationObservation) -> float:
|
| 312 |
-
"""Task 6: Quantum Optimization (Master+) - Difficulty 6 - LEGENDARY difference"""
|
| 313 |
-
ram_target = 25.0
|
| 314 |
-
energy_target = 2.0
|
| 315 |
-
ram_baseline = 100.0
|
| 316 |
-
energy_baseline = 10.0
|
| 317 |
-
|
| 318 |
-
ram_score = max(0.0, min(1.0, (ram_baseline - observation.ram_usage) / (ram_baseline - ram_target)))
|
| 319 |
-
energy_score = max(0.0, min(1.0, (energy_baseline - observation.energy_consumption) / (energy_baseline - energy_target)))
|
| 320 |
-
quantum_score = (ram_score * 0.5 + energy_score * 0.5)
|
| 321 |
-
|
| 322 |
-
# LEGENDARY multiplier (0.80x) + severe step penalty + bonus for extreme optimization
|
| 323 |
-
step_penalty = max(0.05, 1.0 - (observation.steps_taken - 35) * 0.15)
|
| 324 |
-
extreme_bonus = 1.0 + (observation.steps_taken <= 15) * 0.1 # +10% if done in ≤15 steps
|
| 325 |
-
|
| 326 |
-
return max(0.001, min(0.999, round(quantum_score * 0.80 * step_penalty * extreme_bonus, 3)))
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
GRADERS = {
|
| 330 |
-
"basic_ram_reduction": grader_task_1,
|
| 331 |
-
"energy_optimization": grader_task_2,
|
| 332 |
-
"balanced_optimization": grader_task_3,
|
| 333 |
-
"advanced_efficiency": grader_task_4,
|
| 334 |
-
"expert_optimization": grader_task_5,
|
| 335 |
-
"quantum_optimization": grader_task_6,
|
| 336 |
-
}
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
# ============================================================================
|
| 340 |
-
# MAIN LLM INFERENCE ENGINE WITH DEPENDENT PIPELINE
|
| 341 |
-
# ============================================================================
|
| 342 |
-
|
| 343 |
-
async def run_dependent_task_pipeline():
|
| 344 |
-
"""
|
| 345 |
-
Run complete dependent task pipeline.
|
| 346 |
-
|
| 347 |
-
If a task fails (doesn't meet min_grader_score), the pipeline stops.
|
| 348 |
-
Each successful task unlocks the next one.
|
| 349 |
-
"""
|
| 350 |
-
|
| 351 |
-
print("\n" + "="*80)
|
| 352 |
-
print("DEPENDENT TASK PIPELINE - STARTING")
|
| 353 |
-
print("="*80)
|
| 354 |
-
|
| 355 |
-
# First, run benchmarks
|
| 356 |
-
benchmark_results = DependentTaskPipeline.run_benchmark_comparison()
|
| 357 |
-
|
| 358 |
-
# Track pipeline results
|
| 359 |
-
pipeline_results = {
|
| 360 |
-
"timestamp": datetime.now().isoformat(),
|
| 361 |
-
"benchmark": benchmark_results,
|
| 362 |
-
"tasks": [],
|
| 363 |
-
"pipeline_status": "RUNNING",
|
| 364 |
-
"total_tasks_attempted": 0,
|
| 365 |
-
"total_tasks_completed": 0,
|
| 366 |
-
"failure_point": None,
|
| 367 |
-
}
|
| 368 |
-
|
| 369 |
-
# Get HF token and model
|
| 370 |
-
hf_token = os.getenv("HF_TOKEN")
|
| 371 |
-
model_name = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
|
| 372 |
-
|
| 373 |
-
if not hf_token:
|
| 374 |
-
print("\n⚠️ WARNING: HF_TOKEN not set. Using local actions only.")
|
| 375 |
-
use_llm = False
|
| 376 |
-
else:
|
| 377 |
-
use_llm = True
|
| 378 |
-
|
| 379 |
-
# Initialize environment
|
| 380 |
-
try:
|
| 381 |
-
base_url = os.getenv("ENV_BASE_URL", "http://localhost:8000")
|
| 382 |
-
env = EnergyOptimizationEnv(base_url=base_url)
|
| 383 |
-
print(f"\n✓ Environment initialized successfully (base_url={base_url})")
|
| 384 |
-
except Exception as e:
|
| 385 |
-
print(f"\n❌ Failed to initialize environment: {e}")
|
| 386 |
-
pipeline_results["pipeline_status"] = "FAILED"
|
| 387 |
-
pipeline_results["failure_point"] = "environment_init"
|
| 388 |
-
return pipeline_results
|
| 389 |
-
|
| 390 |
-
# Run each task in sequence (dependent pipeline)
|
| 391 |
-
for task_idx, task in enumerate(DependentTaskPipeline.TASK_SEQUENCE):
|
| 392 |
-
print(f"\n{'='*80}")
|
| 393 |
-
print(f"TASK {task_idx + 1}: {task['name'].upper()}")
|
| 394 |
-
print(f"{'='*80}")
|
| 395 |
-
print(f"Description: {task['description']}")
|
| 396 |
-
print(f"Difficulty: {task['difficulty']}")
|
| 397 |
-
print(f"Targets: RAM < {task['target_ram']}%, Energy < {task['target_energy']} kWh")
|
| 398 |
-
print(f"Min Grader Score to Proceed: {task['min_grader_score']}")
|
| 399 |
-
|
| 400 |
-
pipeline_results["total_tasks_attempted"] += 1
|
| 401 |
-
task_result = {
|
| 402 |
-
"task_name": task["name"],
|
| 403 |
-
"difficulty": task["difficulty"],
|
| 404 |
-
"steps": [],
|
| 405 |
-
"total_reward": 0.0,
|
| 406 |
-
"final_grader_score": 0.0,
|
| 407 |
-
"passed": False,
|
| 408 |
-
}
|
| 409 |
-
|
| 410 |
-
# Initialize environment for this task
|
| 411 |
-
try:
|
| 412 |
-
result = await env.reset(task_config={"task": task["name"], "difficulty": task["difficulty"]})
|
| 413 |
-
# Extract observation from result
|
| 414 |
-
if hasattr(result, 'observation'):
|
| 415 |
-
observation = result.observation
|
| 416 |
-
else:
|
| 417 |
-
observation = result
|
| 418 |
-
except Exception as e:
|
| 419 |
-
print(f"\n❌ Failed to reset environment for task: {e}")
|
| 420 |
-
task_result["error"] = str(e)
|
| 421 |
-
pipeline_results["tasks"].append(task_result)
|
| 422 |
-
pipeline_results["pipeline_status"] = "STOPPED"
|
| 423 |
-
pipeline_results["failure_point"] = task["name"]
|
| 424 |
-
break
|
| 425 |
-
|
| 426 |
-
# Get LLM instruction (free-form message)
|
| 427 |
-
print(f"\n📍 Getting LLM instruction for {task['name']}...")
|
| 428 |
-
if use_llm:
|
| 429 |
-
try:
|
| 430 |
-
from openai import OpenAI
|
| 431 |
-
client = OpenAI(api_key=hf_token, base_url="https://router.huggingface.co/v1/")
|
| 432 |
-
|
| 433 |
-
# Request free-form message (not restricted to action_type,intensity)
|
| 434 |
-
response = client.chat.completions.create(
|
| 435 |
-
model=model_name,
|
| 436 |
-
messages=[{
|
| 437 |
-
"role": "user",
|
| 438 |
-
"content": f"""You are an energy optimization expert. The current task is: {task['name']}
|
| 439 |
-
|
| 440 |
-
Description: {task['description']}
|
| 441 |
-
Current RAM: {observation.ram_usage}%
|
| 442 |
-
Current Energy: {observation.energy_consumption} kWh
|
| 443 |
-
|
| 444 |
-
Suggest a sequence of actions as a natural language message (don't use action_type,intensity format).
|
| 445 |
-
Be specific and concise. Example: 'aggressively reduce_ram with 0.9 intensity, then optimize_energy with 0.8'"""
|
| 446 |
-
}],
|
| 447 |
-
max_tokens=200,
|
| 448 |
-
temperature=0.7,
|
| 449 |
-
)
|
| 450 |
-
|
| 451 |
-
llm_message = response.choices[0].message.content.strip()
|
| 452 |
-
print(f"✓ LLM Response: {llm_message}")
|
| 453 |
-
|
| 454 |
-
except Exception as e:
|
| 455 |
-
print(f"⚠️ Could not get LLM instruction: {e}")
|
| 456 |
-
llm_message = f"reduce_ram with 0.8 intensity, then optimize_energy with 0.6"
|
| 457 |
-
else:
|
| 458 |
-
llm_message = f"reduce_ram with 0.8 intensity, then optimize_energy with 0.6"
|
| 459 |
-
print(f"Using default action sequence: {llm_message}")
|
| 460 |
-
|
| 461 |
-
# Evaluate message with token-based reward system
|
| 462 |
-
message_score, token_details = TokenRewardEvaluator.evaluate_message(llm_message)
|
| 463 |
-
print(f"\n📊 Token-Based Reward Analysis:")
|
| 464 |
-
print(f" Message Score: {message_score}")
|
| 465 |
-
print(f" Tokens analyzed: {len(token_details)}")
|
| 466 |
-
for token_info in token_details[:5]: # Show first 5 tokens
|
| 467 |
-
print(f" - '{token_info['token']}': {token_info['score']} ({token_info['category']})")
|
| 468 |
-
|
| 469 |
-
# Execute actions based on message
|
| 470 |
-
step_count = 0
|
| 471 |
-
total_reward = 0.0
|
| 472 |
-
max_steps = task["max_steps"]
|
| 473 |
-
|
| 474 |
-
# Parse and execute actions from message
|
| 475 |
-
actions_to_execute = [
|
| 476 |
-
("reduce_ram", 0.8),
|
| 477 |
-
("optimize_energy", 0.6),
|
| 478 |
-
]
|
| 479 |
-
|
| 480 |
-
# Show observation block
|
| 481 |
-
obs_block = ObservationBlock(
|
| 482 |
-
timestamp=datetime.now().isoformat(),
|
| 483 |
-
step=0,
|
| 484 |
-
task_name=task["name"],
|
| 485 |
-
task_difficulty=task["difficulty"],
|
| 486 |
-
current_ram=observation.ram_usage,
|
| 487 |
-
current_energy=observation.energy_consumption,
|
| 488 |
-
steps_taken=0,
|
| 489 |
-
total_reward=0.0,
|
| 490 |
-
task_progress=0.0,
|
| 491 |
-
)
|
| 492 |
-
print(obs_block)
|
| 493 |
-
|
| 494 |
-
# Execute actions
|
| 495 |
-
for action_type, intensity in actions_to_execute:
|
| 496 |
-
if step_count >= max_steps:
|
| 497 |
-
break
|
| 498 |
-
|
| 499 |
-
step_count += 1
|
| 500 |
-
|
| 501 |
-
try:
|
| 502 |
-
action = EnergyOptimizationAction(
|
| 503 |
-
action_type=action_type,
|
| 504 |
-
intensity=float(intensity),
|
| 505 |
-
)
|
| 506 |
-
result = await env.step(action)
|
| 507 |
-
# Extract observation from result
|
| 508 |
-
if hasattr(result, 'observation'):
|
| 509 |
-
observation = result.observation
|
| 510 |
-
else:
|
| 511 |
-
observation = result
|
| 512 |
-
|
| 513 |
-
step_reward = float(intensity)
|
| 514 |
-
total_reward += step_reward
|
| 515 |
-
|
| 516 |
-
task_result["steps"].append({
|
| 517 |
-
"step": step_count,
|
| 518 |
-
"action": f"{action_type},{intensity}",
|
| 519 |
-
"reward": step_reward,
|
| 520 |
-
"ram": observation.ram_usage,
|
| 521 |
-
"energy": observation.energy_consumption,
|
| 522 |
-
})
|
| 523 |
-
|
| 524 |
-
# Show observation block for each step
|
| 525 |
-
obs_block = ObservationBlock(
|
| 526 |
-
timestamp=datetime.now().isoformat(),
|
| 527 |
-
step=step_count,
|
| 528 |
-
task_name=task["name"],
|
| 529 |
-
task_difficulty=task["difficulty"],
|
| 530 |
-
current_ram=observation.ram_usage,
|
| 531 |
-
current_energy=observation.energy_consumption,
|
| 532 |
-
steps_taken=step_count,
|
| 533 |
-
total_reward=total_reward,
|
| 534 |
-
last_action=f"{action_type},{intensity}",
|
| 535 |
-
last_action_reward=step_reward,
|
| 536 |
-
task_progress=min(100.0, (step_count / max_steps) * 100),
|
| 537 |
-
)
|
| 538 |
-
print(obs_block)
|
| 539 |
-
|
| 540 |
-
except Exception as e:
|
| 541 |
-
print(f"\n❌ Step {step_count} failed: {e}")
|
| 542 |
-
break
|
| 543 |
-
|
| 544 |
-
# Calculate final grader score
|
| 545 |
-
grader_fn = GRADERS.get(task["name"])
|
| 546 |
-
if grader_fn:
|
| 547 |
-
final_score = grader_fn(observation)
|
| 548 |
-
else:
|
| 549 |
-
final_score = 0.5
|
| 550 |
-
|
| 551 |
-
task_result["total_reward"] = total_reward
|
| 552 |
-
task_result["final_grader_score"] = final_score
|
| 553 |
-
task_result["total_steps"] = step_count
|
| 554 |
-
|
| 555 |
-
# Check if task passed (min_grader_score requirement)
|
| 556 |
-
if final_score >= task["min_grader_score"]:
|
| 557 |
-
task_result["passed"] = True
|
| 558 |
-
pipeline_results["total_tasks_completed"] += 1
|
| 559 |
-
print(f"\n✅ TASK PASSED: Grader Score {final_score} >= {task['min_grader_score']}")
|
| 560 |
-
else:
|
| 561 |
-
print(f"\n❌ TASK FAILED: Grader Score {final_score} < {task['min_grader_score']}")
|
| 562 |
-
pipeline_results["pipeline_status"] = "STOPPED"
|
| 563 |
-
pipeline_results["failure_point"] = task["name"]
|
| 564 |
-
pipeline_results["tasks"].append(task_result)
|
| 565 |
-
break # Stop pipeline on failure
|
| 566 |
-
|
| 567 |
-
pipeline_results["tasks"].append(task_result)
|
| 568 |
-
|
| 569 |
-
# Final summary
|
| 570 |
-
print(f"\n{'='*80}")
|
| 571 |
-
print("PIPELINE SUMMARY")
|
| 572 |
-
print(f"{'='*80}")
|
| 573 |
-
print(f"Tasks Attempted: {pipeline_results['total_tasks_attempted']}")
|
| 574 |
-
print(f"Tasks Completed: {pipeline_results['total_tasks_completed']}")
|
| 575 |
-
print(f"Pipeline Status: {pipeline_results['pipeline_status']}")
|
| 576 |
-
|
| 577 |
-
if pipeline_results["failure_point"]:
|
| 578 |
-
print(f"Failed at: {pipeline_results['failure_point']}")
|
| 579 |
-
else:
|
| 580 |
-
print("✅ ALL TASKS COMPLETED SUCCESSFULLY!")
|
| 581 |
-
|
| 582 |
-
# Save results
|
| 583 |
-
results_file = "pipeline_results.json"
|
| 584 |
-
with open(results_file, "w") as f:
|
| 585 |
-
json.dump(pipeline_results, f, indent=2)
|
| 586 |
-
|
| 587 |
-
print(f"\n✓ Results saved to {results_file}")
|
| 588 |
-
|
| 589 |
-
return pipeline_results
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
# ============================================================================
|
| 593 |
-
# ENTRY POINT
|
| 594 |
-
# ============================================================================
|
| 595 |
-
|
| 596 |
-
async def main():
|
| 597 |
-
"""Main entry point"""
|
| 598 |
-
try:
|
| 599 |
-
results = await run_dependent_task_pipeline()
|
| 600 |
-
print("\n✅ Pipeline execution completed")
|
| 601 |
-
return results
|
| 602 |
-
except Exception as e:
|
| 603 |
-
print(f"\n❌ Fatal error: {e}")
|
| 604 |
-
import traceback
|
| 605 |
-
traceback.print_exc()
|
| 606 |
-
return {"status": "error", "error": str(e)}
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
if __name__ == "__main__":
|
| 610 |
-
asyncio.run(main())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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