Spaces:
Sleeping
Sleeping
databoysu commited on
Commit ·
b4f37fd
1
Parent(s): beb93a1
fixing state machine
Browse filesFiles changed (7)
1 unmodified line2345678100 unmodified lines1091101111121131141151161171181191201 unmodified linetitle: TraceFix-RLemoji: 🧑💻colorFrom: bluecolorTo: indigosdk: dockerpinned: falseapp_port: 7860100 unmodified lines- `--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:1 unmodified line234567100 unmodified lines1081091101111121131141151161171181191 unmodified linetitle: TraceFix-RLemoji: 🧑💻colorFrom: bluesdk: dockerpinned: falseapp_port: 7860100 unmodified lines- `--easy`: run episode using easy-tier curriculum sampling.- `--medium`: run episode using medium-tier curriculum sampling.- `--hard`: run episode using hard-tier curriculum sampling.- `--thought`: include model thought traces in internal prompt history.Example:```bashpython inference.py --medium --thought```The script also enforces a model-thinking/output cap:
46 unmodified lines474849505152535445 unmodified lines1001011021031041051069 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451463 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721731741751767 unmodified lines18418518618718818919023 unmodified lines2142152162172182192202217 unmodified lines2292302312322332342357 unmodified lines24324424524624724824925025125211 unmodified lines2642652662672682692704 unmodified lines27527627727846 unmodified linesMAX_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. "45 unmodified linesexcept json.JSONDecodeError:passreturn {"action_type": "RUN_TESTS"}def _build_observation_text(observation: Any) -> str:9 unmodified linesdef _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"f"{obs_text}\n\n"f"history:\n{chr(10).join(history[-5:]) if history else 'none'}")try:completion = client.chat.completions.create(model=MODEL_NAME,messages=[{"role": "system", "content": SYSTEM_PROMPT},{"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"}if action.get("action_type") not in {"VIEW_CODE",3 unmodified lines"RESET_TO_ORIGINAL","SUBMIT",}:action = {"action_type": "RUN_TESTS"}return actiondef _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"),}try:return CodeAction(**payload)except Exception:return CodeAction(action_type="RUN_TESTS")def _compute_score(step_result: Any, rewards: list[float]) -> float:7 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] = None23 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)reward = float(result.reward or 0.0)7 unmodified linesrewards.append(reward)steps_taken = stephistory.append(f"step={step} action={action_str} reward={reward:.2f}")log_step(step=step, action=action_str, reward=reward, done=done, error=error)if done:7 unmodified lineslog_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)started = Truemsg = str(exc).replace("\n", " ")if steps_taken == 0:log_step(step=1, action="RUN_TESTS", reward=0.0, done=False, error=msg)steps_taken = 1rewards.append(0.0)score = 0.0success = Falsefinally:11 unmodified linesgroup.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] = None4 unmodified lineselif args.hard:difficulty = "hard"asyncio.run(run(difficulty=difficulty, debug=args.debug))46 unmodified lines4748495051525345 unmodified lines991001011021031041059 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391403 unmodified lines1441451461471481491501511521531541551561571581591601611621637 unmodified lines17117217317417517617723 unmodified lines2012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332347 unmodified lines2422432442452462472487 unmodified lines25625725825926026111 unmodified lines2732742752762772782794 unmodified lines28428528628746 unmodified linesMAX_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"))MAX_PARSE_RETRIES = 3SYSTEM_PROMPT = ("You are controlling a Python debugging RL environment. "45 unmodified linesexcept json.JSONDecodeError:passraise ValueError("Invalid JSON response.")def _build_observation_text(observation: Any) -> str:9 unmodified linesdef _get_model_action(client: OpenAI, observation: Any, history: list[str]) -> tuple[dict[str, Any], str]:obs_text = _build_observation_text(observation)user_prompt = ("Pick the single best next action and return only JSON.\n\n"f"{obs_text}\n\n"f"history:\n{chr(10).join(history[-5:]) if history else 'none'}")completion = client.chat.completions.create(model=MODEL_NAME,messages=[{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": user_prompt},],temperature=0.0,max_tokens=THINKING_TOKEN_LIMIT,stream=False,)response_text = (completion.choices[0].message.content or "").strip()action = _extract_json(response_text)if action.get("action_type") not in {"VIEW_CODE",3 unmodified lines"RESET_TO_ORIGINAL","SUBMIT",}:raise ValueError("Invalid action_type in model response.")return action, response_textdef _to_code_action(action_dict: dict[str, Any]) -> CodeAction:payload = {"action_type": action_dict.get("action_type"),"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"),}return CodeAction(**payload)def _compute_score(step_result: Any, rewards: list[float]) -> float:7 unmodified linesreturn max(0.0, min(1.0, float(raw)))async def run(difficulty: Optional[str] = None, show_thought: bool = False) -> None:client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)env: Optional[TraceFixRLEnv] = None23 unmodified linesif result.done:breakaction: Optional[CodeAction] = Nonemodel_response = ""for attempt in range(1, MAX_PARSE_RETRIES + 1):try:action_dict, model_response = _get_model_action(client, result.observation, history)action = _to_code_action(action_dict)if show_thought:history.append(f"thought={action.thought}")breakexcept Exception as exc:cause = str(exc).replace("\n", " ")history.append((f"parse_failure attempt={attempt} cause={cause}. ""Error: Invalid JSON or schema. Return a complete valid JSON object ""with fields: thought, action_type, start_line, end_line, new_code_block."))if model_response:history.append(f"raw_response={model_response[:500]}")if action is None:action = CodeAction(action_type="RUN_TESTS",thought="Fallback after repeated invalid JSON/schema responses.",)result = await env.step(action)reward = float(result.reward or 0.0)7 unmodified linesrewards.append(reward)steps_taken = stephistory.append(f"step={step} action={action_str} reward={reward:.2f} error={error or 'null'}")log_step(step=step, action=action_str, reward=reward, done=done, error=error)if done:7 unmodified lineslog_start(task=TASK_NAME, env=BENCHMARK, model=MODEL_NAME)started = Truemsg = str(exc).replace("\n", " ")score = 0.0success = Falsefinally:11 unmodified linesgroup.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("--thought", action="store_true", help="Include model thought traces in internal history.")args = parser.parse_args()difficulty: Optional[str] = None4 unmodified lineselif args.hard:difficulty = "hard"asyncio.run(run(difficulty=difficulty, show_thought=args.thought))
20 unmodified lines21222324252627282920 unmodified linesclass CodeAction(Action):"""Structured action consumed by the environment."""thought: Optional[str] = Field(default=None,description="Optional reasoning string for debugging/traceability.",)action_type: ActionType = Field(...,20 unmodified lines21222324252627282920 unmodified linesclass CodeAction(Action):"""Structured action consumed by the environment."""thought: str = Field(...,description="Mandatory reasoning string before selecting an action.",)action_type: ActionType = Field(...,
12345fastapi==0.111.0uvicorn[standard]==0.30.1pydantic==1.10.17websockets==12.0openai>=1.30.012345fastapi==0.111.0uvicorn[standard]==0.30.1pydantic>=2.0.0websockets==12.0openai>=1.30.0
608 unmodified lines60961061161261361461561661761861 unmodified lines680681682683608 unmodified lines" intervals.sort()"," merged = []"," for interval in intervals:"," if not merged or merged[-1][1] <= interval[0]:"," merged.append(list(interval))"," else:"," merged[-1][1] = min(merged[-1][1], interval[1])"," return merged",],tests=[_tmi_1, _tmi_2, _tmi_3],61 unmodified lines# Flat list — used for random sampling when training_step is not setALL_TASKS: List[Dict] = [t for bucket in TASKS_BY_DIFFICULTY.values() for t in bucket]608 unmodified lines60961061161261361461561661761861 unmodified lines680681682683608 unmodified lines" intervals.sort()"," merged = []"," for interval in intervals:"," if not merged or merged[-1][1] < interval[0]:"," merged.append(list(interval))"," else:"," merged[-1][1] = max(merged[-1][1], interval[1])"," return merged",],tests=[_tmi_1, _tmi_2, _tmi_3],61 unmodified lines# Flat list — used for random sampling when training_step is not setALL_TASKS: List[Dict] = [t for bucket in TASKS_BY_DIFFICULTY.values() for t in bucket]
README.md+2-3
__pycache__/models.cpython-312.pyc
__pycache__/tasks.cpython-312.pyc
inference.py+53-44
models.py+3-3
requirements.txt+1-1
tasks.py+3-3