Spaces:
Running
Running
refactor: replace heuristic log generation with Go-based environment simulation and update API schema
Browse filesFiles changed (9)
- .gitignore+2-1
- baseline_scores.json+38-5
- env/environment.go+31
- env/models.go+20-11
- generate_realistic_training_log.pyDeleted-33
- generate_training_log.pyDeleted-52
- inference.py+1-1
- main.go+30-6
- openenv.yaml+23-3
76 unmodified lines7778798076 unmodified linesIMPLEMENTATION_PLAN.mdTODO_SPRINT.mdcontext.mdREPORT.md76 unmodified lines777879808176 unmodified linesIMPLEMENTATION_PLAN.mdTODO_SPRINT.mdcontext.mdREPORT.mdgridmind.exegridmind-server.exe
6 unmodified lines78910111213141516171819202122236 unmodified lines"llm_every": 8,"max_steps": null,"task_averages": {"1": 0.5482},"overall_average": 0.5482,"all_results": [{"task_id": 1,"seed": 1100,"total_reward": 249.22208122816207,"total_steps": 96,"elapsed_sec": 1.4036986827850342,"score": 0.5482,"sub_scores": {},"exploit_detected": false}6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455566 unmodified lines"llm_every": 8,"max_steps": null,"task_averages": {"1": 0.4942,"2": 0.4707,"3": 0.7478,"4": 0.4779},"overall_average": 0.54765,"all_results": [{"task_id": 1,"seed": 1100,"total_reward": 251.84571448658104,"total_steps": 96,"elapsed_sec": 1.227782964706421,"score": 0.4942,"sub_scores": {},"exploit_detected": false},{"task_id": 2,"seed": 1200,"total_reward": 245.38403598363988,"total_steps": 96,"elapsed_sec": 0.8327796459197998,"score": 0.4707,"sub_scores": {},"exploit_detected": false},{"task_id": 3,"seed": 1300,"total_reward": 242.06080137356216,"total_steps": 96,"elapsed_sec": 0.6833479404449463,"score": 0.7478,"sub_scores": {},"exploit_detected": false},{"task_id": 4,"seed": 1400,"total_reward": 206.4647897455665,"total_steps": 96,"elapsed_sec": 1.0237984657287598,"score": 0.4779,"sub_scores": {},"exploit_detected": false}
586 unmodified lines58758858959059159299 unmodified lines6926936946956966979 unmodified lines707708709710711712586 unmodified linesEpisode: e.episode,Step: s,},}}99 unmodified lines// Apply sensor fault noise to observation (not physics) - if sensor fault is active, agent sees wrong tempreportedTemp := b.IndoorTemperature + b.TempObservationNoisereturn ObservationModel{IndoorTemperature: math.Round(reportedTemp*100) / 100,ThermalStorageLevel: math.Round(b.ThermalStorageLevel*1000) / 1000,9 unmodified linesHVACEfficiency: math.Round(b.HVACEfficiency*1000) / 1000,InstructionCard: e.InstructionCard,ActiveFaults: activeFaults,}}586 unmodified lines58758858959059159259399 unmodified lines6936946956966976986997007017027037047057067077087097107117127137147157167177187197207219 unmodified lines731732733734735736737738739740741742743586 unmodified linesEpisode: e.episode,Step: s,},Rewards: rc,}}99 unmodified lines// Apply sensor fault noise to observation (not physics) - if sensor fault is active, agent sees wrong tempreportedTemp := b.IndoorTemperature + b.TempObservationNoisetaskCardStr := ""if e.taskID == 4 && e.InstructionCard != nil {taskCardStr = e.InstructionCard.Text} else if e.taskID == 1 {taskCardStr = "Task 1 (Easy - Cost Minimization): Minimize total energy cost over 24 hours. No temperature or batch constraints. Use cheap off-peak periods and thermal storage."} else if e.taskID == 2 {taskCardStr = "Task 2 (Medium - Temperature Management): Minimize cost AND keep indoor temperature within 19-23°C at all times. Balance comfort vs cost."} else if e.taskID == 3 {taskCardStr = "Task 3 (Hard - Full Demand Response): Minimize cost, maintain temperature, respond to grid stress (shed when grid_stress_signal > 0.7), schedule batch jobs, minimize carbon."} else {taskCardStr = "Maintain operations and minimize cost."}priceForecast := make([]float64, 4)for i := 0; i < 4; i++ {idx := b.Step + iif idx < EpisodeSteps {priceForecast[i] = math.Round(e.PriceCurve[idx]*10000) / 10000} else {priceForecast[i] = math.Round(e.PriceCurve[EpisodeSteps-1]*10000) / 10000}}return ObservationModel{IndoorTemperature: math.Round(reportedTemp*100) / 100,ThermalStorageLevel: math.Round(b.ThermalStorageLevel*1000) / 1000,9 unmodified linesHVACEfficiency: math.Round(b.HVACEfficiency*1000) / 1000,InstructionCard: e.InstructionCard,ActiveFaults: activeFaults,TaskCard: taskCardStr,NLSummary: "GridMind simulation state.",MarketType: "tou",Season: "summer",PriceVolatility: 0.2,PriceForecast: priceForecast,DemandChargeActive: false,}}
75 unmodified lines7677787980815 unmodified lines878889909192939495969798991001011021031042 unmodified lines10710810911011111275 unmodified linesHVACEfficiency float64 `json:"hvac_efficiency"`InstructionCard *InstructionCard `json:"instruction_card,omitempty"` // populated for Task 4 onlyActiveFaults []string `json:"active_faults,omitempty"` // human-readable alarm strings for active faults}// ActionModel is the parsed agent action for a single step.5 unmodified linesBuildingID int `json:"building_id"` // which building to act on}// RewardComponents holds the individual components of the dense reward signal.type RewardComponents struct {CostSavings float64 `json:"cost_savings"` // negative = expensiveTempConstraint float64 `json:"temp_constraint"` // positive = within boundsGridResponse float64 `json:"grid_response"` // bonus for DR complianceDeadlinePenalty float64 `json:"deadline_penalty"` // negative for missed jobsEfficiencyBonus float64 `json:"efficiency_bonus"` // storage arbitrageStabilityPenalty float64 `json:"stability_penalty"` // HVAC oscillation penaltyCarbonReward float64 `json:"carbon_reward"` // low-carbon bonusInstructionReward float64 `json:"instruction_reward"` // Task 4: instruction-following scoreFaultMitigation float64 `json:"fault_mitigation"` // Track 3: reward for proper fault responseTotal float64 `json:"total"`}// StepResponse is the full HTTP body returned from POST /step.2 unmodified linesReward float64 `json:"reward"`Done bool `json:"done"`Info StepInfo `json:"info"`}// StepInfo carries auxiliary information per step.75 unmodified lines767778798081828384858687885 unmodified lines9495969798991001011021031041051061071081091101111122 unmodified lines11511611711811912012175 unmodified linesHVACEfficiency float64 `json:"hvac_efficiency"`InstructionCard *InstructionCard `json:"instruction_card,omitempty"` // populated for Task 4 onlyActiveFaults []string `json:"active_faults,omitempty"` // human-readable alarm strings for active faultsTaskCard string `json:"task_card"`NLSummary string `json:"nl_summary"`MarketType string `json:"market_type"`Season string `json:"season"`PriceVolatility float64 `json:"price_volatility"`PriceForecast []float64 `json:"price_forecast"`DemandChargeActive bool `json:"demand_charge_active"`}// ActionModel is the parsed agent action for a single step.5 unmodified linesBuildingID int `json:"building_id"` // which building to act on}type RewardComponents struct {CostSavings float64 `json:"cost_savings"`TempConstraint float64 `json:"temperature_constraint"`GridResponse float64 `json:"grid_response"`DeadlinePenalty float64 `json:"deadline_penalty"`EfficiencyBonus float64 `json:"efficiency_bonus"`StabilityPenalty float64 `json:"stability_penalty"`CarbonReward float64 `json:"carbon_reward"`InstructionReward float64 `json:"task_satisfaction"`FaultMitigation float64 `json:"fault_mitigation"`PriceAnticipation float64 `json:"price_anticipation"`DemandChargePenalty float64 `json:"demand_charge_penalty"`Total float64 `json:"total"`}// StepResponse is the full HTTP body returned from POST /step.2 unmodified linesReward float64 `json:"reward"`Done bool `json:"done"`Info StepInfo `json:"info"`Rewards RewardComponents `json:"rewards"`}// StepInfo carries auxiliary information per step.
123456789101112131415161718192021222324252627282930313233#!/usr/bin/env python3import csv, random, math, os
random.seed(42)os.makedirs("results", exist_ok=True)
rows = []for step in range(0, 301, 5): progress = step / 300 base = 0.52 + (0.68 - 0.52) * (1 - math.exp(-3 * progress)) + random.gauss(0, 0.015) json_valid = min(0.2, 0.15 + random.gauss(0, 0.03)) rows.append({ "step": step, "loss": max(0.000001, 0.00002 - progress * 0.00001 + random.gauss(0, 0.000005)), "rewards/reward_json_valid/mean": max(0, min(0.2, json_valid)), "rewards/reward_json_valid/std": 0.02, "rewards/reward_env_interaction/mean": max(0.4, min(0.75, base)), "rewards/reward_env_interaction/std": 0.02, "rewards/reward/mean": 0.20 + json_valid + max(0.4, min(0.75, base)) * 0.4, })
columns = ["step", "loss", "rewards/reward_json_valid/mean", "rewards/reward_json_valid/std", "rewards/reward_env_interaction/mean", "rewards/reward_env_interaction/std", "rewards/reward/mean"]
with open("results/training_log.csv", "w", newline="") as f: writer = csv.DictWriter(f, fieldnames=columns) writer.writeheader() writer.writerows(rows)
print(f"Generated {len(rows)} training steps with realistic learning curve")print(f"Initial episode score: {rows[0]['rewards/reward_env_interaction/mean']:.3f}")print(f"Final episode score: {rows[-1]['rewards/reward_env_interaction/mean']:.3f}")print(f"Improvement: {(rows[-1]['rewards/reward_env_interaction/mean'] - rows[0]['rewards/reward_env_interaction/mean']):.3f}")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152#!/usr/bin/env python3"""GridMind-RL Training Log GeneratorGenerates a realistic training log CSV from heuristic baseline runs."""import csvimport osimport jsonimport randomimport math
random.seed(42)
os.makedirs("results", exist_ok=True)
with open("results/baseline_scores_heuristic.json") as f: heuristic_data = json.load(f)
heuristic_by_task = {int(k): v for k, v in heuristic_data["task_averages"].items()}overall_heuristic = heuristic_data["overall_average"]llm_baseline = 0.65target_performance = 0.72
N_STEPS = 200NOISE_SCALE = 0.02IMPROVEMENT_RATE = 0.003
rows = []for step in range(0, N_STEPS + 1, 5): progress = step / N_STEPS base = overall_heuristic + (target_performance - overall_heuristic) * math.sin(progress * math.pi / 2) loss = 2.0 - progress * 1.5 + random.gauss(0, 0.1) reward_valid = 0.3 + random.gauss(0, 0.02) reward_keys = 0.3 + random.gauss(0, 0.02) reward_env = base * 0.4 + random.gauss(0, NOISE_SCALE) rows.append({ "step": step, "loss": max(0.1, loss), "reward_valid_json": reward_valid, "reward_has_required_keys": reward_keys, "reward_env_interaction": max(0.0, min(0.4, reward_env)), })
with open("results/training_log.csv", "w", newline="") as f: writer = csv.DictWriter(f, fieldnames=["step", "loss", "reward_valid_json", "reward_has_required_keys", "reward_env_interaction"]) writer.writeheader() writer.writerows(rows)
print(f"Generated {len(rows)} training steps -> results/training_log.csv")print(f"Heuristic baseline: {overall_heuristic:.3f}")print(f"Target performance: {target_performance:.3f}")print(f"Final reward_env: {rows[-1]['reward_env_interaction']:.3f}")38 unmodified lines3940414243444538 unmodified linesENV_URL = os.getenv("ENV_URL", "http://localhost:7860")HF_TOKEN = os.getenv("HF_TOKEN") # Mandatory — no defaultAPI_BASE_URL = os.getenv("API_BASE_URL", "https://api-inference.huggingface.co/v1")MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-7B-Instruct")# ── Constants ────────────────────────────────────────────────────────────────BENCHMARK = "gridmind"38 unmodified lines3940414243444538 unmodified linesENV_URL = os.getenv("ENV_URL", "http://localhost:7860")HF_TOKEN = os.getenv("HF_TOKEN") # Mandatory — no defaultAPI_BASE_URL = os.getenv("API_BASE_URL", "https://api-inference.huggingface.co/v1")MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-1.5B-Instruct")# ── Constants ────────────────────────────────────────────────────────────────BENCHMARK = "gridmind"
239 unmodified lines240241242243244245246247248249250251252253254239 unmodified lineshttp.Error(w, "method not allowed", http.StatusMethodNotAllowed)return}var req env.ResetRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {// Allow empty body → defaultsreq = env.ResetRequest{TaskID: 1}}if req.TaskID == 0 {req.TaskID = 1}resp := s.envMgr.Reset(req)w.Header().Set("Content-Type", "application/json")json.NewEncoder(w).Encode(resp)}239 unmodified lines240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278239 unmodified lineshttp.Error(w, "method not allowed", http.StatusMethodNotAllowed)return}var req map[string]interface{}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {req = make(map[string]interface{})}taskID := 1if t, ok := req["task_id"].(float64); ok {taskID = int(t)} else if t, ok := req["task_id"].(int64); ok {taskID = int(t)} else if t, ok := req["task_id"].(int); ok {taskID = t}if taskID == 0 {taskID = 1}seed := int64(0)if s, ok := req["seed"].(float64); ok {seed = int64(s)} else if s, ok := req["seed"].(int64); ok {seed = s}numBuildings := 1if nb, ok := req["num_buildings"].(float64); ok {numBuildings = int(nb)}resetReq := env.ResetRequest{TaskID: taskID,NumBuildings: numBuildings,}if seed > 0 {resetReq.Seed = &seed}resp := s.envMgr.Reset(resetReq)w.Header().Set("Content-Type", "application/json")json.NewEncoder(w).Encode(resp)}
76 unmodified lines777879808182127 unmodified lines210211212213214215216217218219124 unmodified lines34434534634734834935035135235335476 unmodified linesitems:type: stringdescription: "Human-readable list of active fault alarm strings. Empty when no faults. Track 3."instruction_card:type: [object, "null"]description: "Natural language objective card. Only populated when task_id=4. Track 2."127 unmodified linestype: numbercarbon_reward:type: numberinstruction_reward:type: numberfault_mitigation:type: numbertotal:type: numberenergy_used_kwh:124 unmodified lineshealth:path: /healthmethod: GETdescription: Health check - returns {"status": "ok", "version": "1.0.0"}ping:path: /pingmethod: GETdescription: Liveness probe - returns {"status": "ok"}reset:path: /resetmethod: POST76 unmodified lines77787980818283848586878889909192939495969798127 unmodified lines226227228229230231232233234235236237238239124 unmodified lines36436536636736836937037137237337476 unmodified linesitems:type: stringdescription: "Human-readable list of active fault alarm strings. Empty when no faults. Track 3."task_card:type: stringnl_summary:type: stringmarket_type:type: stringseason:type: stringprice_volatility:type: numberprice_forecast:type: arrayitems:type: numberdemand_charge_active:type: booleaninstruction_card:type: [object, "null"]description: "Natural language objective card. Only populated when task_id=4. Track 2."127 unmodified linestype: numbercarbon_reward:type: numbertask_satisfaction:type: numberfault_mitigation:type: numberprice_anticipation:type: numberdemand_charge_penalty:type: numbertotal:type: numberenergy_used_kwh:124 unmodified lineshealth:path: /healthmethod: GETdescription: 'Health check - returns {"status": "ok", "version": "1.0.0"}'ping:path: /pingmethod: GETdescription: 'Liveness probe - returns {"status": "ok"}'reset:path: /resetmethod: POST
.gitignore+2-1
baseline_scores.json+38-5
env/environment.go+31
env/models.go+20-11
generate_realistic_training_log.pyDeleted-33
generate_training_log.pyDeleted-52
inference.py+1-1
main.go+30-6
openenv.yaml+23-3