Spaces:
Sleeping
Sleeping
Update training.py
Browse files123413 unmodified lines18192021222324252627282930313233341 unmodified line36373839404142432 unmodified lines46474849505152534 unmodified lines58596061626364656667686970712 unmodified lines7475767778798081829 unmodified lines929394959697981 unmodified line10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013124 unmodified lines15615715815916016116221 unmodified lines18418518618718818919047 unmodified lines2382392402412422432442452462472482492502512522532542552562572582592602612622637 unmodified lines2712722732742752762772782792802812 unmodified lines2842852862872882892906 unmodified lines2972982993003013023031 unmodified line30530630730830931031131231331431531631731831932032132232 unmodified lines3553563573583593603612 unmodified lines3643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035043 unmodified lines5085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495501 unmodified line5525535545555565575585595605615625635645655665675685695705713 unmodified lines5755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876881 unmodified line690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784# training.pyimport torch._dynamotorch._dynamo.config.disable = Trueimport json13 unmodified linesfrom trl import SFTTrainerfrom datasets import Dataset# Import your environment and actions (unchanged)from environment import CodeReviewEnvfrom redteam import BUG_DBfrom models import (RunTests, RunLinter, Inspect,ProposeFix, WriteComment, AskQuestion,Done, Skip , QueryDocs)# ======================================================================# 1. ACTION PARSING (improved with fallback)# ======================================================================@dataclassclass AgentAction:1 unmodified linecontent: Optional[str] = Nonedef parse_action(output: str) -> AgentAction:"""Robust JSON parsing with regex fallback and keyword detection."""# Try strict JSON firsttry:data = json.loads(output)return AgentAction(2 unmodified lines)except:pass# Try to extract JSON from markdown blocksjson_match = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', output, re.DOTALL)if json_match:try:4 unmodified lines)except:pass# Try to find "action_type" field with regexaction_pattern = r'"action_type"\s*:\s*"(\w+)"'match = re.search(action_pattern, output)if match:return AgentAction(action_type=match.group(1).lower())# Keyword detection as last resortoutput_lower = output.lower()if "test" in output_lower:return AgentAction("run_tests")2 unmodified linesif "inspect" in output_lower:return AgentAction("inspect")if "doc" in output_lower or "documentation" in output_lower:# Bridge natural language mentions to rltool-backed retrieval action.return AgentAction("query_docs", "bug fix guidance")return AgentAction("invalid", output)def map_to_env(action: AgentAction):9 unmodified linesreturn WriteComment(comment_text=action.content or "")elif action.action_type == "question":return AskQuestion(question=action.content or "")elif action.action_type == "query_docs": # <-- newreturn QueryDocs(query_topic=action.content or "")elif action.action_type == "done":return Done()1 unmodified linereturn Skip()# ======================================================================# 2. MODEL SETUP (stabilised LoRA)# ======================================================================def load_model():model, tokenizer = FastLanguageModel.from_pretrained(model_name="unsloth/gemma-2-2b-it-bnb-4bit",max_seq_length=768,load_in_4bit=True,)# FIXED: Lower rank (16), dropout=0 for stabilitymodel = FastLanguageModel.get_peft_model(model,r=16, # was 64 → causes collapsetarget_modules=["q_proj", "k_proj", "v_proj", "o_proj","gate_proj", "up_proj", "down_proj"],lora_alpha=32, # adjusted for r=16lora_dropout=0.0, # dropout can cause empty outputs)# Ensure tokenizer has correct chat template for Gemma-2if tokenizer.chat_template is None:tokenizer.chat_template = "{{ bos_token }}{% for message in messages %}{% if message['role'] == 'user' %}<start_of_turn>user\n{{ message['content'] }}<end_of_turn>\n<start_of_turn>model\n{% elif message['role'] == 'assistant' %}{{ message['content'] }}<end_of_turn>\n{% endif %}{% endfor %}"return model, tokenizer# ======================================================================# 3. MODEL SANITY CHECK (new – ensures model can generate text)# ======================================================================def test_model_sanity(model, tokenizer) -> bool:print("\n" + "="*60)24 unmodified linesreturn True# ======================================================================# 4. SUPERVISED WARM-UP (teaches JSON output)# ======================================================================def supervised_warmup(model, tokenizer, n_examples=500, epochs=8):print("\n" + "="*60)21 unmodified lines"No previous action",]last_output = random.choice(last_outputs)# Use same prompt structure as build_promptprompt = f"""You are an AI code review agent. Your goal is to convince a simulated human developer to accept your proposed fix.The developer has a **defensive** personality and will only accept if you provide solid evidence:47 unmodified lineslearning_rate=2e-5,logging_steps=50,save_strategy="no",bf16=True,),)print(f"Training on {n_examples} examples for {epochs} epochs...")trainer.train()print("✓ Warm-up complete\n")torch.cuda.empty_cache()# ======================================================================# 5. ACTION GENERATION WITH LOGPROB TRACKING (fixed)# ======================================================================def generate_action_with_logprob(prompt: str,model,tokenizer,temperature: float = 0.0, # changed: greedy by default for stabilitymax_retries: int = 2) -> Tuple[str, float]:"""Generate action using correct chat template, with fallback."""messages = [{"role": "user", "content": prompt}]formatted = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)inputs = tokenizer(formatted, return_tensors="pt", max_length=768, truncation=True).to("cuda")for attempt in range(max_retries):7 unmodified linesreturn_dict_in_generate=True,output_scores=True,)generated_ids = outputs.sequences[0][inputs['input_ids'].shape[1]:]action_text = tokenizer.decode(generated_ids, skip_special_tokens=True).strip()# Compute logproblogprobs = []for idx, token_id in enumerate(generated_ids):if idx < len(outputs.scores):2 unmodified lineslogprobs.append(token_logprob)total_logprob = sum(logprobs) if logprobs else -100.0# If empty, use fallbackif not action_text:fallback_actions = ['{"action_type": "run_tests"}',6 unmodified linesprint(f"[WARN] Empty generation → using fallback: {action_text}")return action_text, total_logprob# Validate JSONtry:json.loads(action_text)return action_text, total_logprob1 unmodified lineif attempt == max_retries - 1:return '{"action_type":"skip"}', -100.0continuereturn '{"action_type":"skip"}', -100.0# ======================================================================# 6. PROMPT BUILDER (unchanged – exactly as you wrote)# ======================================================================def build_prompt(obs, history_lines: List[str]) -> str:author_msg = getattr(obs, "author_response", "") or ""tool_output = getattr(obs, "last_tool_output", "") or ""# Personality hint (optional but helpful)author_personality = getattr(obs, "author_personality", "defensive") # e.g., from envprompt = f"""You are an AI code review agent. Your goal is to convince a simulated human developer to accept your proposed fix and name your proposed fix function fix.32 unmodified linesreturn prompt# ======================================================================# 7. TRAJECTORY STORAGE (unchanged)# ======================================================================@dataclassclass Trajectory:2 unmodified linesrewards: List[float]logprobs: List[float]dones: List[bool]def __len__(self):return len(self.states)def to_dict(self):return {"states": self.states,"actions": self.actions,"rewards": self.rewards,"logprobs": self.logprobs,"dones": self.dones,}# ======================================================================# 8. ROLLOUT COLLECTION (uses fixed generate)# ======================================================================def collect_trajectory(env: CodeReviewEnv,model,tokenizer,max_steps: int = 10,temperature: float = 0.0 # changed to greedy) -> Trajectory:obs = env.reset()history_lines = []states = []actions = []rewards = []logprobs = []dones = []for step in range(max_steps):prompt = build_prompt(obs, history_lines)states.append(prompt)action_text, logprob = generate_action_with_logprob(prompt, model, tokenizer, temperature)actions.append(action_text)logprobs.append(logprob)action = parse_action(action_text)env_action = map_to_env(action)next_obs, reward, done, _ = env.step(env_action)rewards.append(reward.value)dones.append(done)history_lines.append(f"Agent: {action_text}")history_lines.append(f"Env: {next_obs.last_tool_output}")obs = next_obsif done:breakreturn Trajectory(states, actions, rewards, logprobs, dones)def collect_trajectories(env: CodeReviewEnv,model,tokenizer,n_trajectories: int,max_steps: int = 10,task_levels: Optional[List[str]] = None,task_weights: Optional[List[float]] = None,) -> List[Trajectory]:# Link training to RedTeam's full bug distribution by sampling tasks# per trajectory instead of training only on env default ("easy").if task_levels is None:task_levels = list(BUG_DB.keys())if task_weights is not None and len(task_weights) != len(task_levels):raise ValueError("task_weights must match task_levels length")if task_weights is not None and sum(task_weights) <= 0:raise ValueError("task_weights must have a positive total")trajectories = []for i in range(n_trajectories):# Weighted sampling supports curriculum-style training schedules.sampled_task = random.choices(task_levels, weights=task_weights, k=1)[0]env.set_task(sampled_task)traj = collect_trajectory(env, model, tokenizer, max_steps)total_reward = sum(traj.rewards)print(f"Trajectory {i+1}/{n_trajectories}: "f"task={sampled_task}, steps={len(traj)}, reward={total_reward:.3f}")trajectories.append(traj)return trajectories# ======================================================================# 9. ADVANTAGE ESTIMATION (unchanged)# ======================================================================def compute_returns_and_advantages(rewards: List[float],dones: List[bool],gamma: float = 0.99,standardize: bool = True) -> Tuple[List[float], List[float]]:"""Computes discounted returns and normalised advantages (no critic).Advantages = returns - mean(returns) (or zero baseline)."""n = len(rewards)returns = [0.0] * nrunning_return = 0.0for t in reversed(range(n)):if dones[t]:running_return = 0.0running_return = rewards[t] + gamma * running_returnreturns[t] = running_returnif standardize:advantages = np.array(returns) - np.mean(returns)adv_std = np.std(advantages) + 1e-8advantages = (advantages / adv_std).tolist()else:advantages = returns.copy()return advantages, returns# ======================================================================# 10. COMPUTE NEW LOGPROBS (unchanged)# ======================================================================def compute_logprob(prompt: str, action: str, model, tokenizer) -> float:messages = [{"role": "user", "content": prompt}]formatted = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)full_text = formatted + actioninputs = tokenizer(formatted, return_tensors="pt", max_length=768, truncation=True).to("cuda")with torch.no_grad():outputs = model(**inputs)logits = outputs.logitsaction_ids = tokenizer.encode(action, add_special_tokens=False)prefix_ids = tokenizer.encode(formatted, add_special_tokens=False)action_start = len(prefix_ids)logprobs = []for idx, token_id in enumerate(action_ids):position = action_start + idx - 13 unmodified lineslogprobs.append(token_logprob)return sum(logprobs) if logprobs else -100.0# ======================================================================# 11. PPO UPDATE (unchanged except uses compute_logprob correctly)# ======================================================================def ppo_update(trajectories: List[Trajectory],model,tokenizer,optimizer,n_epochs: int = 4,clip_epsilon: float = 0.2,entropy_coef: float = 0.01,gamma: float = 0.99,) -> Dict[str, float]:model.train()all_states = []all_actions = []all_old_logprobs = []all_advantages = []all_returns = []for traj in trajectories:advantages, returns = compute_returns_and_advantages(traj.rewards, traj.dones, gamma=gamma, standardize=True)all_states.extend(traj.states)all_actions.extend(traj.actions)all_old_logprobs.extend(traj.logprobs)all_advantages.extend(advantages)all_returns.extend(returns)n_samples = len(all_states)total_loss = 0.0total_policy_loss = 0.0total_entropy = 0.0n_updates = 0for epoch in range(n_epochs):indices = np.random.permutation(n_samples)for i in indices:1 unmodified lineaction = all_actions[i]old_logprob = all_old_logprobs[i]advantage = all_advantages[i]# Use the same chat template for PPO updatemessages = [{"role": "user", "content": state}]formatted = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)full_text = formatted + actioninputs = tokenizer(full_text, return_tensors="pt", max_length=768, truncation=True).to("cuda")outputs = model(**inputs)logits = outputs.logitsaction_ids = tokenizer.encode(action, add_special_tokens=False)prefix_ids = tokenizer.encode(formatted, add_special_tokens=False)action_start = len(prefix_ids)logprobs = []entropy = 0.0for idx, token_id in enumerate(action_ids):3 unmodified lineslog_probs = F.log_softmax(token_logits, dim=-1)token_logprob = log_probs[token_id]logprobs.append(token_logprob)probs = F.softmax(token_logits, dim=-1)entropy += -(probs * log_probs).sum()if not logprobs:continuenew_logprob = sum(logprobs)avg_entropy = entropy / len(logprobs) if logprobs else 0.0ratio = torch.exp(new_logprob - old_logprob)surr1 = ratio * advantagesurr2 = torch.clamp(ratio, 1 - clip_epsilon, 1 + clip_epsilon) * advantagepolicy_loss = -torch.min(surr1, surr2)loss = policy_loss - entropy_coef * avg_entropyoptimizer.zero_grad()loss.backward()torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)optimizer.step()total_loss += loss.item()total_policy_loss += policy_loss.item()total_entropy += avg_entropy.item()n_updates += 1return {"loss": total_loss / n_updates if n_updates > 0 else 0.0,"policy_loss": total_policy_loss / n_updates if n_updates > 0 else 0.0,"entropy": total_entropy / n_updates if n_updates > 0 else 0.0,}# ======================================================================# 12. EVALUATION (unchanged)# ======================================================================def evaluate_policy(env: CodeReviewEnv,model,tokenizer,n_episodes: int = 10,max_steps: int = 10) -> Dict[str, float]:model.eval()total_rewards = []episode_lengths = []success_count = 0for _ in range(n_episodes):traj = collect_trajectory(env, model, tokenizer, max_steps, temperature=0.0)total_reward = sum(traj.rewards)total_rewards.append(total_reward)episode_lengths.append(len(traj))if total_reward > 0.5:success_count += 1return {"avg_reward": np.mean(total_rewards),"std_reward": np.std(total_rewards),"avg_length": np.mean(episode_lengths),"success_rate": success_count / n_episodes,}# ======================================================================# 13. MAIN TRAINING LOOP (added sanity check and warm-up)# ======================================================================def train_ppo(n_iterations: int = 50,trajectories_per_iter: int = 10,n_epochs: int = 2,max_steps: int = 10,learning_rate: float = 3e-5,clip_epsilon: float = 0.2,entropy_coef: float = 0.01,gamma: float = 0.99,eval_every: int = 5,task_levels: Optional[List[str]] = None,curriculum_weighted_sampling: bool = True,reward_profile: str = "full",):print("Loading model...")model, tokenizer = load_model()# NEW: Sanity check before any trainingif not test_model_sanity(model, tokenizer):print("\n❌ Model sanity check failed – cannot proceed.")return# NEW: Supervised warm-up to teach JSON format (500 steps with epochs=8)supervised_warmup(model, tokenizer, n_examples=500, epochs=8)optimizer = AdamW(model.parameters(), lr=learning_rate)env = CodeReviewEnv()if task_levels is None:task_levels = list(BUG_DB.keys())print(f"\n{'='*60}")print(f"Starting PPO Training")print(f"Iterations: {n_iterations}")print(f"Trajectories per iteration: {trajectories_per_iter}")print(f"PPO epochs: {n_epochs}")print(f"Reward profile: {reward_profile}")print(f"{'='*60}\n")reward_history: List[float] = []loss_history: List[float] = []for iteration in range(n_iterations):print(f"\n--- Iteration {iteration + 1}/{n_iterations} ---")# Optional weighted curriculum:# start with easier tasks and smoothly ramp difficulty over training.if curriculum_weighted_sampling:progress = (iteration + 1) / max(n_iterations, 1)easy_w = max(0.15, 0.55 - 0.40 * progress)1 unmodified linehard_w = 0.10 + 0.05 * progressharder_w = 0.05 + 0.20 * progresshardest_w = 0.05 + 0.25 * progresstask_weight_map = {"easy": easy_w,"medium": medium_w,"hard": hard_w,"harder": harder_w,"hardest": hardest_w,}task_weights = [task_weight_map.get(level, 1.0) for level in task_levels]else:task_weights = Noneprint("Collecting trajectories...")trajectories = collect_trajectories(env,model,tokenizer,trajectories_per_iter,max_steps,task_levels=task_levels,task_weights=task_weights,)avg_reward = np.mean([sum(t.rewards) for t in trajectories])avg_length = np.mean([len(t) for t in trajectories])reward_history.append(float(avg_reward))print(f"Avg reward: {avg_reward:.3f}")print(f"Avg length: {avg_length:.1f}")print("Updating policy...")metrics = ppo_update(trajectories,model,tokenizer,optimizer,n_epochs=n_epochs,clip_epsilon=clip_epsilon,entropy_coef=entropy_coef,gamma=gamma,)print(f"Loss: {metrics['loss']:.4f}")print(f"Policy loss: {metrics['policy_loss']:.4f}")print(f"Entropy: {metrics['entropy']:.4f}")loss_history.append(float(metrics["loss"]))if (iteration + 1) % eval_every == 0:print("\nEvaluating policy...")eval_metrics = evaluate_policy(env, model, tokenizer, n_episodes=10)print(f"Eval avg reward: {eval_metrics['avg_reward']:.3f} ± {eval_metrics['std_reward']:.3f}")print(f"Eval success rate: {eval_metrics['success_rate']:.2%}")print(f"Eval avg length: {eval_metrics['avg_length']:.1f}")print("\n" + "="*60)print("Training complete. Saving model...")model.save_pretrained("ppo_final_model")tokenizer.save_pretrained("ppo_final_model")print("Model saved to ppo_final_model/")# Save training curves for quick before/after comparisons.if reward_history:plt.figure(figsize=(8, 4))plt.plot(range(1, len(reward_history) + 1), reward_history, marker="o")plt.title("Average Reward per Iteration")plt.xlabel("Iteration")plt.ylabel("Average Reward")plt.grid(alpha=0.3)plt.tight_layout()plt.savefig("reward_curve.png", dpi=150)plt.close()if loss_history:plt.figure(figsize=(8, 4))plt.plot(range(1, len(loss_history) + 1), loss_history, marker="o", color="tab:red")plt.title("Training Loss per Iteration")plt.xlabel("Iteration")plt.ylabel("Loss")plt.grid(alpha=0.3)plt.tight_layout()plt.savefig("loss_curve.png", dpi=150)plt.close()if os.path.exists("reward_curve.png") and os.path.exists("loss_curve.png"):print("Saved reward_curve.png and loss_curve.png")print("="*60)# ======================================================================# 14. ENTRY POINT (unchanged)# ======================================================================if __name__ == "__main__":train_ppo(n_iterations=30,123413 unmodified lines18192021222324252627282930313233341 unmodified line3637383940412 unmodified lines4445464748494 unmodified lines545556575859606162632 unmodified lines666768697071729 unmodified lines828384858687881 unmodified line9091929394959697989910010110210310410510610710810911011111211311411511611711824 unmodified lines14314414514614714814921 unmodified lines17117217317417517647 unmodified lines2242252262272282292302312322332342352362372382392402412422432442452462472482492507 unmodified lines2582592602612622632642652662 unmodified lines2692702712722732746 unmodified lines2812822832842852861 unmodified line28828929029129229329429529629729829930030130232 unmodified lines3353363373383393403412 unmodified lines3443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174183 unmodified lines4224234244254264274284294304314324334344354364374384394401 unmodified line4424434444454464474484494504514524534544554563 unmodified lines4604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335341 unmodified line536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581# training.py – Refactored for Phi-3-mini-4k-instruct (no Flash-Attn required)import torch._dynamotorch._dynamo.config.disable = Trueimport json13 unmodified linesfrom trl import SFTTrainerfrom datasets import Dataset# Import your environment and actionsfrom environment import CodeReviewEnvfrom redteam import BUG_DBfrom models import (RunTests, RunLinter, Inspect,ProposeFix, WriteComment, AskQuestion,Done, Skip, QueryDocs)# ======================================================================# 1. ACTION PARSING (unchanged)# ======================================================================@dataclassclass AgentAction:1 unmodified linecontent: Optional[str] = Nonedef parse_action(output: str) -> AgentAction:try:data = json.loads(output)return AgentAction(2 unmodified lines)except:passjson_match = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', output, re.DOTALL)if json_match:try:4 unmodified lines)except:passaction_pattern = r'"action_type"\s*:\s*"(\w+)"'match = re.search(action_pattern, output)if match:return AgentAction(action_type=match.group(1).lower())output_lower = output.lower()if "test" in output_lower:return AgentAction("run_tests")2 unmodified linesif "inspect" in output_lower:return AgentAction("inspect")if "doc" in output_lower or "documentation" in output_lower:return AgentAction("query_docs", "bug fix guidance")return AgentAction("invalid", output)def map_to_env(action: AgentAction):9 unmodified linesreturn 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()1 unmodified linereturn Skip()# ======================================================================# 2. MODEL SETUP (Phi‑3‑mini, no Flash‑Attn needed)# ======================================================================def load_model():model, tokenizer = FastLanguageModel.from_pretrained(model_name="unsloth/Phi-3-mini-4k-instruct-bnb-4bit",max_seq_length=2048, # full 4k context, we still truncate inputs for memoryload_in_4bit=True,)model = FastLanguageModel.get_peft_model(model,r=16,target_modules=["q_proj", "k_proj", "v_proj", "o_proj","gate_proj", "up_proj", "down_proj"],lora_alpha=32,lora_dropout=0.0,)# Unsloth already sets the correct chat template for Phi-3; do not override it.return model, tokenizer# ======================================================================# 3. MODEL SANITY CHECK# ======================================================================def test_model_sanity(model, tokenizer) -> bool:print("\n" + "="*60)24 unmodified linesreturn True# ======================================================================# 4. SUPERVISED WARM-UP (unchanged except prompt uses safe variables)# ======================================================================def supervised_warmup(model, tokenizer, n_examples=500, epochs=8):print("\n" + "="*60)21 unmodified lines"No previous action",]last_output = random.choice(last_outputs)prompt = f"""You are an AI code review agent. Your goal is to convince a simulated human developer to accept your proposed fix.The developer has a **defensive** personality and will only accept if you provide solid evidence:47 unmodified lineslearning_rate=2e-5,logging_steps=50,save_strategy="no",bf16=True, # Phi‑3 on A10G uses bfloat16),)print(f"Training on {n_examples} examples for {epochs} epochs...")trainer.train()print("✓ Warm-up complete\n")torch.cuda.empty_cache()# ======================================================================# 5. ACTION GENERATION (truncation added)# ======================================================================def generate_action_with_logprob(prompt: str,model,tokenizer,temperature: float = 0.0,max_retries: int = 2) -> Tuple[str, float]:messages = [{"role": "user", "content": prompt}]formatted = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)# Keep prompt length under controlinputs = tokenizer(formatted, return_tensors="pt", max_length=768, truncation=True).to("cuda")for attempt in range(max_retries):7 unmodified linesreturn_dict_in_generate=True,output_scores=True,)generated_ids = outputs.sequences[0][inputs['input_ids'].shape[1]:]action_text = tokenizer.decode(generated_ids, skip_special_tokens=True).strip()logprobs = []for idx, token_id in enumerate(generated_ids):if idx < len(outputs.scores):2 unmodified lineslogprobs.append(token_logprob)total_logprob = sum(logprobs) if logprobs else -100.0if not action_text:fallback_actions = ['{"action_type": "run_tests"}',6 unmodified linesprint(f"[WARN] Empty generation → using fallback: {action_text}")return action_text, total_logprobtry:json.loads(action_text)return action_text, total_logprob1 unmodified lineif attempt == max_retries - 1:return '{"action_type":"skip"}', -100.0continuereturn '{"action_type":"skip"}', -100.0# ======================================================================# 6. PROMPT BUILDER (unchanged)# ======================================================================def build_prompt(obs, history_lines: List[str]) -> str:author_msg = getattr(obs, "author_response", "") or ""tool_output = getattr(obs, "last_tool_output", "") or ""author_personality = getattr(obs, "author_personality", "defensive")prompt = f"""You are an AI code review agent. Your goal is to convince a simulated human developer to accept your proposed fix and name your proposed fix function fix.32 unmodified linesreturn prompt# ======================================================================# 7-12: Trajectory, Rollout, Advantage, Logprob, PPO Update, Eval (unchanged except added truncation in ppo_update)# ======================================================================@dataclassclass Trajectory:2 unmodified linesrewards: List[float]logprobs: List[float]dones: List[bool]def __len__(self): return len(self.states)def to_dict(self): return {"states": self.states, "actions": self.actions, "rewards": self.rewards, "logprobs": self.logprobs, "dones": self.dones}def collect_trajectory(env, model, tokenizer, max_steps=10, temperature=0.0):obs = env.reset()history_lines = []states, actions, rewards, logprobs, dones = [], [], [], [], []for step in range(max_steps):prompt = build_prompt(obs, history_lines)states.append(prompt)action_text, logprob = generate_action_with_logprob(prompt, model, tokenizer, temperature)actions.append(action_text)logprobs.append(logprob)action = parse_action(action_text)env_action = map_to_env(action)next_obs, reward, done, _ = env.step(env_action)rewards.append(reward.value)dones.append(done)history_lines.append(f"Agent: {action_text}")history_lines.append(f"Env: {next_obs.last_tool_output}")obs = next_obsif done: breakreturn Trajectory(states, actions, rewards, logprobs, dones)def collect_trajectories(env, model, tokenizer, n_trajectories, max_steps=10,task_levels=None, task_weights=None):if task_levels is None:task_levels = list(BUG_DB.keys())if task_weights is not None and len(task_weights) != len(task_levels):raise ValueError("task_weights must match task_levels length")if task_weights is not None and sum(task_weights) <= 0:raise ValueError("task_weights must have a positive total")trajectories = []for i in range(n_trajectories):sampled_task = random.choices(task_levels, weights=task_weights, k=1)[0]env.set_task(sampled_task)traj = collect_trajectory(env, model, tokenizer, max_steps)total_reward = sum(traj.rewards)print(f"Trajectory {i+1}/{n_trajectories}: task={sampled_task}, steps={len(traj)}, reward={total_reward:.3f}")trajectories.append(traj)return trajectoriesdef compute_returns_and_advantages(rewards, dones, gamma=0.99, standardize=True):n = len(rewards)returns = [0.0]*nrunning = 0.0for t in reversed(range(n)):if dones[t]: running = 0.0running = rewards[t] + gamma * runningreturns[t] = runningif standardize:advantages = np.array(returns) - np.mean(returns)adv_std = np.std(advantages) + 1e-8advantages = (advantages / adv_std).tolist()else:advantages = returns.copy()return advantages, returnsdef compute_logprob(prompt, action, model, tokenizer):messages = [{"role": "user", "content": prompt}]formatted = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)full_text = formatted + actioninputs = tokenizer(full_text, return_tensors="pt").to("cuda")with torch.no_grad():outputs = model(**inputs)logits = outputs.logitsaction_ids = tokenizer.encode(action, add_special_tokens=False)prefix_ids = tokenizer.encode(formatted, add_special_tokens=False)action_start = len(prefix_ids)logprobs = []for idx, token_id in enumerate(action_ids):position = action_start + idx - 13 unmodified lineslogprobs.append(token_logprob)return sum(logprobs) if logprobs else -100.0def ppo_update(trajectories, model, tokenizer, optimizer, n_epochs=4, clip_epsilon=0.2,entropy_coef=0.01, gamma=0.99):model.train()all_states, all_actions, all_old_logprobs, all_advantages, all_returns = [], [], [], [], []for traj in trajectories:advantages, returns = compute_returns_and_advantages(traj.rewards, traj.dones, gamma=gamma, standardize=True)all_states.extend(traj.states)all_actions.extend(traj.actions)all_old_logprobs.extend(traj.logprobs)all_advantages.extend(advantages)all_returns.extend(returns)n_samples = len(all_states)total_loss, total_policy_loss, total_entropy, n_updates = 0.0, 0.0, 0.0, 0for epoch in range(n_epochs):indices = np.random.permutation(n_samples)for i in indices:1 unmodified lineaction = all_actions[i]old_logprob = all_old_logprobs[i]advantage = all_advantages[i]messages = [{"role": "user", "content": state}]formatted = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)full_text = formatted + actioninputs = tokenizer(full_text, return_tensors="pt", max_length=768, truncation=True).to("cuda")outputs = model(**inputs)logits = outputs.logitsaction_ids = tokenizer.encode(action, add_special_tokens=False)prefix_ids = tokenizer.encode(formatted, add_special_tokens=False)action_start = len(prefix_ids)logprobs = []entropy = 0.0for idx, token_id in enumerate(action_ids):3 unmodified lineslog_probs = F.log_softmax(token_logits, dim=-1)token_logprob = log_probs[token_id]logprobs.append(token_logprob)probs = F.softmax(token_logits, dim=-1)entropy += -(probs * log_probs).sum()if not logprobs: continuenew_logprob = sum(logprobs)avg_entropy = entropy / len(logprobs) if logprobs else 0.0ratio = torch.exp(new_logprob - old_logprob)surr1 = ratio * advantagesurr2 = torch.clamp(ratio, 1 - clip_epsilon, 1 + clip_epsilon) * advantagepolicy_loss = -torch.min(surr1, surr2)loss = policy_loss - entropy_coef * avg_entropyoptimizer.zero_grad()loss.backward()torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)optimizer.step()total_loss += loss.item()total_policy_loss += policy_loss.item()total_entropy += avg_entropy.item()n_updates += 1return {"loss": total_loss / n_updates if n_updates else 0.0,"policy_loss": total_policy_loss / n_updates if n_updates else 0.0,"entropy": total_entropy / n_updates if n_updates else 0.0}def evaluate_policy(env, model, tokenizer, n_episodes=10, max_steps=10):model.eval()total_rewards, episode_lengths, success_count = [], [], 0for _ in range(n_episodes):traj = collect_trajectory(env, model, tokenizer, max_steps, temperature=0.0)total_reward = sum(traj.rewards)total_rewards.append(total_reward)episode_lengths.append(len(traj))if total_reward > 0.5: success_count += 1return {"avg_reward": np.mean(total_rewards),"std_reward": np.std(total_rewards),"avg_length": np.mean(episode_lengths),"success_rate": success_count / n_episodes}# ======================================================================# 13. MAIN TRAINING LOOP# ======================================================================def train_ppo(n_iterations=30,trajectories_per_iter=10,n_epochs=4,max_steps=10,learning_rate=3e-5,clip_epsilon=0.2,entropy_coef=0.01,gamma=0.99,eval_every=5,task_levels=None,curriculum_weighted_sampling=True,):print("Loading model...")model, tokenizer = load_model()if not test_model_sanity(model, tokenizer):print("\n❌ Model sanity check failed – cannot proceed.")returnsupervised_warmup(model, tokenizer, n_examples=500, epochs=8)optimizer = AdamW(model.parameters(), lr=learning_rate)env = CodeReviewEnv()if task_levels is None:task_levels = list(BUG_DB.keys())print(f"\n{'='*60}")print("Starting PPO Training")print(f"Iterations: {n_iterations}, Trajectories per iter: {trajectories_per_iter}, PPO epochs: {n_epochs}")print(f"{'='*60}\n")reward_history, loss_history = [], []for iteration in range(n_iterations):print(f"\n--- Iteration {iteration + 1}/{n_iterations} ---")if curriculum_weighted_sampling:progress = (iteration + 1) / max(n_iterations, 1)easy_w = max(0.15, 0.55 - 0.40 * progress)1 unmodified linehard_w = 0.10 + 0.05 * progressharder_w = 0.05 + 0.20 * progresshardest_w = 0.05 + 0.25 * progresstask_weight_map = {"easy": easy_w, "medium": medium_w, "hard": hard_w, "harder": harder_w, "hardest": hardest_w}task_weights = [task_weight_map.get(level, 1.0) for level in task_levels]else:task_weights = Noneprint("Collecting trajectories...")trajectories = collect_trajectories(env, model, tokenizer, trajectories_per_iter, max_steps,task_levels=task_levels, task_weights=task_weights)avg_reward = np.mean([sum(t.rewards) for t in trajectories])avg_length = np.mean([len(t) for t in trajectories])reward_history.append(float(avg_reward))print(f"Avg reward: {avg_reward:.3f}, Avg length: {avg_length:.1f}")print("Updating policy...")metrics = ppo_update(trajectories, model, tokenizer, optimizer,n_epochs=n_epochs, clip_epsilon=clip_epsilon, entropy_coef=entropy_coef, gamma=gamma)print(f"Loss: {metrics['loss']:.4f}, Policy loss: {metrics['policy_loss']:.4f}, Entropy: {metrics['entropy']:.4f}")loss_history.append(float(metrics["loss"]))if (iteration + 1) % eval_every == 0:print("\nEvaluating policy...")eval_metrics = evaluate_policy(env, model, tokenizer, n_episodes=10)print(f"Eval avg reward: {eval_metrics['avg_reward']:.3f} ± {eval_metrics['std_reward']:.3f}")print(f"Eval success rate: {eval_metrics['success_rate']:.2%}, Eval avg length: {eval_metrics['avg_length']:.1f}")print("\n" + "="*60)print("Training complete. Saving model...")model.save_pretrained("ppo_final_model")tokenizer.save_pretrained("ppo_final_model")print("Model saved to ppo_final_model/")if reward_history:plt.figure(figsize=(8,4))plt.plot(range(1, len(reward_history)+1), reward_history, marker="o")plt.title("Average Reward per Iteration"); plt.xlabel("Iteration"); plt.ylabel("Average Reward")plt.grid(alpha=0.3); plt.tight_layout(); plt.savefig("reward_curve.png", dpi=150); plt.close()if loss_history:plt.figure(figsize=(8,4))plt.plot(range(1, len(loss_history)+1), loss_history, marker="o", color="tab:red")plt.title("Training Loss per Iteration"); plt.xlabel("Iteration"); plt.ylabel("Loss")plt.grid(alpha=0.3); plt.tight_layout(); plt.savefig("loss_curve.png", dpi=150); plt.close()if os.path.exists("reward_curve.png") and os.path.exists("loss_curve.png"):print("Saved reward_curve.png and loss_curve.png")print("="*60)if __name__ == "__main__":train_ppo(n_iterations=30,
training.py+89-292