Spaces:
Running
Running
Commit ·
2ede269
1
Parent(s): f316664
fix llm based reward output
Browse files45 unmodified lines46474849505152535455565758596061626364656667686970717236 unmodified lines1091101111121131141151 unmodified line11711811912012112212312412512662 unmodified lines18919019119219319419519611 unmodified lines208209210211212213214215216217218219220221222223224122 unmodified lines34734834935035135230 unmodified lines38338438538638738838939039139239339439539639739839940028 unmodified lines429430431432433434435436437438124 unmodified lines56356456556656756856957057145 unmodified lines# ── Constants ──────────────────────────────────────────────────────────────ENV_URL = os.getenv("ENV_URL", "http://localhost:7860")MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-7B-Instruct")API_BASE_URL = os.getenv("API_BASE_URL", "https://api-inference.huggingface.co/v1")# ── Environment Variable Handling ─────────────────────────────────────────# The LLM API credential is read from HF_TOKEN or OPENAI_API_KEY environment variables# and passed directly to the OpenAI client for initialization.# Primary: HF_TOKEN# Fallback: OPENAI_API_KEY (for local testing/development)HF_TOKEN = os.getenv("HF_TOKEN")OPENAI_API_KEY = HF_TOKENDEFAULT_EPISODES = 1DEFAULT_SEED_BASE = 1000MAX_RETRIES = 3# 96 steps × 15 min = 24 h (must match env.EpisodeSteps)EPISODE_STEPS = 96LAST_STEP_INDEX = EPISODE_STEPS - 1SCORE_EPSILON = 1e-6REW_MIN = -8.0REW_MAX = 6.0REW_RANGE = REW_MAX - REW_MINSYSPROMPT = """You are GridMind, an expert industrial energy management controller.You control a building's HVAC, thermal storage, batch job scheduling, and load shedding.36 unmodified linesdef clamp_open_score(score: float) -> float:"""Clamp score into strict open interval (0, 1)."""if score <= 0.0:return SCORE_EPSILONif score >= 1.0:1 unmodified linereturn scoredef normalize_reward(raw_reward: float) -> float:"""Normalize raw reward to (0, 1) using fixed theoretical range."""normalized = (raw_reward - REW_MIN) / REW_RANGEreturn clamp_open_score(normalized)# ── Environment client ───────────────────────────────────────────────────────62 unmodified lines"""OpenAI-compatible LLM agent that chooses actions given observations."""def __init__(self):# Initialize OpenAI client with credentials from HF_TOKEN (per hackathon spec)# The OPENAI_API_KEY variable contains the HF_TOKEN value passed by evaluatorsself.client = OpenAI(base_url=API_BASE_URL, api_key=OPENAI_API_KEY)self.model = MODEL_NAMEself.fallback_mode = False11 unmodified lines- Thermal storage level: {obs.get('thermal_storage_level', 0.5):.2f} (0=empty, 1=full)- Process demand: {obs.get('process_demand', 15):.1f} kW- Current electricity price: ${obs.get('current_price', 0.10):.4f}/kWh- Grid stress signal: {obs.get('grid_stress_signal', 0):.3f} (>0.7 = critical, shed load!)- Carbon intensity: {obs.get('carbon_intensity', 300):.0f} gCO2/kWh- Hour of day: {obs.get('hour_of_day', 12)} (0=midnight, peak prices 8-12 and 17-21)- Pending batch job deadlines: {obs.get('batch_queue', [])}- Cumulative cost so far: ${obs.get('cumulative_cost', 0):.4f}- Episode step: {obs.get('step', 0)}/{LAST_STEP_INDEX}Strategy hints:- Charge thermal storage when price < $0.08/kWh, discharge when price > $0.15/kWh- Set HVAC low during peak prices (0.3-0.4) and use storage for temperature control- Shed 30-50% load if grid_stress_signal > 0.7- Schedule batch jobs early if deadline is close (slot 0 or 1)Respond with ONLY a JSON action:122 unmodified linescached_action = agent._default_action()step_rewards: list[float] = []success = Falseobs: dict[str, Any] = {}30 unmodified linesobs = step_resp["observation"]raw_reward = float(step_resp["reward"])reward = normalize_reward(raw_reward)total_reward += raw_rewardstep_rewards.append(raw_reward)total_steps += 1done = bool(step_resp.get("done", False))action_json = json.dumps(action, separators=(',', ':'))last_action_error = step_resp.get("last_action_error")error_field = "null" if last_action_error is None else str(last_action_error)print(f"[STEP] step={total_steps} action={action_json} "f"reward={reward:.2f} done={'true' if done else 'false'} error={error_field}",flush=True)28 unmodified lineselapsed = time.time() - start_timegrade = env_client.grade()if step_rewards:normalized_rewards = [normalize_reward(r) for r in step_rewards]else:normalized_rewards = []episode_score = sum(normalized_rewards) / len(normalized_rewards) if normalized_rewards else SCORE_EPSILONepisode_score = clamp_open_score(episode_score)124 unmodified linesparser.add_argument("--llm-every",type=int,default=4,metavar="N",help="Reuse the same LLM action for N consecutive steps (default: 4).",)parser.add_argument("--max-steps",45 unmodified lines4647484950515253545556575859606136 unmodified lines98991001011021031041 unmodified line10610710810911011111211311411511611711811912012162 unmodified lines18418518618718818911 unmodified lines201202203204205206207208209210211212213214215216217218219220221222223122 unmodified lines34634734834935035135235330 unmodified lines38438538638738838939039139239339439539639739839940040140240340440540640740840941041141228 unmodified lines441442443444445446447124 unmodified lines57257357457557657757857958045 unmodified lines# ── Constants ──────────────────────────────────────────────────────────────ENV_URL = os.getenv("ENV_URL", "http://localhost:7860")HF_TOKEN = os.getenv("HF_TOKEN")OPENAI_API_KEY = HF_TOKENMODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-7B-Instruct")API_BASE_URL = os.getenv("API_BASE_URL", "https://api-inference.huggingface.co/v1")DEFAULT_EPISODES = 1DEFAULT_SEED_BASE = 1000MAX_RETRIES = 3EPISODE_STEPS = 96LAST_STEP_INDEX = EPISODE_STEPS - 1SCORE_EPSILON = 0.01SYSPROMPT = """You are GridMind, an expert industrial energy management controller.You control a building's HVAC, thermal storage, batch job scheduling, and load shedding.36 unmodified linesdef clamp_open_score(score: float) -> float:"""Clamp score to strictly between 0 and 1 (never 0.0 or 1.0)."""if score <= 0.0:return SCORE_EPSILONif score >= 1.0:1 unmodified linereturn scoredef normalize_rewards(raw_rewards: list[float]) -> list[float]:"""Normalize raw rewards to (0, 1) using min-max scaling."""if not raw_rewards:return []raw_min = min(raw_rewards)raw_max = max(raw_rewards)raw_range = raw_max - raw_minif raw_range > 0:return [clamp_open_score((r - raw_min) / raw_range) for r in raw_rewards]return [0.5] * len(raw_rewards)# ── Environment client ───────────────────────────────────────────────────────62 unmodified lines"""OpenAI-compatible LLM agent that chooses actions given observations."""def __init__(self):self.client = OpenAI(base_url=API_BASE_URL, api_key=OPENAI_API_KEY)self.model = MODEL_NAMEself.fallback_mode = False11 unmodified lines- Thermal storage level: {obs.get('thermal_storage_level', 0.5):.2f} (0=empty, 1=full)- Process demand: {obs.get('process_demand', 15):.1f} kW- Current electricity price: ${obs.get('current_price', 0.10):.4f}/kWh- Grid stress signal: {obs.get('grid_stress_signal', 0):.3f} (>0.7 = critical, MUST shed 0.2-0.5 load!)- Carbon intensity: {obs.get('carbon_intensity', 300):.0f} gCO2/kWh- Hour of day: {obs.get('hour_of_day', 12)} (0=midnight, peak prices 8-12 and 17-21)- Pending batch job deadlines: {obs.get('batch_queue', [])}- Cumulative cost so far: ${obs.get('cumulative_cost', 0):.4f}- Episode step: {obs.get('step', 0)}/{LAST_STEP_INDEX}IMPORTANT RULES:- thermal_charge_rate: use NEGATIVE (-0.5) to DISCHARGE storage, POSITIVE (+0.5) to CHARGE- load_shed_fraction: MUST be 0.2-0.5 when grid_stress_signal > 0.7, otherwise 0.0- shed load during grid stress to earn rewards, else keep at 0.0Strategy hints:- Charge thermal storage (positive) when price < $0.08/kWh- Discharge thermal storage (negative) when price > $0.15/kWh- MUST shed load (0.2-0.5) when grid_stress_signal > 0.7- Set HVAC low during peak prices (0.3-0.4) and use storage for temperature control- Schedule batch jobs early if deadline is close (slot 0 or 1)Respond with ONLY a JSON action:122 unmodified linescached_action = agent._default_action()step_rewards: list[float] = []reward_min = float('inf')reward_max = float('-inf')success = Falseobs: dict[str, Any] = {}30 unmodified linesobs = step_resp["observation"]raw_reward = float(step_resp["reward"])total_reward += raw_rewardstep_rewards.append(raw_reward)if raw_reward < reward_min:reward_min = raw_rewardif raw_reward > reward_max:reward_max = raw_rewardtotal_steps += 1done = bool(step_resp.get("done", False))reward_range = reward_max - reward_minif reward_range > 0:normalized_reward = clamp_open_score((raw_reward - reward_min) / reward_range)else:normalized_reward = 0.5action_json = json.dumps(action, separators=(',', ':'))last_action_error = step_resp.get("last_action_error")error_field = "null" if last_action_error is None else str(last_action_error)print(f"[STEP] step={total_steps} action={action_json} "f"reward={normalized_reward:.2f} done={'true' if done else 'false'} error={error_field}",flush=True)28 unmodified lineselapsed = time.time() - start_timegrade = env_client.grade()normalized_rewards = normalize_rewards(step_rewards)episode_score = sum(normalized_rewards) / len(normalized_rewards) if normalized_rewards else SCORE_EPSILONepisode_score = clamp_open_score(episode_score)124 unmodified linesparser.add_argument("--llm-every",type=int,default=8,metavar="N",help="Reuse the same LLM action for N consecutive steps (default: 8).",)parser.add_argument("--max-steps",
inference.py+41-32