Spaces:
Running
Running
after transfer
#1
by ShreeshantXD - opened
Files changed (3)
- .gitattributesAdded+10
- .gitignore
- scripts/train_unsloth.py+68-37
12345678910*.png filter=xet merge=xet*.jpg filter=xet merge=xet*.jpeg filter=xet merge=xet*.gif filter=xet merge=xet*.pdf filter=xet merge=xet*.zip filter=xet merge=xet*.pth filter=xet merge=xet*.pt filter=xet merge=xet*.ckpt filter=xet merge=xet*.safetensors filter=xet merge=xet1234567893 unmodified lines131415161718192021222324252627282 unmodified lines3132333435363738394041424344454647484950515253541 unmodified line565758596061621 unmodified line646566676869703 unmodified lines747576777879803 unmodified lines84858687888990919293949596977 unmodified lines1051061071081091101111121134 unmodified lines1181191201211221231245 unmodified lines1301311321331341351361371381393 unmodified lines14314414514614714810 unmodified lines1591601611621631641653 unmodified lines16917017117217317417523 unmodified lines1992002012022032042052062072082092102112122132146 unmodified lines221222223224225226#!/usr/bin/env python3"""GridMind-RL Unsloth GRPO Training Script----------------------------------------Fine-tunes Qwen2.5-0.5B-Instruct using Unsloth's 4-bit LoRA and TRL's GRPOTrainer.The environment rewards are gathered by hitting the OpenEnv HTTP server directly."""import argparse3 unmodified linesimport sysimport requestsimport pandas as pdfrom datasets import Datasetfrom trl import GRPOTrainer, GRPOConfigfrom unsloth import FastLanguageModelfrom transformers import TrainerCallback# Ensure results directory existsos.makedirs("results", exist_ok=True)SYSTEM_PROMPT = """\You are an expert industrial building energy controller.Each turn you receive the current building state and must respond withONLY a valid JSON action object.2 unmodified lines"batch_job_slot": <0-4>, "load_shed_fraction": <0.0-0.5>, "building_id": 0}Strategy:- Charge storage when price < $0.08/kWh (positive thermal_charge_rate)- Discharge storage when price > $0.15/kWh (negative thermal_charge_rate)- Shed load 0.3-0.5 when grid_stress_signal > 0.7- Reduce HVAC during peak hours (8-12, 17-21)- Keep temperature between 19-23°C"""def make_prompt(i):return [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user","content": f"Episode {i+1}: The building simulation is starting. ""You will receive the state each step. ""Output your first action as JSON now."}]def reward_valid_json(completions, **kwargs):"""Reward 0.3 for any valid JSON output."""rewards = []for completion in completions:text = completion[0]["content"] if isinstance(completion, list) else completion1 unmodified linematch = re.search(r'\{.*?\}', text, re.DOTALL)if match:json.loads(match.group())rewards.append(0.3)else:rewards.append(0.0)except Exception:1 unmodified linereturn rewardsdef reward_has_required_keys(completions, **kwargs):"""Reward 0.3 if JSON has all 4 required action keys."""required = {"hvac_power_level", "thermal_charge_rate", "batch_job_slot", "load_shed_fraction"}rewards = []for completion in completions:3 unmodified linesif match:action = json.loads(match.group())if required.issubset(action.keys()):rewards.append(0.3)else:rewards.append(0.1)else:3 unmodified linesreturn rewardsdef get_reward_env_interaction(env_url):"""Episode-level reward from /grade endpoint with seed variation.Uses 8-step rollouts with varied seeds to prevent mode collapse.The /grade endpoint returns the true episode score (0.0-1.0 clamped),which we use directly as the primary learning signal."""def reward_env_interaction(completions, **kwargs):rewards = []for i, completion in enumerate(completions):text = completion[0]["content"] if isinstance(completion, list) else completiontry:7 unmodified lines"building_id": 0}# Vary seed to prevent mode collapse — each rollout sees a different episodeseed = 1000 + itask_id = (i % 3) + 1 # Cycle through tasks 1, 2, 3reset_resp = requests.post(f"{env_url}/reset",4 unmodified linesrewards.append(0.0)continuefor _ in range(8):step_resp = requests.post(f"{env_url}/step",json=[step_action],5 unmodified linesgrade_resp = requests.get(f"{env_url}/grade", timeout=30)if grade_resp.status_code == 200:episode_score = float(grade_resp.json().get("score", 0.5))# Normalize: heuristic baseline ≈ 0.5, zero-shot ≈ 0.65, trained ≈ 0.72# Map to 0.0-1.0 where 0.5 is the floor (heuristic), 0.72 is the ceiling (trained target)normalized = (episode_score - 0.4) / 0.32 # maps 0.4→0.0, 0.72→1.0rewards.append(max(0.0, min(1.0, normalized)))else:rewards.append(0.0)3 unmodified linesreturn rewardsreturn reward_env_interactionclass CSVLogCallback(TrainerCallback):"""Custom callback to continuously log training metrics to a CSV file."""def __init__(self, output_path):10 unmodified linesdef main():parser = argparse.ArgumentParser(description="Train GridMind-RL agent with Unsloth GRPO")parser.add_argument("--env-url", type=str, default="http://localhost:7860", help="OpenEnv server URL")parser.add_argument("--model-name", type=str, default="unsloth/Qwen2.5-0.5B-Instruct", help="Base model")parser.add_argument("--prompts", type=int, default=300, help="Number of training prompts")parser.add_argument("--epochs", type=int, default=1, help="Training epochs")parser.add_argument("--max-steps", type=int, default=-1, help="Max steps (overrides epochs if > 0)")3 unmodified linesprint(f"🚀 Loading model: {args.model_name}")max_seq_length = 512lora_rank = 8model, tokenizer = FastLanguageModel.from_pretrained(model_name=args.model_name,23 unmodified linesmax_steps=args.max_steps,per_device_train_batch_size=1,gradient_accumulation_steps=4,num_generations=4, # GRPO group sizemax_prompt_length=256,max_completion_length=128,learning_rate=5e-6,lr_scheduler_type="cosine",warmup_ratio=0.1,logging_steps=5,save_steps=100,fp16=True,report_to="none", # We use our CSV callback insteadseed=42,)6 unmodified linesreward_valid_json,reward_has_required_keys,get_reward_env_interaction(args.env_url),],callbacks=[CSVLogCallback(args.output_csv)])12345678910113 unmodified lines151617181920212223242526272829302 unmodified lines3334353637383940414243444546474849505152535455561 unmodified line585960616263641 unmodified line666768697071723 unmodified lines767778798081823 unmodified lines86878889909192939495969798991001011027 unmodified lines1101111121131141151161171184 unmodified lines1231241251261271281291301311321335 unmodified lines1391401411421431441453 unmodified lines14915015115215315415515615715815916016116216316416516616716816917017117217317417517617717810 unmodified lines1891901911921931941953 unmodified lines19920020120220320420523 unmodified lines2292302312322332342352362372382392402412422432446 unmodified lines251252253254255256257#!/usr/bin/env python3"""GridMind-RL Unsloth GRPO Training Script----------------------------------------------Fine-tunes Qwen2.5-1.5B-Instruct using Unsloth's 4-bit LoRA and TRL's GRPOTrainer.The environment rewards are gathered by hitting the OpenEnv HTTP server directly.FIXED: Removed reward hacking, added entropy bonus, diverse seeds, proper normalization."""import argparse3 unmodified linesimport sysimport requestsimport pandas as pdimport randomfrom collections import Counterfrom datasets import Datasetfrom trl import GRPOTrainer, GRPOConfigfrom unsloth import FastLanguageModelfrom transformers import TrainerCallbackos.makedirs("results", exist_ok=True)SYSTEM_PROMPT = """You are an expert industrial building energy controller.Each turn you receive the current building state and must respond withONLY a valid JSON action object.2 unmodified lines"batch_job_slot": <0-4>, "load_shed_fraction": <0.0-0.5>, "building_id": 0}Strategy:- Always respond with valid JSON containing all required keys- Vary your actions - don't repeat the same pattern- Optimize for low cost + comfort maintenance + grid response"""def make_prompt(i, obs=None, task_desc=""):system_content = SYSTEM_PROMPTif obs and task_desc:system_content += f"\n\nCurrent observation:\n- Temperature: {obs.get('indoor_temperature', 21):.1f}°C\n- Price: ${obs.get('current_price', 0.10):.3f}/kWh\n- Grid stress: {obs.get('grid_stress_signal', 0):.2f}\n- Hour: {obs.get('hour_of_day', 12)}\n- Storage: {obs.get('thermal_storage_level', 0.5):.1%}"return [{"role": "system", "content": system_content}, {"role": "user","content": f"Episode {i+1}: {task_desc}\nOutput action as JSON."}]def reward_valid_json(completions, **kwargs):"""Reward 0.25 for any valid JSON output."""rewards = []for completion in completions:text = completion[0]["content"] if isinstance(completion, list) else completion1 unmodified linematch = re.search(r'\{.*?\}', text, re.DOTALL)if match:json.loads(match.group())rewards.append(0.25)else:rewards.append(0.0)except Exception:1 unmodified linereturn rewardsdef reward_has_required_keys(completions, **kwargs):"""Reward 0.25 if JSON has all 4 required action keys."""required = {"hvac_power_level", "thermal_charge_rate", "batch_job_slot", "load_shed_fraction"}rewards = []for completion in completions:3 unmodified linesif match:action = json.loads(match.group())if required.issubset(action.keys()):rewards.append(0.25)else:rewards.append(0.1)else:3 unmodified linesreturn rewardsdef get_reward_env_interaction(env_url):"""Episode-level reward from /grade endpoint with diverse seeds.FIXED: Uses raw /grade score directly (0.0-1.0), no normalization that causes reward hacking.Each sample gets a different seed/task to prevent mode collapse."""last_observations = []def reward_env_interaction(completions, **kwargs):nonlocal last_observationsrewards = []for i, completion in enumerate(completions):text = completion[0]["content"] if isinstance(completion, list) else completiontry:7 unmodified lines"building_id": 0}# Diverse seeds to prevent mode collapseseed = 2000 + (i * 17) % 500task_id = (i % 3) + 1reset_resp = requests.post(f"{env_url}/reset",4 unmodified linesrewards.append(0.0)continueobs = reset_resp.json().get("observations", [{}])[0] if reset_resp.json().get("observations") else {}last_observations.append(obs)# 4-step mini-rollout for faster trainingfor _ in range(4):step_resp = requests.post(f"{env_url}/step",json=[step_action],5 unmodified linesgrade_resp = requests.get(f"{env_url}/grade", timeout=30)if grade_resp.status_code == 200:episode_score = float(grade_resp.json().get("score", 0.5))rewards.append(episode_score)else:rewards.append(0.0)3 unmodified linesreturn rewardsreturn reward_env_interactiondef reward_entropy_bonus(completions, **kwargs):"""Reward action diversity to prevent mode collapse - bonus for varied actions."""rewards = []actions_seen = []for completion in completions:text = completion[0]["content"] if isinstance(completion, list) else completiontry:match = re.search(r'\{.*?\}', text, re.DOTALL)if match:action = json.loads(match.group())actions_seen.append(json.dumps(action, sort_keys=True))except:passif len(actions_seen) > 1:unique_actions = len(set(actions_seen))diversity_ratio = unique_actions / len(actions_seen)rewards = [0.1 * diversity_ratio] * len(actions_seen)else:rewards = [0.05] * len(completions)return rewardsclass CSVLogCallback(TrainerCallback):"""Custom callback to continuously log training metrics to a CSV file."""def __init__(self, output_path):10 unmodified linesdef main():parser = argparse.ArgumentParser(description="Train GridMind-RL agent with Unsloth GRPO")parser.add_argument("--env-url", type=str, default="http://localhost:7860", help="OpenEnv server URL")parser.add_argument("--model-name", type=str, default="unsloth/Qwen2.5-1.5B-Instruct", help="Base model")parser.add_argument("--prompts", type=int, default=300, help="Number of training prompts")parser.add_argument("--epochs", type=int, default=1, help="Training epochs")parser.add_argument("--max-steps", type=int, default=-1, help="Max steps (overrides epochs if > 0)")3 unmodified linesprint(f"🚀 Loading model: {args.model_name}")max_seq_length = 512lora_rank = 16 # Increased for better learning capacitymodel, tokenizer = FastLanguageModel.from_pretrained(model_name=args.model_name,23 unmodified linesmax_steps=args.max_steps,per_device_train_batch_size=1,gradient_accumulation_steps=4,num_generations=4,max_prompt_length=256,max_completion_length=128,learning_rate=3e-6, # Lower LR for stabilitylr_scheduler_type="cosine",warmup_ratio=0.1,logging_steps=5,save_steps=100,fp16=True,report_to="none",seed=42,)6 unmodified linesreward_valid_json,reward_has_required_keys,get_reward_env_interaction(args.env_url),reward_entropy_bonus,],callbacks=[CSVLogCallback(args.output_csv)])
.gitattributesAdded+10
.gitignore
scripts/train_unsloth.py+68-37