manitocross commited on
Commit
5139db1
·
verified ·
1 Parent(s): 3c3f108

Upload full GRPO training script

Browse files
Files changed (1) hide show
  1. train_floorplan_grpo.py +281 -0
train_floorplan_grpo.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FloorplanVLM GRPO Training (Stage 2) - Run after SFT
3
+
4
+ Loads the SFT model and applies geometric reward-based RL.
5
+ Reward: R = 0.1·R_val + 0.5·R_ext + α·0.4·R_int (FloorplanVLM Eq. 9)
6
+
7
+ Usage:
8
+ pip install shapely # + same deps as SFT script
9
+ python train_floorplan_grpo.py
10
+
11
+ Requires: SFT model already pushed to HUB (default: manitocross/floorplan-vlm-sft)
12
+ """
13
+
14
+ import os, json, re, math, torch, numpy as np
15
+ from PIL import Image, ImageDraw
16
+ from datasets import Dataset
17
+ from transformers import AutoProcessor, TrainerCallback
18
+ from trl import GRPOTrainer, GRPOConfig
19
+ from peft import LoraConfig
20
+ from shapely.geometry import Polygon, LineString
21
+ from shapely.ops import unary_union
22
+
23
+ # ══════════════════════════════════════════════════════════════════════════════
24
+ # CONFIGURATION
25
+ # ══════════════════════════════════════════════════════════════════════════════
26
+ SFT_MODEL_ID = "manitocross/floorplan-vlm-sft" # your SFT model from Stage 1
27
+ HUB_MODEL_ID = "manitocross/floorplan-vlm-grpo"
28
+ OUTPUT_DIR = "./floorplan-vlm-grpo"
29
+
30
+ # Uses same CubiCasa5K data directory as SFT script
31
+ DATA_DIR = "./cubicasa_data"
32
+
33
+ NUM_EPOCHS = 1
34
+ BATCH_SIZE = 1
35
+ GRAD_ACCUM = 4
36
+ LEARNING_RATE = 1e-6
37
+ NUM_GENERATIONS = 4 # G: completions per prompt
38
+ MAX_COMPLETION_LENGTH = 4096
39
+ KL_COEF = 0.01
40
+ PUSH_TO_HUB = True
41
+ # ══════════════════════════════════════════════════════════════════════════════
42
+
43
+ SYSTEM_PROMPT = "You are a floor plan vectorization expert. Extract wall, door, window geometry from floor plan images into structured JSON. Output ONLY valid JSON."
44
+ USER_PROMPT = "Vectorize this floor plan into structured JSON with all walls, doors, windows, and rooms."
45
+
46
+
47
+ # ── Geometric Helpers ────────────────────────────────────────────────────────
48
+
49
+ def extract_json(text):
50
+ if isinstance(text, list):
51
+ text = text[0].get("content", "") if text else ""
52
+ text = text.strip()
53
+ try: return json.loads(text)
54
+ except: pass
55
+ m = re.search(r'\{[\s\S]*\}', text)
56
+ if m:
57
+ try: return json.loads(m.group())
58
+ except: pass
59
+ return None
60
+
61
+
62
+ def walls_to_polygon(walls):
63
+ if not walls or len(walls) < 3: return None
64
+ try:
65
+ polys = []
66
+ for w in walls:
67
+ s, e = w.get('start',[0,0]), w.get('end',[0,0])
68
+ t = max(w.get('thickness',10), 1)
69
+ polys.append(LineString([s, e]).buffer(t/2, cap_style=2))
70
+ combined = unary_union(polys)
71
+ return combined.convex_hull if not combined.is_empty else None
72
+ except: return None
73
+
74
+
75
+ def poly_iou(p1, p2):
76
+ if p1 is None or p2 is None: return 0.0
77
+ try:
78
+ if not p1.is_valid: p1 = p1.buffer(0)
79
+ if not p2.is_valid: p2 = p2.buffer(0)
80
+ inter = p1.intersection(p2).area
81
+ union = p1.union(p2).area
82
+ return inter / union if union > 0 else 0.0
83
+ except: return 0.0
84
+
85
+
86
+ # ── Reward Function ──────────────────────────────────────────────────────────
87
+
88
+ def floorplan_reward(completions, **kwargs):
89
+ """Combined: 0.1·R_val + 0.5·R_ext + α·0.4·R_int"""
90
+ gt_jsons = kwargs.get("json_gt", [])
91
+ rewards = []
92
+
93
+ for c, gt_str in zip(completions, gt_jsons):
94
+ text = c[0]["content"] if isinstance(c, list) else c
95
+ pred = extract_json(text)
96
+ if pred is None:
97
+ rewards.append(0.0); continue
98
+ try:
99
+ gt = json.loads(gt_str) if isinstance(gt_str, str) else gt_str
100
+ except:
101
+ rewards.append(0.0); continue
102
+
103
+ # R_val
104
+ r_val = 0.0
105
+ has_walls = "walls" in pred and isinstance(pred["walls"], list) and len(pred["walls"]) > 0
106
+ if has_walls:
107
+ valid = sum(1 for w in pred["walls"]
108
+ if all(k in w for k in ["id","start","end","thickness"])
109
+ and isinstance(w.get("start"), list) and len(w.get("start",[])) == 2)
110
+ r_val = 0.3 + 0.5 * (valid / max(len(pred["walls"]), 1))
111
+ if "rooms" in pred and isinstance(pred["rooms"], list):
112
+ wids = {w.get("id") for w in pred["walls"]}
113
+ vr = sum(1 for r in pred["rooms"]
114
+ if "label" in r and "walls" in r
115
+ and all(wid in wids for wid in r.get("walls",[])))
116
+ r_val += 0.2 * (vr / max(len(pred["rooms"]), 1))
117
+
118
+ # R_ext
119
+ pred_poly = walls_to_polygon(pred.get("walls", []))
120
+ gt_poly = walls_to_polygon(gt.get("walls", []))
121
+ r_ext = poly_iou(pred_poly, gt_poly)
122
+
123
+ # Alpha gating (FloorplanVLM Eq. 8)
124
+ if r_ext < 0.3: alpha = 0.1
125
+ elif r_ext < 0.7: alpha = 0.1 + 0.9 * (r_ext - 0.3) / 0.4
126
+ else: alpha = 1.0
127
+
128
+ # R_int (room label overlap)
129
+ r_int = 0.0
130
+ pred_rooms = pred.get("rooms", [])
131
+ gt_rooms = gt.get("rooms", [])
132
+ if pred_rooms and gt_rooms:
133
+ pl = set(r.get("label","") for r in pred_rooms)
134
+ gl = set(r.get("label","") for r in gt_rooms)
135
+ overlap = len(pl & gl)
136
+ total = len(pl | gl)
137
+ r_int = overlap / total if total > 0 else 0.0
138
+
139
+ total = 0.1 * min(r_val, 1.0) + 0.5 * r_ext + alpha * 0.4 * r_int
140
+ rewards.append(float(total))
141
+
142
+ return rewards
143
+
144
+
145
+ # ── Dataset (reuses SFT data dir) ───────────────────────────────────────────
146
+ # You'll need to adapt this to load your data (same CubiCasa5K directory).
147
+ # For GRPO format: prompt-only (no completion), plus metadata for reward.
148
+
149
+ def build_grpo_dataset(data_dir, max_samples=100):
150
+ """Build GRPO dataset — loads pre-converted JSON annotations."""
151
+ # Look for the annotation file from SFT stage
152
+ ann_path = os.path.join(data_dir, "annotations.json")
153
+ if not os.path.exists(ann_path):
154
+ print(f" No pre-converted annotations at {ann_path}")
155
+ print(f" Run train_floorplan_vlm.py (SFT) first to generate data.")
156
+ print(f" Creating synthetic GRPO dataset as fallback...")
157
+ return create_synthetic_grpo(max_samples or 20)
158
+
159
+ with open(ann_path) as f:
160
+ annotations = json.load(f)
161
+
162
+ if max_samples:
163
+ annotations = annotations[:max_samples]
164
+
165
+ records = []
166
+ for ann in annotations:
167
+ img_path = ann.get("image_path")
168
+ if not img_path or not os.path.exists(img_path):
169
+ continue
170
+ img = Image.open(img_path).convert("RGB")
171
+ records.append({
172
+ "prompt": [
173
+ {"role":"system","content":[{"type":"text","text":SYSTEM_PROMPT}]},
174
+ {"role":"user","content":[{"type":"image"},{"type":"text","text":USER_PROMPT}]},
175
+ ],
176
+ "images": [img],
177
+ "json_gt": ann["json_annotation"],
178
+ })
179
+
180
+ print(f" GRPO dataset: {len(records)} samples")
181
+ return Dataset.from_list(records)
182
+
183
+
184
+ def create_synthetic_grpo(n=20):
185
+ records = []
186
+ for i in range(n):
187
+ size = 256
188
+ img = Image.new('RGB', (size,size), 'white')
189
+ d = ImageDraw.Draw(img)
190
+ m = 30+i*3; wt=6; s=1024.0/size; mid=size//2+i*2
191
+ d.rectangle([m,m,size-m,size-m], outline='black', width=wt)
192
+ d.line([(m,mid),(size-m,mid)], fill='black', width=wt)
193
+
194
+ jd = {"walls":[
195
+ {"id":"wall_1","start":[round(m*s),round(m*s)],"end":[round((size-m)*s),round(m*s)],"thickness":round(wt*s),"curvature":0,"openings":[]},
196
+ {"id":"wall_2","start":[round((size-m)*s),round(m*s)],"end":[round((size-m)*s),round((size-m)*s)],"thickness":round(wt*s),"curvature":0,"openings":[]},
197
+ {"id":"wall_3","start":[round((size-m)*s),round((size-m)*s)],"end":[round(m*s),round((size-m)*s)],"thickness":round(wt*s),"curvature":0,"openings":[]},
198
+ {"id":"wall_4","start":[round(m*s),round((size-m)*s)],"end":[round(m*s),round(m*s)],"thickness":round(wt*s),"curvature":0,"openings":[]},
199
+ {"id":"wall_5","start":[round(m*s),round(mid*s)],"end":[round((size-m)*s),round(mid*s)],"thickness":round(wt*s),"curvature":0,"openings":[]},
200
+ ],"rooms":[
201
+ {"label":"bedroom","walls":["wall_1","wall_2","wall_5","wall_4"]},
202
+ {"label":"living_room","walls":["wall_5","wall_2","wall_3","wall_4"]},
203
+ ]}
204
+ records.append({
205
+ "prompt":[
206
+ {"role":"system","content":[{"type":"text","text":SYSTEM_PROMPT}]},
207
+ {"role":"user","content":[{"type":"image"},{"type":"text","text":USER_PROMPT}]},
208
+ ],
209
+ "images":[img],
210
+ "json_gt": json.dumps(jd, separators=(',',':')),
211
+ })
212
+ return Dataset.from_list(records)
213
+
214
+
215
+ # ── Main ─────────────────────────────────────────────────────────────────────
216
+ def main():
217
+ use_gpu = torch.cuda.is_available()
218
+ print("="*64)
219
+ print(f" FloorplanVLM GRPO Training ({'GPU' if use_gpu else 'CPU'})")
220
+ print(f" SFT Model : {SFT_MODEL_ID}")
221
+ print(f" Output : {HUB_MODEL_ID}")
222
+ print(f" Generations: {NUM_GENERATIONS}, KL: {KL_COEF}")
223
+ print("="*64)
224
+
225
+ dataset = build_grpo_dataset(DATA_DIR)
226
+
227
+ peft_config = LoraConfig(
228
+ r=16, lora_alpha=32,
229
+ target_modules=["q_proj","k_proj","v_proj","o_proj","gate_proj","up_proj","down_proj"],
230
+ lora_dropout=0.05, bias="none", task_type="CAUSAL_LM",
231
+ )
232
+
233
+ grpo_config = GRPOConfig(
234
+ output_dir=OUTPUT_DIR,
235
+ num_train_epochs=NUM_EPOCHS,
236
+ per_device_train_batch_size=BATCH_SIZE,
237
+ gradient_accumulation_steps=GRAD_ACCUM,
238
+ learning_rate=LEARNING_RATE,
239
+ bf16=use_gpu, fp16=False,
240
+ gradient_checkpointing=True,
241
+ logging_steps=5, logging_first_step=True,
242
+ logging_strategy="steps", disable_tqdm=True,
243
+ save_steps=200, save_total_limit=2,
244
+ num_generations=NUM_GENERATIONS,
245
+ max_prompt_length=512,
246
+ max_completion_length=MAX_COMPLETION_LENGTH,
247
+ scale_rewards=True,
248
+ beta=KL_COEF,
249
+ temperature=0.7,
250
+ push_to_hub=PUSH_TO_HUB,
251
+ hub_model_id=HUB_MODEL_ID if PUSH_TO_HUB else None,
252
+ report_to="none",
253
+ )
254
+
255
+ trainer = GRPOTrainer(
256
+ model=SFT_MODEL_ID,
257
+ reward_funcs=[floorplan_reward],
258
+ args=grpo_config,
259
+ train_dataset=dataset,
260
+ peft_config=peft_config,
261
+ )
262
+
263
+ print("\nStarting GRPO training...")
264
+ trainer.train()
265
+
266
+ trainer.save_model(OUTPUT_DIR)
267
+ if PUSH_TO_HUB:
268
+ try:
269
+ trainer.push_to_hub()
270
+ print(f"\n✅ Model: https://huggingface.co/{HUB_MODEL_ID}")
271
+ except Exception as e:
272
+ print(f"Push failed: {e}")
273
+ from huggingface_hub import HfApi
274
+ HfApi().create_repo(HUB_MODEL_ID, exist_ok=True)
275
+ HfApi().upload_folder(folder_path=OUTPUT_DIR, repo_id=HUB_MODEL_ID)
276
+
277
+ print(f"\n✅ Done! Local: {OUTPUT_DIR}/")
278
+
279
+
280
+ if __name__ == "__main__":
281
+ main()