junaid0600 commited on
Commit
9a30866
Β·
verified Β·
1 Parent(s): 46fabbd

Update training/train_agent.py

Browse files
Files changed (1) hide show
  1. training/train_agent.py +80 -127
training/train_agent.py CHANGED
@@ -13,10 +13,8 @@ FIXES applied:
13
  import os
14
  import re
15
  import json
16
- import warnings
17
  import requests
18
  from datasets import Dataset
19
- from collections import defaultdict
20
 
21
  # ── Try importing Unsloth (GPU only) ─────────────────────────
22
  try:
@@ -35,7 +33,6 @@ ENV_URL = os.getenv("ENV_URL", "https://junaid0600-sql-db-engineer-agent.h
35
  HF_TOKEN = os.getenv("HF_TOKEN", "")
36
  MODEL_NAME = os.getenv("MODEL_NAME", "unsloth/Qwen2.5-7B-Instruct")
37
  OUTPUT_DIR = os.getenv("OUTPUT_DIR", "./sdea-trained")
38
- MAX_STEPS = int(os.getenv("MAX_STEPS", "50"))
39
 
40
  # Valid Round 2 action types β€” model must use one of these
41
  VALID_ACTION_TYPES = {
@@ -45,9 +42,6 @@ VALID_ACTION_TYPES = {
45
  "request_hint", "submit_report",
46
  }
47
 
48
- _last_reward_by_task = {}
49
- _scenario_hits = defaultdict(int)
50
-
51
  SYSTEM_PROMPT = """You are a senior database engineer.
52
  Given a database scenario with slow queries, choose the BEST single action to improve performance.
53
 
@@ -68,22 +62,6 @@ Examples:
68
  {"action_type": "submit_report", "payload": {"summary": "Added composite index on orders(user_id, status). Performance improved from 5.0 to 85.0."}}"""
69
 
70
 
71
- def _configure_warning_filters() -> None:
72
- """
73
- Suppress noisy upstream deprecation warnings that do not affect training
74
- correctness right now. Keep real runtime errors visible.
75
- """
76
- filters = [
77
- r"Passing `generation_config` together with generation-related arguments",
78
- r"Both `max_new_tokens` \(=.+\) and `max_length`\(.+\) seem to have been set",
79
- r"The attention mask API under `transformers\.modeling_attn_mask_utils`",
80
- r"`use_return_dict` is deprecated! Use `return_dict` instead!",
81
- ]
82
- for message in filters:
83
- warnings.filterwarnings("ignore", message=message, category=FutureWarning)
84
- warnings.filterwarnings("ignore", message=message, category=UserWarning)
85
-
86
-
87
  # ─────────────────────────────────────────────
88
  # JSON EXTRACTION (FIX 1 β€” kills PARSE FALLBACK)
89
  # ─────────────────────────────────────────────
@@ -109,78 +87,43 @@ def _extract_json(text: str) -> dict | None:
109
  except json.JSONDecodeError:
110
  pass
111
 
112
- # Try 2: scan for JSON object starts and raw-decode from each "{"
113
- # This handles nested objects/arrays better than regex-only extraction.
114
- decoder = json.JSONDecoder()
115
- brace_positions = [m.start() for m in re.finditer(r"\{", text)]
116
- for pos in brace_positions:
117
- try:
118
- obj, _ = decoder.raw_decode(text[pos:])
119
- if isinstance(obj, dict) and "action_type" in obj:
120
- return obj
121
- except Exception:
122
- continue
123
-
124
- # Try 3: greedy β€” find first { to last }
125
- start = text.find("{")
126
- end = text.rfind("}")
127
- if start != -1 and end != -1 and end > start:
128
- try:
129
- obj = json.loads(text[start:end + 1])
130
- if isinstance(obj, dict) and "action_type" in obj:
131
- return obj
132
- except json.JSONDecodeError:
133
- pass
 
 
 
 
 
 
 
 
 
 
 
134
 
135
  return None
136
 
137
 
138
- def _recover_action_from_text(text: str) -> dict | None:
139
- """
140
- Heuristic fallback when strict JSON parse fails.
141
- Helps GRPO get useful gradient instead of all-invalid outputs.
142
- """
143
- if not text:
144
- return None
145
-
146
- action_match = re.search(
147
- r"(inspect_query|analyze_indexes|create_index|rewrite_query|add_column|drop_index|partition_table|analyze_statistics|request_hint|submit_report)",
148
- text,
149
- flags=re.IGNORECASE,
150
- )
151
- if not action_match:
152
- return None
153
-
154
- action_type = action_match.group(1).lower()
155
- payload = {}
156
-
157
- query_match = re.search(r"\bq\d+\b", text, flags=re.IGNORECASE)
158
- table_match = re.search(
159
- r"\b(users|orders|products|sessions|logs|tickets|events|posts|authors|transactions|accounts|customers|audit_log|workspaces|projects|tasks|comments|attachments|activity_log|notifications|patients|appointments|prescriptions|clinical_notes|players|matches|leaderboards|achievements|shipments|routes|drivers|vehicles|warehouses|tracking)\b",
160
- text,
161
- flags=re.IGNORECASE,
162
- )
163
- cols_match = re.search(r"\[(.*?)\]", text, flags=re.DOTALL)
164
-
165
- if action_type == "inspect_query":
166
- payload["query_id"] = query_match.group(0) if query_match else "q1"
167
- elif action_type in {"analyze_indexes", "partition_table", "analyze_statistics"}:
168
- payload["table"] = table_match.group(1) if table_match else "orders"
169
- elif action_type == "create_index":
170
- payload["table"] = table_match.group(1) if table_match else "orders"
171
- if cols_match:
172
- cols = re.findall(r"[A-Za-z_][A-Za-z0-9_]*", cols_match.group(1))
173
- payload["columns"] = cols[:4] if cols else ["user_id", "status"]
174
- else:
175
- payload["columns"] = ["user_id", "status"]
176
- elif action_type == "submit_report":
177
- payload["summary"] = "Applied index and query optimization recommendations."
178
- else:
179
- payload = {}
180
-
181
- return {"action_type": action_type, "payload": payload}
182
-
183
-
184
  def _is_valid_action(action: dict) -> bool:
185
  """Check action has correct structure before sending to /grader."""
186
  if not isinstance(action, dict):
@@ -194,6 +137,37 @@ def _is_valid_action(action: dict) -> bool:
194
  return True
195
 
196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  # ─────────────────────────────────────────────
198
  # REWARD FUNCTION (FIX 2 + FIX 3)
199
  # ─────────────────────────────────────────────
@@ -219,28 +193,17 @@ def reward_fn(prompts, completions, **kwargs):
219
  raw_task_ids = [raw_task_ids]
220
 
221
  for i, (prompt, completion) in enumerate(zip(prompts, completions)):
222
- if raw_task_ids:
223
- task_id = raw_task_ids[i % len(raw_task_ids)]
224
- else:
225
- # Last-resort fallback should not pin all rewards to one scenario.
226
- task_id = f"fallback_{i}"
227
- _scenario_hits[task_id] += 1
228
 
229
  # ── Extract text from completion ──────────────────────────
230
- if isinstance(completion, list):
231
- # Standard TRL format: [{"role": "assistant", "content": "..."}]
232
- text = completion[0].get("content", "") if completion else ""
233
- elif isinstance(completion, dict):
234
- text = completion.get("content", "")
235
- else:
236
- text = str(completion)
237
 
238
  # ── FIX 1: robust JSON parse ──────────────────────────────
239
  action = _extract_json(text)
240
- recovered = False
241
- if action is None:
242
- action = _recover_action_from_text(text)
243
- recovered = action is not None
244
 
245
  if action is None:
246
  # Complete parse failure β€” 0.001 (not 0.0, avoids GRPO div-by-zero)
@@ -253,10 +216,7 @@ def reward_fn(prompts, completions, **kwargs):
253
  # the right actions, avoiding the all-zero gradient problem.
254
  if not _is_valid_action(action):
255
  # JSON parsed but action_type is wrong/missing
256
- print(
257
- f" [REWARD] scenario={task_id} | action={action.get('action_type', 'unknown')} "
258
- f"| INVALID ACTION STRUCTURE | score=0.05"
259
- )
260
  rewards.append(0.05)
261
  continue
262
 
@@ -270,17 +230,11 @@ def reward_fn(prompts, completions, **kwargs):
270
  resp.raise_for_status()
271
  score = float(resp.json().get("score", 0.001))
272
  score = max(0.001, min(0.999, score))
 
273
  rewards.append(score)
274
- delta_reward = score - _last_reward_by_task.get(task_id, score)
275
- _last_reward_by_task[task_id] = score
276
- parse_tag = "RECOVERED" if recovered else "JSON_OK"
277
- print(
278
- f" [REWARD] scenario={task_id} | action={action['action_type']} | {parse_tag} "
279
- f"| score={score:.3f} | delta_reward={delta_reward:+.3f}"
280
- )
281
 
282
  except requests.exceptions.Timeout:
283
- print(f" [REWARD] scenario={task_id} | grader TIMEOUT | score=0.05")
284
  rewards.append(0.05) # grader timed out β€” give format credit
285
  except Exception as e:
286
  print(f"[reward_fn] grader call failed for {task_id}: {e}")
@@ -377,8 +331,6 @@ def reward_wrapper(prompts, completions, **kwargs):
377
  # ─────────────────────────────────────────────
378
 
379
  def train():
380
- _configure_warning_filters()
381
-
382
  if not UNSLOTH_AVAILABLE:
383
  print("Cannot train β€” Unsloth not installed")
384
  print("Run: pip install 'unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git' trl transformers datasets accelerate")
@@ -416,18 +368,20 @@ def train():
416
  )
417
 
418
  # Build dataset
419
- dataset = build_dataset().shuffle(seed=42)
420
 
421
  # GRPO config
 
 
 
 
422
  config = GRPOConfig(
423
  output_dir = OUTPUT_DIR,
424
- # Set explicit optimizer steps so "Total steps" is predictable.
425
- max_steps = MAX_STEPS,
426
- num_train_epochs = 100, # ignored when max_steps is reached first
427
  per_device_train_batch_size = 1, # was 2 β†’ frees memory for 1.5B
428
  gradient_accumulation_steps = 2, # was 8 β†’ was hiding steps, now shows them
429
  learning_rate = 2e-5, # was 5e-5 β†’ lower = more stable for small model
430
- max_completion_length = 512,
431
  num_generations = 4,
432
  logging_steps = 1, # was 10 β†’ see every step
433
  save_steps = 20,
@@ -444,7 +398,6 @@ def train():
444
  )
445
 
446
  print("πŸ‹οΈ Starting GRPO training...")
447
- print(f" Target optimizer steps: {MAX_STEPS}")
448
  print(" Expected reward progression:")
449
  print(" Steps 10: ~0.05-0.15 (model still outputting free text)")
450
  print(" Steps 50: ~0.20-0.35 (learning JSON format)")
 
13
  import os
14
  import re
15
  import json
 
16
  import requests
17
  from datasets import Dataset
 
18
 
19
  # ── Try importing Unsloth (GPU only) ─────────────────────────
20
  try:
 
33
  HF_TOKEN = os.getenv("HF_TOKEN", "")
34
  MODEL_NAME = os.getenv("MODEL_NAME", "unsloth/Qwen2.5-7B-Instruct")
35
  OUTPUT_DIR = os.getenv("OUTPUT_DIR", "./sdea-trained")
 
36
 
37
  # Valid Round 2 action types β€” model must use one of these
38
  VALID_ACTION_TYPES = {
 
42
  "request_hint", "submit_report",
43
  }
44
 
 
 
 
45
  SYSTEM_PROMPT = """You are a senior database engineer.
46
  Given a database scenario with slow queries, choose the BEST single action to improve performance.
47
 
 
62
  {"action_type": "submit_report", "payload": {"summary": "Added composite index on orders(user_id, status). Performance improved from 5.0 to 85.0."}}"""
63
 
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  # ─────────────────────────────────────────────
66
  # JSON EXTRACTION (FIX 1 β€” kills PARSE FALLBACK)
67
  # ─────────────────────────────────────────────
 
87
  except json.JSONDecodeError:
88
  pass
89
 
90
+ # Try 2: balanced-brace scan from every opening '{'
91
+ # This handles nested payload objects/arrays more reliably than regex.
92
+ starts = [idx for idx, ch in enumerate(text) if ch == "{"]
93
+ for start in starts:
94
+ depth = 0
95
+ in_str = False
96
+ escape = False
97
+ for i in range(start, len(text)):
98
+ ch = text[i]
99
+ if in_str:
100
+ if escape:
101
+ escape = False
102
+ elif ch == "\\":
103
+ escape = True
104
+ elif ch == '"':
105
+ in_str = False
106
+ continue
107
+ if ch == '"':
108
+ in_str = True
109
+ continue
110
+ if ch == "{":
111
+ depth += 1
112
+ elif ch == "}":
113
+ depth -= 1
114
+ if depth == 0:
115
+ candidate = text[start:i + 1]
116
+ try:
117
+ obj = json.loads(candidate)
118
+ if isinstance(obj, dict) and "action_type" in obj:
119
+ return obj
120
+ except json.JSONDecodeError:
121
+ pass
122
+ break
123
 
124
  return None
125
 
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  def _is_valid_action(action: dict) -> bool:
128
  """Check action has correct structure before sending to /grader."""
129
  if not isinstance(action, dict):
 
137
  return True
138
 
139
 
140
+ def _completion_to_text(completion) -> str:
141
+ """
142
+ Normalize TRL completion formats into raw text.
143
+ Handles dict/list/string and content blocks emitted by some chat templates.
144
+ """
145
+ if isinstance(completion, str):
146
+ return completion
147
+
148
+ if isinstance(completion, dict):
149
+ content = completion.get("content", "")
150
+ if isinstance(content, str):
151
+ return content
152
+ if isinstance(content, list):
153
+ chunks = []
154
+ for block in content:
155
+ if isinstance(block, dict):
156
+ chunks.append(str(block.get("text", "")))
157
+ else:
158
+ chunks.append(str(block))
159
+ return "".join(chunks)
160
+ return str(content)
161
+
162
+ if isinstance(completion, list):
163
+ # Common shape: [{"role":"assistant","content":"..."}]
164
+ if not completion:
165
+ return ""
166
+ return "".join(_completion_to_text(item) for item in completion)
167
+
168
+ return str(completion)
169
+
170
+
171
  # ─────────────────────────────────────────────
172
  # REWARD FUNCTION (FIX 2 + FIX 3)
173
  # ─────────────────────────────────────────────
 
193
  raw_task_ids = [raw_task_ids]
194
 
195
  for i, (prompt, completion) in enumerate(zip(prompts, completions)):
196
+ task_id = (
197
+ raw_task_ids[i]
198
+ if i < len(raw_task_ids)
199
+ else "easy_s001"
200
+ )
 
201
 
202
  # ── Extract text from completion ──────────────────────────
203
+ text = _completion_to_text(completion)
 
 
 
 
 
 
204
 
205
  # ── FIX 1: robust JSON parse ──────────────────────────────
206
  action = _extract_json(text)
 
 
 
 
207
 
208
  if action is None:
209
  # Complete parse failure β€” 0.001 (not 0.0, avoids GRPO div-by-zero)
 
216
  # the right actions, avoiding the all-zero gradient problem.
217
  if not _is_valid_action(action):
218
  # JSON parsed but action_type is wrong/missing
219
+ print(f" [REWARD] scenario={task_id} | INVALID ACTION | score=0.05")
 
 
 
220
  rewards.append(0.05)
221
  continue
222
 
 
230
  resp.raise_for_status()
231
  score = float(resp.json().get("score", 0.001))
232
  score = max(0.001, min(0.999, score))
233
+ print(f" [REWARD] scenario={task_id} | action={action['action_type']} | score={score:.3f}")
234
  rewards.append(score)
 
 
 
 
 
 
 
235
 
236
  except requests.exceptions.Timeout:
237
+ print(f" [REWARD] scenario={task_id} | GRADER TIMEOUT | score=0.05")
238
  rewards.append(0.05) # grader timed out β€” give format credit
239
  except Exception as e:
240
  print(f"[reward_fn] grader call failed for {task_id}: {e}")
 
331
  # ─────────────────────────────────────────────
332
 
333
  def train():
 
 
334
  if not UNSLOTH_AVAILABLE:
335
  print("Cannot train β€” Unsloth not installed")
336
  print("Run: pip install 'unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git' trl transformers datasets accelerate")
 
368
  )
369
 
370
  # Build dataset
371
+ dataset = build_dataset()
372
 
373
  # GRPO config
374
+ # Avoid generation warnings from simultaneously using max_length and max_new_tokens.
375
+ if hasattr(model, "generation_config"):
376
+ model.generation_config.max_length = None
377
+
378
  config = GRPOConfig(
379
  output_dir = OUTPUT_DIR,
380
+ num_train_epochs = 100, # was 3 β†’ now 100 β†’ gives ~120 steps
 
 
381
  per_device_train_batch_size = 1, # was 2 β†’ frees memory for 1.5B
382
  gradient_accumulation_steps = 2, # was 8 β†’ was hiding steps, now shows them
383
  learning_rate = 2e-5, # was 5e-5 β†’ lower = more stable for small model
384
+ max_completion_length = 120,
385
  num_generations = 4,
386
  logging_steps = 1, # was 10 β†’ see every step
387
  save_steps = 20,
 
398
  )
399
 
400
  print("πŸ‹οΈ Starting GRPO training...")
 
401
  print(" Expected reward progression:")
402
  print(" Steps 10: ~0.05-0.15 (model still outputting free text)")
403
  print(" Steps 50: ~0.20-0.35 (learning JSON format)")