Spaces:
Sleeping
Sleeping
Update training.py
Browse files12349 unmodified lines1415161718195 unmodified lines25262728293031323335 unmodified lines6970717273747576777879808138 unmodified lines1201211221231241251261271281294 unmodified lines1341351361371381391401411421431441451461471481491501511521 unmodified line1541551561571581591601615 unmodified lines1671681691701711721738 unmodified lines1821831841851861871884 unmodified lines1931941951961971981992001 unmodified line2022032042052062072082092102112122138 unmodified lines2222232242252262272282292302312322332342352362372382392402412422431 unmodified line24524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829917 unmodified lines317318319320321322323324325225 unmodified lines55155255355455555655710 unmodified lines56856957057157257357457531 unmodified lines607608609610611612# training.py – Memory‑safe: Phi‑3‑mini + Expert Demos + Fast PPO (2 iterations)import osos.environ["TRITON_DISABLE"] = "1"9 unmodified linesimport reimport randomimport matplotlib.pyplot as pltfrom unsloth import FastLanguageModelfrom transformers import TrainingArguments5 unmodified linesfrom models import (RunTests, RunLinter, Inspect,ProposeFix, WriteComment, AskQuestion,Done, Skip, QueryDocs, map_to_env as model_map_to_env)# ======================================================================@dataclassclass AgentAction:35 unmodified linesreturn AgentAction("invalid", output)def map_to_env(action: AgentAction):return model_map_to_env(action.action_type, action.content)# ======================================================================def load_model():model, tokenizer = FastLanguageModel.from_pretrained(model_name="unsloth/Phi-3-mini-4k-instruct-bnb-4bit",max_seq_length=480, # smaller window for memoryload_in_4bit=True,)model = FastLanguageModel.get_peft_model(38 unmodified lines# ======================================================================def _expert_fix_from_context(obs) -> str:"""Build a conservative fix template named `fix` (required by tests).Uses bug hints + code snippet patterns to create realistic fixes."""bug = (getattr(obs, "bug_description", "") or "").lower()code = getattr(obs, "code_snippet", "") or ""4 unmodified lines" return 0\n"" return sum(data) / len(data)")if "operator" in bug or "sign" in bug:return ("def fix(a, b):\n"" return a + b")if "off_by_one" in bug or "loop" in bug:return ("def fix(items):\n"" return len(items)")if "null" in bug or "key" in bug or "dict" in code.lower():return ("def fix(payload):\n"1 unmodified line" user_id = payload.get('id')\n"" return users.get(user_id)")# Concurrency-heavy tasks (harder/hardest).if "race" in bug or "missing_lock" in bug or "thread_safe" in bug or "global_nonatomic" in bug:return ("import threading\n"5 unmodified lines" return 0\n"" return counter + 1")if "deadlock" in bug or "double_lock" in bug or "lock order" in bug or "nested_lock" in bug:return ("import threading\n"8 unmodified lines" with second:\n"" return work() if callable(work) else work")if "fork_join" in bug or "join" in bug:return ("import threading\n"4 unmodified lines" t.join()\n"" return True")# Generic safe fallback keeps the RL pipeline alive for unknown bugs.return ("def fix(data):\n"" if data is None:\n"1 unmodified line" return data")def _expert_supervised_policy(obs) -> str:"""Real workflow policy:inspect -> tests/linter -> docs -> fix -> negotiate -> done."""author_msg = (getattr(obs, "author_response", "") or "").lower()tool_output = (getattr(obs, "last_tool_output", "") or "").lower()8 unmodified linesif not getattr(obs, "docs_queried", False):return '{"action_type": "query_docs", "content": "python bug fixing best practices for edge cases and null safety"}'# Use docs again on hard tasks when evidence is still weak.if getattr(obs, "current_test_score", 0.0) < 0.6 and getattr(obs, "step", 0) >= 3:bug_hint = (getattr(obs, "bug_description", "") or "concurrency bug").replace('"', "'")return json.dumps({"action_type": "query_docs","content": f"python {bug_hint} lock ordering race condition mitigation patterns",})# If test quality is poor, propose a concrete fix.if getattr(obs, "current_test_score", 0.0) < 0.95:fix_code = _expert_fix_from_context(obs)return json.dumps({"action_type": "fix", "content": fix_code})# If author is still unconvinced, provide causal explanation.if author_msg and ("not convinced" in author_msg or "explain" in author_msg or "brief" in author_msg):return ('{"action_type": "comment", "content": "This fix works because it handles the failing edge case directly, '1 unmodified line'The change is intentionally small to reduce regression risk."}')# If negotiation is strong enough and quality is good, terminate.conf = float(getattr(obs, "author_confidence", 0.0))threshold = float(getattr(obs, "author_threshold", 0.5))score = float(getattr(obs, "current_test_score", 0.0))if conf >= threshold and score >= 0.8:return '{"action_type": "done"}'# Nudge conversation forward when tests are okay but acceptance is pending.return ('{"action_type": "question", "content": "Would you like a quick walkthrough of a failing scenario, the root cause, and how the fix prevents regressions?"}')# ======================================================================def supervised_warmup(model, tokenizer, env, n_episodes=16, epochs=1, max_steps=8):print("\n" + "="*60)print("SUPERVISED WARM-UP: Real environment demonstrations")print("="*60)examples = []tasks = ["easy", "medium", "hard", "harder", "hardest"]for ep in range(n_episodes):task = random.choice(tasks)env.set_task(task)obs = env.reset()history = []done = Falsesteps = 0while not done and steps < max_steps:prompt = build_prompt(obs, history)action_text = _expert_supervised_policy(obs)action = parse_action(action_text)env_action = map_to_env(action)next_obs, _, done, _ = env.step(env_action)messages = [{"role": "user", "content": prompt},{"role": "assistant", "content": action_text},]full_text = tokenizer.apply_chat_template(messages, tokenize=False)examples.append({"text": full_text})history.append(f"Agent: {action_text}")history.append(f"Env: {next_obs.last_tool_output}")history = history[-8:]obs = next_obssteps += 1print(f"Supervised episode {ep+1}: task={task}, steps={steps}, done={done}")if not examples:print("No supervised examples generated; skipping warm-up.")17 unmodified linesbf16=True,),)print(f"Training on {len(examples)} real env examples for {epochs} epochs...")trainer.train()print("✓ Supervised warm-up (real env) complete\n")torch.cuda.empty_cache()# ======================================================================225 unmodified linesreturn {"avg_reward": np.mean(total_rewards), "std_reward": np.std(total_rewards)}# ======================================================================def train_ppo():n_iterations = 2trajectories_per_iter = 2n_epochs = 110 unmodified linesreturnenv = CodeReviewEnv()# Warm-up (real env demonstrations with expert policy)supervised_warmup(model, tokenizer, env, n_episodes=16, epochs=1, max_steps=8)optimizer = AdamW(model.parameters(), lr=learning_rate)task_levels = list(BUG_DB.keys())31 unmodified linesplt.grid(alpha=0.3); plt.tight_layout(); plt.savefig("loss_curve.png", dpi=150); plt.close()print("Plots saved as reward_curve.png and loss_curve.png.")print("="*60)if __name__ == "__main__":train_ppo()12349 unmodified lines141516171819205 unmodified lines26272829303132333435363738394035 unmodified lines76777879808182838485868788899091929394959697989910010110210310410538 unmodified lines1441451461471481491504 unmodified lines1551561571581591601611621631641651661671681691701 unmodified line1721731741751761775 unmodified lines1831841851861871888 unmodified lines1971981992002012024 unmodified lines2072082092102112121 unmodified line2142152162172182192202218 unmodified lines2302312322332342352362372382392402412422432442452461 unmodified line24824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831917 unmodified lines337338339340341342343344345225 unmodified lines57157257357457557657710 unmodified lines58858959059159259359459559659759831 unmodified lines630631632633634635636637638# training.py – Pre‑loaded embedder, dual supervised warm‑up, 2 PPO iterationsimport osos.environ["TRITON_DISABLE"] = "1"9 unmodified linesimport reimport randomimport matplotlib.pyplot as pltfrom pathlib import Pathfrom unsloth import FastLanguageModelfrom transformers import TrainingArguments5 unmodified linesfrom models import (RunTests, RunLinter, Inspect,ProposeFix, WriteComment, AskQuestion,Done, Skip, QueryDocs)# Pre‑load the sentence‑transformer model to avoid OOM during warm‑upfrom rltool import ToolBoxprint("Pre‑loading documentation retriever …")ToolBox._get_embedder()print("Done.")# ======================================================================@dataclassclass AgentAction:35 unmodified linesreturn AgentAction("invalid", output)def map_to_env(action: AgentAction):if action.action_type == "run_tests":return RunTests()elif action.action_type == "run_linter":return RunLinter()elif action.action_type == "inspect":return Inspect()elif action.action_type == "fix":return ProposeFix(fix_code=action.content or "")elif action.action_type == "comment":return WriteComment(comment_text=action.content or "")elif action.action_type == "question":return AskQuestion(question=action.content or "")elif action.action_type == "query_docs":return QueryDocs(query_topic=action.content or "")elif action.action_type == "done":return Done()else:return Skip()# ======================================================================def load_model():model, tokenizer = FastLanguageModel.from_pretrained(model_name="unsloth/Phi-3-mini-4k-instruct-bnb-4bit",max_seq_length=480,load_in_4bit=True,)model = FastLanguageModel.get_peft_model(38 unmodified lines# ======================================================================def _expert_fix_from_context(obs) -> str:"""Build a conservative fix template based on bug hints."""bug = (getattr(obs, "bug_description", "") or "").lower()code = getattr(obs, "code_snippet", "") or ""4 unmodified lines" return 0\n"" return sum(data) / len(data)")if "operator" in bug or "sign" in bug:return ("def fix(a, b):\n"" return a + b")if "off_by_one" in bug or "loop" in bug:return ("def fix(items):\n"" return len(items)")if "null" in bug or "key" in bug or "dict" in code.lower():return ("def fix(payload):\n"1 unmodified line" user_id = payload.get('id')\n"" return users.get(user_id)")if "race" in bug or "missing_lock" in bug or "thread_safe" in bug or "global_nonatomic" in bug:return ("import threading\n"5 unmodified lines" return 0\n"" return counter + 1")if "deadlock" in bug or "double_lock" in bug or "lock order" in bug or "nested_lock" in bug:return ("import threading\n"8 unmodified lines" with second:\n"" return work() if callable(work) else work")if "fork_join" in bug or "join" in bug:return ("import threading\n"4 unmodified lines" t.join()\n"" return True")return ("def fix(data):\n"" if data is None:\n"1 unmodified line" return data")def _expert_supervised_policy(obs) -> str:"""Expert policy used during supervised warm‑up."""author_msg = (getattr(obs, "author_response", "") or "").lower()tool_output = (getattr(obs, "last_tool_output", "") or "").lower()8 unmodified linesif not getattr(obs, "docs_queried", False):return '{"action_type": "query_docs", "content": "python bug fixing best practices for edge cases and null safety"}'if getattr(obs, "current_test_score", 0.0) < 0.6 and getattr(obs, "step", 0) >= 3:bug_hint = (getattr(obs, "bug_description", "") or "concurrency bug").replace('"', "'")return json.dumps({"action_type": "query_docs","content": f"python {bug_hint} lock ordering race condition mitigation patterns"})if getattr(obs, "current_test_score", 0.0) < 0.95:fix_code = _expert_fix_from_context(obs)return json.dumps({"action_type": "fix", "content": fix_code})if author_msg and ("not convinced" in author_msg or "explain" in author_msg or "brief" in author_msg):return ('{"action_type": "comment", "content": "This fix works because it handles the failing edge case directly, '1 unmodified line'The change is intentionally small to reduce regression risk."}')conf = float(getattr(obs, "author_confidence", 0.0))threshold = float(getattr(obs, "author_threshold", 0.5))score = float(getattr(obs, "current_test_score", 0.0))if conf >= threshold and score >= 0.8:return '{"action_type": "done"}'return ('{"action_type": "question", "content": "Would you like a quick walkthrough of a failing scenario, ''the root cause, and how the fix prevents regressions?"}')# ======================================================================def supervised_warmup(model, tokenizer, env, n_episodes=16, epochs=1, max_steps=8,json_path: Optional[str] = None):"""Supervised warm‑up using either a JSON file of (prompt, action) pairs,or a rule‑based expert playing in the real environment."""print("\n" + "="*60)print("SUPERVISED WARM-UP: Real environment demonstrations")print("="*60)examples = []if json_path and Path(json_path).exists():print(f"Loading training examples from {json_path} ...")with open(json_path, 'r', encoding='utf-8') as f:raw_pairs = json.load(f)for pair in raw_pairs:prompt = pair["prompt"]action = pair["action"]messages = [{"role": "user", "content": prompt},{"role": "assistant", "content": action}]full_text = tokenizer.apply_chat_template(messages, tokenize=False)examples.append({"text": full_text})print(f"Loaded {len(examples)} examples from JSON.")else:# Fallback to real environment rollouts with expert policytasks = ["easy", "medium", "hard", "harder", "hardest"]for ep in range(n_episodes):task = random.choice(tasks)env.set_task(task)obs = env.reset()history = []done = Falsesteps = 0while not done and steps < max_steps:prompt = build_prompt(obs, history)action_text = _expert_supervised_policy(obs)action = parse_action(action_text)env_action = map_to_env(action)next_obs, _, done, _ = env.step(env_action)messages = [{"role": "user", "content": prompt},{"role": "assistant", "content": action_text},]full_text = tokenizer.apply_chat_template(messages, tokenize=False)examples.append({"text": full_text})history.append(f"Agent: {action_text}")history.append(f"Env: {next_obs.last_tool_output}")history = history[-8:]obs = next_obssteps += 1print(f"Supervised episode {ep+1}: task={task}, steps={steps}, done={done}")if not examples:print("No supervised examples generated; skipping warm-up.")17 unmodified linesbf16=True,),)print(f"Training on {len(examples)} examples for {epochs} epochs...")trainer.train()print("✓ Supervised warm-up complete\n")torch.cuda.empty_cache()# ======================================================================225 unmodified linesreturn {"avg_reward": np.mean(total_rewards), "std_reward": np.std(total_rewards)}# ======================================================================def train_ppo(json_dataset_path: Optional[str] = None):n_iterations = 2trajectories_per_iter = 2n_epochs = 110 unmodified linesreturnenv = CodeReviewEnv()# Run supervised warm‑up twice (if JSON provided, it will be used each time)supervised_warmup(model, tokenizer, env, n_episodes=12, epochs=1, max_steps=8,json_path=json_dataset_path)supervised_warmup(model, tokenizer, env, n_episodes=12, epochs=1, max_steps=8,json_path=json_dataset_path)optimizer = AdamW(model.parameters(), lr=learning_rate)task_levels = list(BUG_DB.keys())31 unmodified linesplt.grid(alpha=0.3); plt.tight_layout(); plt.savefig("loss_curve.png", dpi=150); plt.close()print("Plots saved as reward_curve.png and loss_curve.png.")print("="*60)# ======================================================================if __name__ == "__main__":# Optionally provide a path to a JSON file of training pairs.# Example: {"prompt": "You are a code review agent...", "action": "{\"action_type\": \"inspect\"}"}train_ppo(json_dataset_path=None) # set to your JSON file path if you have one
training.py+92-66