Spaces:
Sleeping
Sleeping
modified: inference.py
Browse files- inference.py +106 -76
- openenv.yaml +36 -0
inference.py
CHANGED
|
@@ -51,18 +51,29 @@ logger = logging.getLogger(__name__)
|
|
| 51 |
|
| 52 |
# ── Configuration ───────────────────────────────────────────────────────────────
|
| 53 |
|
| 54 |
-
|
| 55 |
-
"
|
| 56 |
-
"
|
| 57 |
-
|
| 58 |
-
"
|
| 59 |
-
|
| 60 |
-
"
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 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(
|
| 80 |
"""OpenAI client pointed at the HuggingFace OpenAI-compatible endpoint."""
|
|
|
|
| 81 |
return OpenAI(
|
| 82 |
-
|
| 83 |
-
|
| 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=
|
| 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 =
|
| 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 |
-
|
|
|
|
| 382 |
n_runs = config["number_of_runs"]
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
"
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|