hugsbun commited on
Commit
5bbf4f7
·
1 Parent(s): 506be14

modified: inference.py

Browse files
Files changed (2) hide show
  1. inference.py +106 -76
  2. openenv.yaml +36 -0
inference.py CHANGED
@@ -51,18 +51,29 @@ logger = logging.getLogger(__name__)
51
 
52
  # ── Configuration ───────────────────────────────────────────────────────────────
53
 
54
- CONFIG = {
55
- "env_url": os.getenv("ENV_URL", "http://localhost:7860"),
56
- "api_base_url": os.getenv("API_BASE_URL", "https://router.huggingface.co/v1"),
57
- "model_name": os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct"),
58
- "api_key": os.getenv("API_KEY") or os.getenv("HF_TOKEN"),
59
- "task": os.getenv("TASK", "task1"),
60
- "number_of_runs": int(os.getenv("NUMBER_OF_RUNS", "1")),
61
- "max_steps_per_run": int(os.getenv("MAX_STEPS", "10")),
62
- "temperature": float(os.getenv("TEMPERATURE", "0.0")),
63
- "max_tokens": int(os.getenv("MAX_TOKENS", "2048")),
64
- "request_delay_ms": int(os.getenv("REQUEST_DELAY_MS", "500")),
65
- }
 
 
 
 
 
 
 
 
 
 
 
66
 
67
 
68
  def _validate_config(config: Dict[str, Any]) -> None:
@@ -76,11 +87,12 @@ def _validate_config(config: Dict[str, Any]) -> None:
76
 
77
  # ── LLM client (OpenAI SDK → HuggingFace router) ────────────────────────────────
78
 
79
- def _init_client(config: Dict[str, Any]) -> OpenAI:
80
  """OpenAI client pointed at the HuggingFace OpenAI-compatible endpoint."""
 
81
  return OpenAI(
82
- api_key=config["api_key"],
83
- base_url=config["api_base_url"],
84
  )
85
 
86
 
@@ -136,7 +148,7 @@ def _log_step(step, tool_name, tool_args, reward, done, error=None):
136
  action_str = f"{tool_name}({args_str})"
137
  else:
138
  action_str = f"{tool_name}()"
139
- print(f"[STEP] step={step} action={action_str} reward={reward:.2f} done={str(done).lower()} error={error or 'null'}")
140
 
141
 
142
  def _parse_file_list(logs: str) -> List[str]:
@@ -195,7 +207,7 @@ async def execute_run(
195
  task = config["task"]
196
  model = config["model_name"]
197
 
198
- print(f"[START] task={task} env=debug-env model={model}")
199
 
200
  rewards: List[float] = []
201
  tools_used: List[str] = []
@@ -276,7 +288,7 @@ async def execute_run(
276
 
277
  try:
278
  response = client.chat.completions.create(
279
- model=model,
280
  messages=[{"role": "user", "content": prompt}],
281
  temperature=config["temperature"],
282
  max_tokens=config["max_tokens"],
@@ -297,13 +309,20 @@ async def execute_run(
297
  reward, done = res.get("reward", 0.0), res.get("done", False)
298
  _record("edit_file", {"path": fname}, reward, done)
299
 
 
 
 
 
 
 
300
  elapsed_ms = int((datetime.now(timezone.utc) - start_ts).total_seconds() * 1000)
301
  final_reward = rewards[-1] if rewards else 0.0
302
  rewards_str = ",".join(f"{r:.2f}" for r in rewards)
303
 
304
  print(
305
  f"[END] success={str(success).lower()} steps={global_step} "
306
- f"score={final_reward:.2f} rewards={rewards_str}"
 
307
  )
308
 
309
  return {
@@ -370,7 +389,7 @@ def _save_results(all_runs: List[Dict], config: Dict, out_file: str) -> None:
370
 
371
  async def main(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
372
  if config is None:
373
- config = CONFIG
374
 
375
  try:
376
  _validate_config(config)
@@ -378,63 +397,74 @@ async def main(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
378
  logger.error(f"Configuration error: {e}")
379
  sys.exit(1)
380
 
381
- task = config["task"]
 
382
  n_runs = config["number_of_runs"]
383
-
384
- logger.info("=" * 70)
385
- logger.info("DEBUG-ENV BENCHMARK")
386
- logger.info(f"task={task} model={config['model_name']} runs={n_runs} max_steps={config['max_steps_per_run']}")
387
- logger.info(f"endpoint={config['api_base_url']}")
388
- logger.info("=" * 70)
389
-
390
- client = _init_client(config)
391
- all_runs: List[Dict[str, Any]] = []
392
- ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
393
- out_file = f"results_{task}_{ts}.json"
394
-
395
- for run_number in range(1, n_runs + 1):
396
- try:
397
- result = await execute_run(run_number, client, config)
398
- all_runs.append(result)
399
- except Exception as e:
400
- logger.error(f"Run {run_number} failed: {e}", exc_info=True)
401
- all_runs.append({
402
- "run_number": run_number,
403
- "success": False,
404
- "final_reward": 0.0,
405
- "rewards": [],
406
- "steps": [],
407
- "tools_used": [],
408
- "elapsed_ms": 0,
409
- "error": str(e),
410
- })
411
-
412
- # Save after every run so partial results are never lost
413
- _save_results(all_runs, config, out_file)
414
- logger.info(f"Results saved → {out_file} (run {run_number}/{n_runs})")
415
-
416
- stats = calculate_statistics(all_runs)
417
-
418
- print()
419
- print("=" * 70)
420
- print("BENCHMARK SUMMARY")
421
- print("=" * 70)
422
- print(f"Task: {task}")
423
- print(f"Model: {config['model_name']}")
424
- print(f"Runs: {stats['total_runs']}")
425
- print(f"Success rate: {stats['success_rate']:.1%} ({stats['successful_runs']}/{stats['total_runs']})")
426
- for k in range(1, n_runs + 1):
427
- key = f"pass@{k}"
428
- if key in stats:
429
- print(f"{key:15} {stats[key]:.1%}")
430
- print(f"Avg steps: {stats['avg_steps_per_run']}")
431
- print(f"Avg reward: {stats['avg_final_reward']:.4f}")
432
- print(f"Mean time: {stats['mean_elapsed_ms']:.0f} ms")
433
- print(f"Tool usage: {stats['tool_usage']}")
434
- print(f"Results file: {out_file}")
435
- print("=" * 70)
436
-
437
- return {"benchmark_config": config, "runs": all_runs, "statistics": stats}
 
 
 
 
 
 
 
 
 
 
438
 
439
 
440
  if __name__ == "__main__":
 
51
 
52
  # ── Configuration ───────────────────────────────────────────────────────────────
53
 
54
+ def _ensure_env_vars():
55
+ """Ensure environment variables exist so os.environ[...] doesn't raise KeyError locally."""
56
+ if "API_BASE_URL" not in os.environ:
57
+ os.environ["API_BASE_URL"] = "https://router.huggingface.co/v1"
58
+ if "MODEL_NAME" not in os.environ:
59
+ os.environ["MODEL_NAME"] = "Qwen/Qwen2.5-72B-Instruct"
60
+ if "API_KEY" not in os.environ:
61
+ os.environ["API_KEY"] = os.environ.get("HF_TOKEN", "dummy_key_for_local_testing")
62
+
63
+ def get_config() -> Dict[str, Any]:
64
+ _ensure_env_vars()
65
+ return {
66
+ "env_url": os.getenv("ENV_URL", "http://localhost:7860"),
67
+ "api_base_url": os.environ["API_BASE_URL"],
68
+ "model_name": os.environ["MODEL_NAME"],
69
+ "api_key": os.environ["API_KEY"],
70
+ "task": os.getenv("TASK", "task1"),
71
+ "number_of_runs": int(os.getenv("NUMBER_OF_RUNS", "1")),
72
+ "max_steps_per_run": int(os.getenv("MAX_STEPS", "10")),
73
+ "temperature": float(os.getenv("TEMPERATURE", "0.0")),
74
+ "max_tokens": int(os.getenv("MAX_TOKENS", "2048")),
75
+ "request_delay_ms": int(os.getenv("REQUEST_DELAY_MS", "500")),
76
+ }
77
 
78
 
79
  def _validate_config(config: Dict[str, Any]) -> None:
 
87
 
88
  # ── LLM client (OpenAI SDK → HuggingFace router) ────────────────────────────────
89
 
90
+ def _init_client() -> OpenAI:
91
  """OpenAI client pointed at the HuggingFace OpenAI-compatible endpoint."""
92
+ _ensure_env_vars()
93
  return OpenAI(
94
+ base_url=os.environ["API_BASE_URL"],
95
+ api_key=os.environ["API_KEY"],
96
  )
97
 
98
 
 
148
  action_str = f"{tool_name}({args_str})"
149
  else:
150
  action_str = f"{tool_name}()"
151
+ print(f"[STEP] step={step} action={action_str} reward={reward:.2f} done={str(done).lower()} error={error or 'null'}", flush=True)
152
 
153
 
154
  def _parse_file_list(logs: str) -> List[str]:
 
207
  task = config["task"]
208
  model = config["model_name"]
209
 
210
+ print(f"[START] task={task} env=debug-env model={model}", flush=True)
211
 
212
  rewards: List[float] = []
213
  tools_used: List[str] = []
 
288
 
289
  try:
290
  response = client.chat.completions.create(
291
+ model=os.environ["MODEL_NAME"],
292
  messages=[{"role": "user", "content": prompt}],
293
  temperature=config["temperature"],
294
  max_tokens=config["max_tokens"],
 
309
  reward, done = res.get("reward", 0.0), res.get("done", False)
310
  _record("edit_file", {"path": fname}, reward, done)
311
 
312
+ # ── Remove Generated Solution ──────────────────────────────────────────────
313
+ for fname in files:
314
+ original = file_contents.get(fname)
315
+ if original:
316
+ await env_step(env_url, "edit_file", {"path": fname, "content": original}, delay_ms=0)
317
+
318
  elapsed_ms = int((datetime.now(timezone.utc) - start_ts).total_seconds() * 1000)
319
  final_reward = rewards[-1] if rewards else 0.0
320
  rewards_str = ",".join(f"{r:.2f}" for r in rewards)
321
 
322
  print(
323
  f"[END] success={str(success).lower()} steps={global_step} "
324
+ f"score={final_reward:.2f} rewards={rewards_str}",
325
+ flush=True
326
  )
327
 
328
  return {
 
389
 
390
  async def main(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
391
  if config is None:
392
+ config = get_config()
393
 
394
  try:
395
  _validate_config(config)
 
397
  logger.error(f"Configuration error: {e}")
398
  sys.exit(1)
399
 
400
+ tasks_input = config["task"].split(",") if "," in config["task"] else [config["task"]]
401
+ tasks = [f"task{i}" for i in range(1, 10)] if "all" in tasks_input else tasks_input
402
  n_runs = config["number_of_runs"]
403
+ client = _init_client()
404
+
405
+ all_tasks_results = {}
406
+
407
+ for task in tasks:
408
+ config["task"] = task
409
+ logger.info("=" * 70)
410
+ logger.info("DEBUG-ENV BENCHMARK")
411
+ logger.info(f"task={task} model={config['model_name']} runs={n_runs} max_steps={config['max_steps_per_run']}")
412
+ logger.info(f"endpoint={config['api_base_url']}")
413
+ logger.info("=" * 70)
414
+
415
+ all_runs: List[Dict[str, Any]] = []
416
+ ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
417
+ out_file = f"results_{task}_{ts}.json"
418
+
419
+ for run_number in range(1, n_runs + 1):
420
+ try:
421
+ result = await execute_run(run_number, client, config)
422
+ all_runs.append(result)
423
+ except Exception as e:
424
+ logger.error(f"Run {run_number} failed: {e}", exc_info=True)
425
+ all_runs.append({
426
+ "run_number": run_number,
427
+ "success": False,
428
+ "final_reward": 0.0,
429
+ "rewards": [],
430
+ "steps": [],
431
+ "tools_used": [],
432
+ "elapsed_ms": 0,
433
+ "error": str(e),
434
+ })
435
+
436
+ # Save after every run so partial results are never lost
437
+ _save_results(all_runs, config, out_file)
438
+ logger.info(f"Results saved → {out_file} (run {run_number}/{n_runs})")
439
+
440
+ if all_runs[-1]["success"]:
441
+ logger.info(f"Task {task} solved successfully on run {run_number}. Moving to next task.")
442
+ break
443
+
444
+ stats = calculate_statistics(all_runs)
445
+
446
+ print()
447
+ print("=" * 70)
448
+ print("BENCHMARK SUMMARY")
449
+ print("=" * 70)
450
+ print(f"Task: {task}")
451
+ print(f"Model: {config['model_name']}")
452
+ print(f"Runs: {stats['total_runs']}")
453
+ print(f"Success rate: {stats['success_rate']:.1%} ({stats['successful_runs']}/{stats['total_runs']})")
454
+ for k in range(1, n_runs + 1):
455
+ key = f"pass@{k}"
456
+ if key in stats:
457
+ print(f"{key:15} {stats[key]:.1%}")
458
+ print(f"Avg steps: {stats['avg_steps_per_run']}")
459
+ print(f"Avg reward: {stats['avg_final_reward']:.4f}")
460
+ print(f"Mean time: {stats['mean_elapsed_ms']:.0f} ms")
461
+ print(f"Tool usage: {stats['tool_usage']}")
462
+ print(f"Results file: {out_file}")
463
+ print("=" * 70)
464
+
465
+ all_tasks_results[task] = {"benchmark_config": config.copy(), "runs": all_runs, "statistics": stats}
466
+
467
+ return all_tasks_results
468
 
469
 
470
  if __name__ == "__main__":
openenv.yaml CHANGED
@@ -35,6 +35,42 @@ tasks:
35
  Agent must diagnose and fix all issues to pass all tests.
36
  difficulty: hard
37
  estimated_steps: 8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  action_schema:
40
  type: object
 
35
  Agent must diagnose and fix all issues to pass all tests.
36
  difficulty: hard
37
  estimated_steps: 8
38
+ - id: task4
39
+ title: "Type Error Detection"
40
+ description: >
41
+ Identify and fix type annotation errors detected by static type checking.
42
+ difficulty: medium
43
+ estimated_steps: 5
44
+ - id: task5
45
+ title: "Unused Imports and Dead Code"
46
+ description: >
47
+ Find and remove unused imports and dead code using code analysis tools.
48
+ difficulty: medium
49
+ estimated_steps: 5
50
+ - id: task6
51
+ title: "Complex Multi-file Refactoring"
52
+ description: >
53
+ Refactor code across multiple files while maintaining test coverage and fixing architectural issues.
54
+ difficulty: hard
55
+ estimated_steps: 8
56
+ - id: task7
57
+ title: "Code Review Workflow"
58
+ description: >
59
+ Multi-user collaborative task: Junior developer submits fix that needs code review and approval.
60
+ difficulty: medium
61
+ estimated_steps: 5
62
+ - id: task8
63
+ title: "Cross-team Bug Investigation"
64
+ description: >
65
+ Multi-user collaborative task: QA reported bug, dev team investigates and implements fix.
66
+ difficulty: hard
67
+ estimated_steps: 8
68
+ - id: task9
69
+ title: "Collaborative Architecture Refactoring"
70
+ description: >
71
+ Multi-user collaborative task: Large refactoring with multiple developers working in parallel.
72
+ difficulty: hard
73
+ estimated_steps: 10
74
 
75
  action_schema:
76
  type: object