glitchfilter commited on
Commit
dde819a
Β·
verified Β·
1 Parent(s): d8dac6c

training script

Browse files
Files changed (1) hide show
  1. train_hf_job.py +266 -0
train_hf_job.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """GRPO Training for Methanol APC β€” HF Jobs runner.
3
+
4
+ Run with: hf jobs run ghcr.io/huggingface/gpu-jobs:latest \
5
+ "python /data/train_hf_job.py" \
6
+ --flavor t4-medium --timeout 2h \
7
+ --volume methanol-training:/data
8
+ """
9
+ import json, os, random, sys, time, subprocess
10
+
11
+ # ── Install deps ──
12
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "-q",
13
+ "unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git"])
14
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "-q",
15
+ "--no-deps", "trl>=0.15", "peft", "accelerate", "bitsandbytes"])
16
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "-q",
17
+ "openenv-core[core]>=0.2.2", "numpy", "matplotlib", "datasets"])
18
+
19
+ # Clone env repo
20
+ REPO_DIR = "/tmp/methanol-apc"
21
+ if not os.path.exists(REPO_DIR):
22
+ os.system(f"git clone https://github.com/Bhavneet1492/openenv-methanol-apc.git {REPO_DIR}")
23
+ sys.path.insert(0, REPO_DIR)
24
+ sys.path.insert(0, f"{REPO_DIR}/methanol_apc_env/server")
25
+ sys.path.insert(0, f"{REPO_DIR}/methanol_apc_env")
26
+
27
+ import numpy as np
28
+ import matplotlib
29
+ matplotlib.use("Agg")
30
+ import matplotlib.pyplot as plt
31
+ import torch
32
+
33
+ print(f"GPU: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU'}")
34
+ vram = torch.cuda.get_device_properties(0).total_memory / 1e9 if torch.cuda.is_available() else 0
35
+ print(f"VRAM: {vram:.1f} GB")
36
+
37
+ # ── Load model ──
38
+ from unsloth import FastLanguageModel
39
+
40
+ if vram >= 30:
41
+ MODEL = "unsloth/Qwen2.5-7B-Instruct-bnb-4bit"
42
+ elif vram >= 10:
43
+ MODEL = "unsloth/Qwen2.5-3B-Instruct-bnb-4bit"
44
+ else:
45
+ MODEL = "unsloth/Qwen2.5-1.5B-Instruct-bnb-4bit"
46
+ print(f"Model: {MODEL}")
47
+
48
+ model, tokenizer = FastLanguageModel.from_pretrained(
49
+ model_name=MODEL, max_seq_length=2048, dtype=None, load_in_4bit=True)
50
+ model = FastLanguageModel.get_peft_model(
51
+ model, r=16, lora_alpha=32,
52
+ target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"],
53
+ lora_dropout=0, bias="none", use_gradient_checkpointing="unsloth", random_state=42)
54
+ print(f"Trainable: {sum(p.numel() for p in model.parameters() if p.requires_grad):,}")
55
+
56
+ # ── Environment ──
57
+ from methanol_apc_env.server.methanol_environment import MethanolAPCEnvironment
58
+ from methanol_apc_env.models import MethanolAPCAction
59
+
60
+ TASKS = ["optimization", "startup", "disturbance_rejection"]
61
+ NUM_STEPS = 150
62
+ NUM_PROMPTS = 200
63
+ PLOT_DIR = "/data" if os.path.isdir("/data") else "./training_plots"
64
+ os.makedirs(PLOT_DIR, exist_ok=True)
65
+
66
+ SYSTEM_PROMPT = """You are an AI controller for a methanol synthesis reactor.
67
+ Given sensor readings, output a JSON control action:
68
+ {"feed_rate_h2": <0-10>, "feed_rate_co": <0-5>, "cooling_water_flow": <0-100>, "compressor_power": <0-100>}
69
+
70
+ RULES: CO + 2H2 -> CH3OH is exothermic. Optimal 240-260C. >300C = SHUTDOWN.
71
+ H2/CO ~ 2.0. Revenue $0.74/kg. Output ONLY the JSON."""
72
+
73
+ def make_env(task="optimization", seed=42):
74
+ env = MethanolAPCEnvironment()
75
+ obs = env.reset(task_name=task, seed=seed)
76
+ return env, obs
77
+
78
+ def obs_to_text(obs):
79
+ return (f"T={obs.temperature:.1f}C P={obs.pressure:.1f}bar "
80
+ f"H2={obs.feed_rate_h2:.2f} CO={obs.feed_rate_co:.2f} ratio={obs.h2_co_ratio:.2f} "
81
+ f"cool={obs.cooling_water_flow:.0f}L/min cat={obs.catalyst_health:.2%} "
82
+ f"rate={obs.reaction_rate:.4f} MeOH={obs.methanol_produced:.1f}kg "
83
+ f"profit=${obs.cumulative_profit:.2f} step={obs.step_number}/{obs.max_steps}")
84
+
85
+ def _replay(env, seed, nw):
86
+ for step in range(nw):
87
+ rng = random.Random(seed * 1000 + step)
88
+ env.step(MethanolAPCAction(
89
+ feed_rate_h2=rng.uniform(1,8), feed_rate_co=rng.uniform(0.5,4),
90
+ cooling_water_flow=rng.uniform(10,80), compressor_power=rng.uniform(30,80)))
91
+
92
+ def reward_fn(completions, task=None, seed=None, num_warmup=None, **kwargs):
93
+ rewards = []
94
+ for i, c in enumerate(completions):
95
+ t = task[i] if task else random.choice(TASKS)
96
+ s = int(seed[i]) if seed else 42
97
+ nw = int(num_warmup[i]) if num_warmup else 0
98
+ try:
99
+ text = c if isinstance(c, str) else str(c)
100
+ text = text.strip()
101
+ if '```' in text: text = text.split('```')[1].replace('json','',1).strip()
102
+ start, end = text.find('{'), text.rfind('}') + 1
103
+ if start >= 0 and end > start: text = text[start:end]
104
+ action = MethanolAPCAction(**json.loads(text))
105
+ env, _ = make_env(task=t, seed=s)
106
+ if nw > 0: _replay(env, s, nw)
107
+ obs = env.step(action)
108
+ rewards.append(max(0.01, min(0.99, float(obs.reward))) * 0.9 + 0.1)
109
+ except Exception:
110
+ rewards.append(0.01)
111
+ return rewards
112
+
113
+ # ── Build dataset ──
114
+ from datasets import Dataset
115
+
116
+ prompts = []
117
+ for i in range(NUM_PROMPTS):
118
+ task = TASKS[i % len(TASKS)]
119
+ seed = i
120
+ nw = random.randint(0, 5)
121
+ env, obs = make_env(task=task, seed=seed)
122
+ actual = 0
123
+ for step in range(nw):
124
+ rng = random.Random(seed * 1000 + step)
125
+ obs = env.step(MethanolAPCAction(
126
+ feed_rate_h2=rng.uniform(1,8), feed_rate_co=rng.uniform(0.5,4),
127
+ cooling_water_flow=rng.uniform(10,80), compressor_power=rng.uniform(30,80)))
128
+ actual += 1
129
+ if obs.done: break
130
+ msgs = [{"role":"system","content":SYSTEM_PROMPT},
131
+ {"role":"user","content":f"Sensors:\n{obs_to_text(obs)}\n\nAction JSON:"}]
132
+ prompt = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
133
+ prompts.append({"prompt": prompt, "task": task, "seed": seed, "num_warmup": actual})
134
+ dataset = Dataset.from_list(prompts)
135
+ print(f"Dataset: {len(dataset)} prompts")
136
+
137
+ # ── Train ──
138
+ from trl import GRPOConfig, GRPOTrainer
139
+ from transformers import TrainerCallback
140
+
141
+ class Logger(TrainerCallback):
142
+ def __init__(self): self.rewards = []
143
+ def on_log(self, args, state, control, logs=None, **kwargs):
144
+ if not logs: return
145
+ s = state.global_step
146
+ loss = logs.get('loss')
147
+ rew = logs.get('reward', logs.get('rewards/mean', logs.get('reward/mean')))
148
+ parts = [f'[Step {s:>4d}]']
149
+ if loss is not None: parts.append(f'loss={loss:.4f}')
150
+ if rew is not None: parts.append(f'reward={rew:.4f}'); self.rewards.append({'step':s,'reward':rew})
151
+ print(' ' + ' '.join(parts))
152
+
153
+ logger = Logger()
154
+ args = GRPOConfig(
155
+ output_dir='./grpo_output', max_steps=NUM_STEPS,
156
+ per_device_train_batch_size=2, gradient_accumulation_steps=4,
157
+ learning_rate=5e-6, max_completion_length=128,
158
+ num_generations=4, temperature=0.7,
159
+ logging_steps=5, save_steps=50, report_to='none',
160
+ fp16=not torch.cuda.is_bf16_supported(),
161
+ bf16=torch.cuda.is_bf16_supported(), seed=42)
162
+
163
+ trainer = GRPOTrainer(model=model, args=args, train_dataset=dataset,
164
+ reward_funcs=reward_fn, processing_class=tokenizer, callbacks=[logger])
165
+
166
+ print(f"\nTraining: {NUM_STEPS} steps...")
167
+ t0 = time.time()
168
+ result = trainer.train()
169
+ elapsed = time.time() - t0
170
+ print(f"\nDone in {elapsed/60:.1f}min. Loss: {result.training_loss:.4f}")
171
+
172
+ # ── Plots ──
173
+ h = trainer.state.log_history
174
+ steps = [e['step'] for e in h if 'loss' in e]
175
+ losses = [e['loss'] for e in h if 'loss' in e]
176
+
177
+ fig, ax = plt.subplots(figsize=(10,5))
178
+ ax.plot(steps, losses, '#3b82f6', lw=2, label='Loss')
179
+ if len(steps) > 10:
180
+ w = max(3, len(losses)//10)
181
+ sm = np.convolve(losses, np.ones(w)/w, 'valid')
182
+ ax.plot(steps[w-1:], sm, '#1e40af', lw=2, ls='--', label='Smoothed')
183
+ ax.set(xlabel='Step', ylabel='Loss', title=f'GRPO Loss β€” {MODEL.split("/")[-1]}')
184
+ ax.legend(); ax.grid(alpha=0.3); fig.tight_layout()
185
+ fig.savefig(f'{PLOT_DIR}/loss_curve.png', dpi=150)
186
+ print(f'Saved {PLOT_DIR}/loss_curve.png')
187
+
188
+ # ── Evaluate ──
189
+ def eval_agent(model, tok, task='optimization', eps=5, steps=15):
190
+ FastLanguageModel.for_inference(model)
191
+ all_r = []
192
+ for ep in range(eps):
193
+ env, obs = make_env(task, ep*100); rs = []
194
+ for _ in range(steps):
195
+ if obs.done: break
196
+ msgs = [{'role':'system','content':SYSTEM_PROMPT},
197
+ {'role':'user','content':f'Sensors:\n{obs_to_text(obs)}\n\nAction JSON:'}]
198
+ p = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
199
+ inp = tok(p, return_tensors='pt').to(model.device)
200
+ with torch.no_grad():
201
+ out = model.generate(**inp, max_new_tokens=150, temperature=0.3,
202
+ do_sample=True, pad_token_id=tok.eos_token_id)
203
+ resp = tok.decode(out[0][inp['input_ids'].shape[1]:], skip_special_tokens=True)
204
+ try:
205
+ t = resp.strip(); s,e = t.find('{'), t.rfind('}')+1
206
+ obs = env.step(MethanolAPCAction(**json.loads(t[s:e])))
207
+ rs.append(float(obs.reward))
208
+ except:
209
+ obs = env.step(MethanolAPCAction(feed_rate_h2=3,feed_rate_co=1.5,
210
+ cooling_water_flow=60,compressor_power=50))
211
+ rs.append(float(obs.reward))
212
+ all_r.append(rs)
213
+ ml = max(len(r) for r in all_r)
214
+ return np.mean([r+[r[-1]]*(ml-len(r)) for r in all_r], axis=0)
215
+
216
+ def eval_baseline(task='optimization', eps=5, steps=15):
217
+ all_r = []
218
+ for ep in range(eps):
219
+ env, obs = make_env(task, ep*100); rs = []
220
+ for _ in range(steps):
221
+ if obs.done: break
222
+ obs = env.step(MethanolAPCAction(feed_rate_h2=random.uniform(1,8),
223
+ feed_rate_co=random.uniform(0.5,4), cooling_water_flow=random.uniform(10,80),
224
+ compressor_power=random.uniform(20,80)))
225
+ rs.append(float(obs.reward))
226
+ all_r.append(rs)
227
+ ml = max(len(r) for r in all_r)
228
+ return np.mean([r+[r[-1]]*(ml-len(r)) for r in all_r], axis=0)
229
+
230
+ print('Evaluating...')
231
+ bl = eval_baseline()
232
+ tr = eval_agent(model, tokenizer)
233
+ imp = np.mean(tr) - np.mean(bl)
234
+ print(f'Baseline: {np.mean(bl):.4f}, Trained: {np.mean(tr):.4f}, Delta: {imp:+.4f}')
235
+
236
+ # Reward curve
237
+ fig, ax = plt.subplots(figsize=(10,5))
238
+ ax.plot(range(len(tr)), tr, '#10b981', lw=2, label=f'Trained ({np.mean(tr):.3f})')
239
+ ax.axhline(np.mean(tr), color='#10b981', ls='--', alpha=0.5)
240
+ ax.set(xlabel='Step', ylabel='Reward', title='Trained Agent Reward')
241
+ ax.legend(); ax.grid(alpha=0.3); fig.tight_layout()
242
+ fig.savefig(f'{PLOT_DIR}/reward_curve.png', dpi=150)
243
+
244
+ # Comparison
245
+ fig, ax = plt.subplots(figsize=(10,5))
246
+ ax.plot(range(len(bl)), bl, '#ef4444', lw=2, alpha=0.8, label=f'Random ({np.mean(bl):.3f})')
247
+ ax.plot(range(len(tr)), tr, '#10b981', lw=2, label=f'GRPO Trained ({np.mean(tr):.3f})')
248
+ ax.fill_between(range(len(bl)), bl, alpha=0.1, color='#ef4444')
249
+ ax.fill_between(range(len(tr)), tr, alpha=0.1, color='#10b981')
250
+ ax.set(xlabel='Step', ylabel='Reward', title='Baseline vs GRPO β€” Methanol APC')
251
+ ax.legend(loc='lower right'); ax.grid(alpha=0.3); fig.tight_layout()
252
+ fig.savefig(f'{PLOT_DIR}/baseline_vs_trained.png', dpi=150)
253
+ print(f'All plots saved to {PLOT_DIR}/')
254
+
255
+ # Save model
256
+ model.save_pretrained(f'{PLOT_DIR}/grpo_methanol_trained')
257
+ tokenizer.save_pretrained(f'{PLOT_DIR}/grpo_methanol_trained')
258
+
259
+ # Summary
260
+ print(f'\n{"="*50}')
261
+ print(f'Model: {MODEL}')
262
+ print(f'Training: {NUM_STEPS} steps in {elapsed/60:.1f} min')
263
+ print(f'Baseline: {np.mean(bl):.4f}')
264
+ print(f'Trained: {np.mean(tr):.4f}')
265
+ print(f'Delta: {imp:+.4f} ({imp/max(np.mean(bl),1e-6)*100:+.1f}%)')
266
+ print(f'{"="*50}')