Spaces:
Sleeping
Sleeping
feat: implement grading system with task definitions and score extraction
Browse filesFiles changed (9)
- grade/common.pyAdded+106
- grade/task_easyAdded+4
- grade/task_hardAdded+4
- grade/task_mediumAdded+4
- inference.py+85-18
- openenv.yaml+10-1
- pyproject.toml+1
- server/workflow_arena_environment.py+10-3
- uv.lock+2
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106from __future__ import annotations
import jsonimport reimport sysfrom pathlib import Pathfrom typing import Any
MIN_SCORE = 0.01MAX_SCORE = 0.99END_SCORE_RE = re.compile(r"\[END\].*?\bscore=([0-9]+(?:\.[0-9]+)?)")START_TASK_RE = re.compile(r"\[START\]\s+task=([^\s]+)")
def clamp_score(score: float) -> float: return round(min(MAX_SCORE, max(MIN_SCORE, score)), 4)
def read_payload_text() -> str: if len(sys.argv) > 1: path = Path(sys.argv[1]) if path.exists(): return path.read_text() return sys.stdin.read()
def _lookup_score(value: Any) -> float | None: if isinstance(value, (int, float)): return float(value)
if isinstance(value, dict): for key in ( "score", "benchmark_score", "final_score", "task_score", ): candidate = value.get(key) if isinstance(candidate, (int, float)): return float(candidate)
for key in ( "success_metrics", "observation", "final_observation", "result", "metrics", ): candidate = value.get(key) if candidate is not None: nested = _lookup_score(candidate) if nested is not None: return nested
if isinstance(value, list): for item in value: nested = _lookup_score(item) if nested is not None: return nested
return None
def extract_score(text: str) -> float: stripped = text.strip() if not stripped: return MIN_SCORE
match = END_SCORE_RE.search(stripped) if match: return clamp_score(float(match.group(1)))
try: payload = json.loads(stripped) except json.JSONDecodeError: return MIN_SCORE
score = _lookup_score(payload) if score is None: return MIN_SCORE return clamp_score(score)
def extract_started_task(text: str) -> str | None: match = START_TASK_RE.search(text) if match: return match.group(1) return None
def emit_grade(expected_task: str) -> int: text = read_payload_text() observed_task = extract_started_task(text) score = extract_score(text) if observed_task is not None and observed_task != expected_task: score = MIN_SCORE print( json.dumps( { "task_id": expected_task, "score": score, }, separators=(",", ":"), ) ) return 01234#!/usr/bin/env python3from common import emit_grade
raise SystemExit(emit_grade("easy"))1234#!/usr/bin/env python3from common import emit_grade
raise SystemExit(emit_grade("hard"))1234#!/usr/bin/env python3from common import emit_grade
raise SystemExit(emit_grade("medium"))25 unmodified lines26272829303133 unmodified lines656667686970101 unmodified lines17217317417517617755 unmodified lines23323423523623723823924024124224324410 unmodified lines2552562572582592602612622632649 unmodified lines27427527627727827928028128228328417 unmodified lines3023033043053063073083093103113123133147 unmodified lines32232332432525 unmodified linesPROJECT_DIR = Path(__file__).resolve().parentIMAGE_NAME = "workflow-arena-inference:latest"DOCKERFILE_PATH = PROJECT_DIR / "server" / "Dockerfile"TEMPERATURE = 0.0MAX_STEPS = 25633 unmodified lines)def compact_task(task: WorkflowTaskView) -> dict[str, object]:return {"task_id": task.task_id,101 unmodified linesreturn json.dumps(payload, separators=(",", ":"))def compute_score(observation: WorkflowArenaObservation) -> float:score = observation.benchmark_scoreif score is None:55 unmodified lines@asynccontextmanagerasync def managed_env():ensure_local_image()env = await WorkflowArenaEnv.from_docker_image(IMAGE_NAME)try:yield envfinally:await env.close()async def run_episode(10 unmodified lineslog_start(task=preset.value, env=BENCHMARK, model=model_name)result = await env.reset(seed=seed,preset=preset.value,)observation = result.observationwhile not observation.done and steps_taken < MAX_STEPS:9 unmodified linestry:result = await env.step(action)except (Exception): # pragma: no cover - preserve log format and continue safelyaction = heuristic_action(observation)result = await env.step(action)observation = result.observationreward = float(result.reward or 0.0)17 unmodified linesasync def main() -> None:api_base_url = os.environ["API_BASE_URL"]model_name = os.environ["MODEL_NAME"]api_key = os.getenv("HF_TOKEN") or os.getenv("OPENAI_API_KEY")if not api_key:raise RuntimeError("HF_TOKEN or OPENAI_API_KEY must be set.")client = OpenAI(base_url=api_base_url, api_key=api_key)async with managed_env() as env:for index, preset in enumerate(PRESETS):7 unmodified linesif __name__ == "__main__":asyncio.run(main())25 unmodified lines2627282930313233 unmodified lines66676869707172737475101 unmodified lines17717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521655 unmodified lines27227327427527627727827928028128228328428528628728828929029129229329429529610 unmodified lines3073083093103113123133143153163173183193203213223233249 unmodified lines33433533633733833934034134234334434534634734834935035135235335417 unmodified lines3723733743753763773787 unmodified lines38638738838939039139225 unmodified linesPROJECT_DIR = Path(__file__).resolve().parentIMAGE_NAME = "workflow-arena-inference:latest"DOCKERFILE_PATH = PROJECT_DIR / "server" / "Dockerfile"DEFAULT_BASE_URL = os.getenv("WORKFLOW_ARENA_BASE_URL", "http://localhost:8000")TEMPERATURE = 0.0MAX_STEPS = 25633 unmodified lines)def log_warning(message: str) -> None:print(f"[WARN] {message}", flush=True)def compact_task(task: WorkflowTaskView) -> dict[str, object]:return {"task_id": task.task_id,101 unmodified linesreturn json.dumps(payload, separators=(",", ":"))def resolve_model_client() -> tuple[OpenAI | None, str]:api_base_url = os.getenv("API_BASE_URL")model_name = os.getenv("MODEL_NAME")api_key = (os.getenv("API_KEY")or os.getenv("HF_TOKEN")or os.getenv("OPENAI_API_KEY"))missing = []if not api_base_url:missing.append("API_BASE_URL")if not model_name:missing.append("MODEL_NAME")if not api_key:missing.append("API_KEY")if missing:log_warning("Missing model configuration ("+ ", ".join(missing)+ "). Falling back to heuristic policy.")return None, "heuristic"try:return OpenAI(base_url=api_base_url, api_key=api_key), model_nameexcept Exception as exc: # pragma: no cover - defensive initialization fallbacklog_warning(f"Failed to initialize model client: {exc}. Falling back to heuristic policy.")return None, "heuristic"def compute_score(observation: WorkflowArenaObservation) -> float:score = observation.benchmark_scoreif score is None:55 unmodified lines@asynccontextmanagerasync def managed_env():try:async with WorkflowArenaEnv(base_url=DEFAULT_BASE_URL) as env:yield envreturnexcept Exception as exc:log_warning(f"Failed to connect to environment at {DEFAULT_BASE_URL}: {exc}. ""Trying local Docker fallback.")ensure_local_image()env = await WorkflowArenaEnv.from_docker_image(IMAGE_NAME)try:yield envfinally:try:await env.close()except Exception as exc: # pragma: no cover - teardown failures should not fail inferencelog_warning(f"Failed to close Docker environment cleanly: {exc}")async def run_episode(10 unmodified lineslog_start(task=preset.value, env=BENCHMARK, model=model_name)try:result = await env.reset(seed=seed,preset=preset.value,)except Exception as exc: # pragma: no cover - env availability failures are externallog_warning(f"Failed to reset preset={preset.value}: {exc}")log_end(success=False, steps=steps_taken, score=score, rewards=rewards)return EpisodeResult(success=success, steps=steps_taken, score=score, rewards=rewards)observation = result.observationwhile not observation.done and steps_taken < MAX_STEPS:9 unmodified linestry:result = await env.step(action)except Exception as exc: # pragma: no cover - preserve log format and continue safelyfallback_action = heuristic_action(observation)if fallback_action != action:log_warning(f"Step failed for preset={preset.value} with model action: {exc}. ""Retrying with heuristic action.")action = fallback_actiontry:result = await env.step(action)except Exception as retry_exc:log_warning(f"Step failed for preset={preset.value} even with heuristic action: {retry_exc}")breakobservation = result.observationreward = float(result.reward or 0.0)17 unmodified linesasync def main() -> None:client, model_name = resolve_model_client()async with managed_env() as env:for index, preset in enumerate(PRESETS):7 unmodified linesif __name__ == "__main__":try:asyncio.run(main())except Exception as exc: # pragma: no cover - final safeguard for validator stabilitylog_warning(f"Fatal inference error: {exc}")
3 unmodified lines45673 unmodified linesruntime: fastapiapp: server.app:appport: 80003 unmodified lines456789101112131415163 unmodified linesruntime: fastapiapp: server.app:appport: 8000tasks:- id: task_easydescription: Schedule a small, low-pressure dependency graph with high worker utilization.grader: grade/task_easy- id: task_mediumdescription: Balance utilization and deadlines on a moderately constrained workflow.grader: grade/task_medium- id: task_harddescription: Schedule under outages and retries while protecting critical work.grader: grade/task_hard
18 unmodified lines19202122232418 unmodified lines# "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git","openenv-core[core]>=0.2.2","gradio>=5.0.0","plotly>=5.24.0",# Environment-specific dependencies# Add all dependencies needed for your environment here18 unmodified lines1920212223242518 unmodified lines# "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git","openenv-core[core]>=0.2.2","gradio>=5.0.0","openai>=1.0.0","plotly>=5.24.0",# Environment-specific dependencies# Add all dependencies needed for your environment here
48 unmodified lines49505152535445 unmodified lines10010110210310410510610710810911011111248 unmodified linesUNFINISHED_PRIORITY_PENALTY: float = -0.02OVERDUE_PRIORITY_PENALTY_PER_TICK: float = -0.005MAX_RECENT_FAILURE_EVENTS: int = 6def __init__(self):self._state = State(episode_id=str(uuid4()), step_count=0)45 unmodified linesscore = lower_bound / max(lower_bound, env_state.current_time)return round(score, 4)def _benchmark_score(self) -> float:makespan_score, deadline_score, utilization_score = self._grade_components(include_terminal_makespan=True)return round((0.5 * makespan_score) + (0.3 * deadline_score) + (0.2 * utilization_score),4,)def _grade_components(48 unmodified lines495051525354555645 unmodified lines10210310410510610710810911011111211311411511611711811948 unmodified linesUNFINISHED_PRIORITY_PENALTY: float = -0.02OVERDUE_PRIORITY_PENALTY_PER_TICK: float = -0.005MAX_RECENT_FAILURE_EVENTS: int = 6MIN_GRADER_SCORE: float = 0.01MAX_GRADER_SCORE: float = 0.99def __init__(self):self._state = State(episode_id=str(uuid4()), step_count=0)45 unmodified linesscore = lower_bound / max(lower_bound, env_state.current_time)return round(score, 4)def _bounded_grader_score(self, score: float) -> float:return round(min(self.MAX_GRADER_SCORE, max(self.MIN_GRADER_SCORE, score)),4,)def _benchmark_score(self) -> float:makespan_score, deadline_score, utilization_score = self._grade_components(include_terminal_makespan=True)return self._bounded_grader_score((0.5 * makespan_score) + (0.3 * deadline_score) + (0.2 * utilization_score))def _grade_components(
1612 unmodified lines1613161416151616161716187 unmodified lines1626162716281629163016311612 unmodified linessource = { editable = "." }dependencies = [{ name = "gradio" },{ name = "openenv-core", extra = ["core"] },{ name = "plotly" },]7 unmodified lines[package.metadata]requires-dist = [{ name = "gradio", specifier = ">=5.0.0" },{ name = "openenv-core", extras = ["core"], specifier = ">=0.2.2" },{ name = "plotly", specifier = ">=5.24.0" },{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0" },1612 unmodified lines16131614161516161617161816197 unmodified lines16271628162916301631163216331612 unmodified linessource = { editable = "." }dependencies = [{ name = "gradio" },{ name = "openai" },{ name = "openenv-core", extra = ["core"] },{ name = "plotly" },]7 unmodified lines[package.metadata]requires-dist = [{ name = "gradio", specifier = ">=5.0.0" },{ name = "openai", specifier = ">=1.0.0" },{ name = "openenv-core", extras = ["core"], specifier = ">=0.2.2" },{ name = "plotly", specifier = ">=5.24.0" },{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0" },
grade/common.pyAdded+106
grade/task_easyAdded+4
grade/task_hardAdded+4
grade/task_mediumAdded+4
inference.py+85-18
openenv.yaml+10-1
pyproject.toml+1
server/workflow_arena_environment.py+10-3
uv.lock+2