Spaces:
Sleeping
Sleeping
databoysu commited on
Commit ·
20ef9ad
1
Parent(s): 2e11c6a
TraceFix-RL v1 deploy
Browse filesFiles changed (9)
57 unmodified lines58596061626319 unmodified lines83848586878811 unmodified lines10010110210310410557 unmodified linesFocus: data-structure invariants, eviction/promotion logic, bracket mapping, and interval merging edge behavior.Every task follows the same schema:- `name`, `description`, `difficulty`, `bug_type`- `code`: buggy implementation (line list)- `solution`: reference implementation19 unmodified lines```Server endpoints:- `POST /reset`- `POST /step`- `GET /health`11 unmodified lines`[START]`, one or more `[STEP]`, then `[END]`.- Final score is clamped to `[0, 1]`.## Docker + DeploymentBuild locally:57 unmodified lines5859606162636419 unmodified lines8485868788899011 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612757 unmodified linesFocus: data-structure invariants, eviction/promotion logic, bracket mapping, and interval merging edge behavior.Every task follows the same schema:- `name`, `description`, `difficulty`, `bug_type`- `code`: buggy implementation (line list)- `solution`: reference implementation19 unmodified lines```Server endpoints:- `POST /reset`- `POST /step`- `GET /health`11 unmodified lines`[START]`, one or more `[STEP]`, then `[END]`.- Final score is clamped to `[0, 1]`.## Inference Flags`inference.py` supports:- `--easy`: run episode using easy-tier curriculum sampling.- `--medium`: run episode using medium-tier curriculum sampling.- `--hard`: run episode using hard-tier curriculum sampling.- `--debug`: print raw model response snippets for troubleshooting.Example:```bashpython inference.py --medium --debug```The script also enforces a model-thinking/output cap:- `THINKING_TOKEN_LIMIT` (default `512`) is used as `max_tokens` in model calls.- `thought` content is hard-truncated before action validation to prevent oversized payloads.## Docker + DeploymentBuild locally:
14 unmodified lines15161718192021222324252627282930318 unmodified lines4041424344458 unmodified lines5455565758596045 unmodified lines1061071081091101111128 unmodified lines12112212312412512612712812913012 unmodified lines14314414514614714814915015115 unmodified lines1671681691701711721731741751767 unmodified lines1841851861871881891902 unmodified lines19319419519619719819938 unmodified lines23823924024114 unmodified linesfrom __future__ import annotationsimport asyncioimport jsonimport osimport refrom typing import Anyfrom openai import OpenAItry:from tracefix_rl import CodeAction, TraceFixRLEnvexcept ImportError:from client import TraceFixRLEnvfrom models import CodeAction8 unmodified linesBENCHMARK = os.getenv("BENCHMARK", "tracefix_rl")MAX_STEPS = int(os.getenv("MAX_STEPS", "50"))SUCCESS_SCORE_THRESHOLD = float(os.getenv("SUCCESS_SCORE_THRESHOLD", "0.99"))SYSTEM_PROMPT = ("You are controlling a Python debugging RL environment. "8 unmodified linesprint(f"[START] task={task} env={env} model={model}", flush=True)def log_step(step: int, action: str, reward: float, done: bool, error: str | None) -> None:error_value = error if error else "null"print(f"[STEP] step={step} action={action} reward={reward:.2f} done={str(done).lower()} error={error_value}",45 unmodified lines)def _get_model_action(client: OpenAI, observation: Any, history: list[str]) -> dict[str, Any]:obs_text = _build_observation_text(observation)user_prompt = ("Pick the single best next action and return only JSON.\n\n"8 unmodified lines{"role": "user", "content": user_prompt},],temperature=0.0,max_tokens=300,stream=False,)response_text = (completion.choices[0].message.content or "").strip()action = _extract_json(response_text)except Exception:action = {"action_type": "RUN_TESTS"}12 unmodified linesdef _to_code_action(action_dict: dict[str, Any]) -> CodeAction:payload = {"action_type": action_dict.get("action_type", "RUN_TESTS"),"thought": action_dict.get("thought"),"start_line": action_dict.get("start_line"),"end_line": action_dict.get("end_line"),"new_code_block": action_dict.get("new_code_block"),15 unmodified linesreturn max(0.0, min(1.0, float(raw)))async def main() -> None:client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)env: TraceFixRLEnv | None = Nonerewards: list[float] = []history: list[str] = []steps_taken = 07 unmodified lineselse:env = TraceFixRLEnv(base_url=ENV_BASE_URL)result = await env.reset()task_name = result.observation.info.get("task_name") or TASK_NAMElog_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)started = True2 unmodified linesif result.done:breakaction_dict = _get_model_action(client, result.observation, history)action = _to_code_action(action_dict)result = await env.step(action)38 unmodified linesif __name__ == "__main__":asyncio.run(main())14 unmodified lines15161718192021222324252627282930313233343536378 unmodified lines4647484950515253548 unmodified lines6364656667686945 unmodified lines1151161171181191201211221238 unmodified lines13213313413513613713813914014114214312 unmodified lines15615715815916016116216316416516616716815 unmodified lines1841851861871881891901911921937 unmodified lines2012022032042052062072082092102112 unmodified lines21421521621721821922038 unmodified lines25926026126226326426526626726826927027127227327427527627727814 unmodified linesfrom __future__ import annotationsimport argparseimport asyncioimport jsonimport osimport reimport sysfrom pathlib import Pathfrom typing import Any, Optionalfrom openai import OpenAItry:from tracefix_rl import CodeAction, TraceFixRLEnvexcept Exception:ROOT_DIR = Path(__file__).resolve().parentif str(ROOT_DIR) not in sys.path:sys.path.insert(0, str(ROOT_DIR))from client import TraceFixRLEnvfrom models import CodeAction8 unmodified linesBENCHMARK = os.getenv("BENCHMARK", "tracefix_rl")MAX_STEPS = int(os.getenv("MAX_STEPS", "50"))SUCCESS_SCORE_THRESHOLD = float(os.getenv("SUCCESS_SCORE_THRESHOLD", "0.99"))THINKING_TOKEN_LIMIT = int(os.getenv("THINKING_TOKEN_LIMIT", "512"))# Approximation used for hard truncation before sending to server.THINKING_CHAR_LIMIT = THINKING_TOKEN_LIMIT * 4SYSTEM_PROMPT = ("You are controlling a Python debugging RL environment. "8 unmodified linesprint(f"[START] task={task} env={env} model={model}", flush=True)def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:error_value = error if error else "null"print(f"[STEP] step={step} action={action} reward={reward:.2f} done={str(done).lower()} error={error_value}",45 unmodified lines)def _get_model_action(client: OpenAI, observation: Any, history: list[str], debug: bool = False) -> dict[str, Any]:obs_text = _build_observation_text(observation)user_prompt = ("Pick the single best next action and return only JSON.\n\n"8 unmodified lines{"role": "user", "content": user_prompt},],temperature=0.0,max_tokens=THINKING_TOKEN_LIMIT,stream=False,)response_text = (completion.choices[0].message.content or "").strip()if debug:print(f"[DEBUG] raw_model_response={response_text[:500]}", flush=True)action = _extract_json(response_text)except Exception:action = {"action_type": "RUN_TESTS"}12 unmodified linesdef _to_code_action(action_dict: dict[str, Any]) -> CodeAction:thought = action_dict.get("thought")if isinstance(thought, str):thought = thought[:THINKING_CHAR_LIMIT]payload = {"action_type": action_dict.get("action_type", "RUN_TESTS"),"thought": thought,"start_line": action_dict.get("start_line"),"end_line": action_dict.get("end_line"),"new_code_block": action_dict.get("new_code_block"),15 unmodified linesreturn max(0.0, min(1.0, float(raw)))async def run(difficulty: Optional[str] = None, debug: bool = False) -> None:client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)env: Optional[TraceFixRLEnv] = Nonerewards: list[float] = []history: list[str] = []steps_taken = 07 unmodified lineselse:env = TraceFixRLEnv(base_url=ENV_BASE_URL)if difficulty:reset_kwargs = {"difficulty": difficulty}result = await env.reset(**reset_kwargs)else:result = await env.reset()task_name = result.observation.info.get("task_name") or TASK_NAMElog_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)started = True2 unmodified linesif result.done:breakaction_dict = _get_model_action(client, result.observation, history, debug=debug)action = _to_code_action(action_dict)result = await env.step(action)38 unmodified linesif __name__ == "__main__":parser = argparse.ArgumentParser(description="Run TraceFix-RL inference baseline.")group = parser.add_mutually_exclusive_group()group.add_argument("--easy", action="store_true", help="Run on easy curriculum tier.")group.add_argument("--medium", action="store_true", help="Run on medium curriculum tier.")group.add_argument("--hard", action="store_true", help="Run on hard curriculum tier.")parser.add_argument("--debug", action="store_true", help="Print debug model output snippets.")args = parser.parse_args()difficulty: Optional[str] = Noneif args.easy:difficulty = "easy"elif args.medium:difficulty = "medium"elif args.hard:difficulty = "hard"asyncio.run(run(difficulty=difficulty, debug=args.debug))
19 unmodified lines2021222324252619 unmodified linesself._gym = TraceFixRLGym()self._state = State(episode_id="", step_count=0)def reset(self) -> CodeObservation:obs, system_prompt = self._gym.reset()self._state = State(episode_id=obs.info.get("episode_id", ""),19 unmodified lines202122232425262728293031323319 unmodified linesself._gym = TraceFixRLGym()self._state = State(episode_id="", step_count=0)def reset(self, difficulty: str | None = None) -> CodeObservation:if difficulty == "easy":self._gym.training_step = 1elif difficulty == "medium":self._gym.training_step = 2000elif difficulty == "hard":self._gym.training_step = 6000obs, system_prompt = self._gym.reset()self._state = State(episode_id=obs.info.get("episode_id", ""),
README.md+22
__pycache__/client.cpython-312.pyc
__pycache__/context.cpython-312.pyc
__pycache__/environment.cpython-312.pyc
__pycache__/models.cpython-312.pyc
__pycache__/sandbox.cpython-312.pyc
inference.py+48-11
server/__pycache__/__init__.cpython-312.pyc
server/tracefix_rl_environment.py+8-1