Spaces:
Sleeping
Sleeping
Update training.py
Browse files123456789104 unmodified lines1516171819202122232425262746 unmodified lines747576777879808182838485868788899091929394959697981 unmodified line10010110210310410510616 unmodified lines12312412512612712812913013113225 unmodified lines15815916016116216316432 unmodified lines1971981992002012022033 unmodified lines2072082092102112122132142152168 unmodified lines2252262272282292302313 unmodified lines2352362372382392402412422432442452461 unmodified line2482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403412 unmodified lines3443453463473483493501 unmodified line3523533543553563573585 unmodified lines3643653663673683693703 unmodified lines37437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043134 unmodified lines46646746846947047147247347447531 unmodified lines50750850951051151251313 unmodified lines52752852953053153253353413 unmodified lines5485495505515525535545555565575585593 unmodified lines5635645655665675685695705715729 unmodified lines5825835845855865875885895905915925935945955961 unmodified line5985996006016026036044 unmodified lines6096106116126136146154 unmodified lines6206216226236246256266276286296306316326336343 unmodified lines63863964064164264364464564664764864965029 unmodified lines6806816826836846856866876886896901 unmodified line6926936946956966976986997007017027037047057067077087097107117127137148 unmodified lines7237247257267277287297307317327337347357367377387397408 unmodified lines7497507517527537547557567577587597607617627637647657667677687697707717727732 unmodified lines7767777787797807817827837847857867877887897907917927937947952 unmodified lines79879980080180280380480580625 unmodified lines8328338348358368378388398408418428438448458468478488498508518528538548558568578583 unmodified lines862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936# training.py – Memory‑safe: Phi‑3‑mini + Expert Demos + Fast PPO (2 iterations)import osos.environ["TRITON_DISABLE"] = "1"os.environ["TOKENIZERS_PARALLELISM"] = "false"import torch._dynamotorch._dynamo.config.disable = Trueimport jsonimport torchimport torch.nn.functional as F4 unmodified linesimport reimport randomimport matplotlibmatplotlib.use('Agg') # ← add this lineimport matplotlib.pyplot as pltfrom unsloth import FastLanguageModelfrom transformers import TrainingArgumentsfrom trl import SFTTrainerfrom datasets import Datasetfrom environment import CodeReviewEnvfrom redteam import BUG_DB46 unmodified linesdef 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,load_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,)return model, tokenizerdef test_model_sanity(model, tokenizer) -> bool:print("\n" + "="*60)print("SANITY CHECK: Testing base model generation")1 unmodified linetest_prompt = "Hello, how are you?"messages = [{"role": "user", "content": test_prompt}]formatted = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)inputs = tokenizer(formatted, return_tensors="pt", max_length=2048, truncation=True).to("cuda")with torch.no_grad():outputs = model.generate(**inputs,16 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 ""25 unmodified lines" 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"32 unmodified lines" return True")# Generic safe fallback keeps the RL pipeline alive for unknown bugs.return ("def fix(data):\n"" if data is None:\n"3 unmodified linesdef _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(3 unmodified lines})# 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.")returndataset = Dataset.from_list(examples)trainer = SFTTrainer(model=model,tokenizer=tokenizer,train_dataset=dataset,dataset_text_field="text",max_seq_length=2048,args=TrainingArguments(output_dir="warmup_output",num_train_epochs=epochs,per_device_train_batch_size=2,gradient_accumulation_steps=2,learning_rate=2e-5,logging_steps=50,save_strategy="no",bf16=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()# ======================================================================def generate_action_with_logprob(prompt, model, tokenizer, temperature=0.0, max_retries=2):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=2048, truncation=True).to("cuda")for attempt in range(max_retries):with torch.no_grad():outputs = model.generate(**inputs,max_new_tokens=64,do_sample=(temperature > 0),temperature=max(temperature, 0.01) if temperature > 0 else 1.0,min_new_tokens=1,2 unmodified lines)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):1 unmodified linetoken_logprob = F.log_softmax(token_logits, dim=-1)[token_id].item()logprobs.append(token_logprob)total_logprob = sum(logprobs) if logprobs else -100.0if not action_text:fallback_actions = ['{"action_type": "run_tests"}',5 unmodified linestotal_logprob = -50.0print(f"[WARN] Empty generation → using fallback: {action_text}")return action_text, total_logprobtry:json.loads(action_text)return action_text, total_logprob3 unmodified linescontinuereturn '{"action_type":"skip"}', -100.0# ======================================================================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.The developer has a **{author_personality}** personality and will only accept if you provide solid evidence:- Tests pass (high pass ratio)- Lint is clean (zero errors)- Documentation or references are provided- Your reasoning is clear, uses words like "because" or "therefore", and is detailed (over 30 words if needed)Workflow:1. Use `inspect` to understand the code.2. Use `run_tests` and `run_linter` to gather evidence.3. Use `query_docs` when you need references or language-specific guidance.4. Propose a fix (`fix`) and explain why it works (`comment` or `question`).5. If the developer pushes back, read their response carefully and address their specific concern.6. Once convinced, use `done` to finish.Code:{obs.code_snippet}Author says:{author_msg if author_msg else "(no response yet – start with inspection)"}Last tool output:{tool_output if tool_output else "(none)"}Available actions:run_tests, run_linter, inspect, query_docs, fix, comment, question, doneRespond ONLY in JSON:{{"action_type": "...", "content": "..."}}"""if history_lines:history = "\n".join(history_lines[-6:])prompt += f"\n\nPrevious steps:\n{history}"return prompt# ======================================================================@dataclassclass Trajectory:states: List[str]actions: List[str]rewards: List[float]logprobs: List[float]dones: List[bool]def __len__(self): return len(self.states)def collect_trajectory(env, model, tokenizer, max_steps=6, temperature=0.0):obs = env.reset()history_lines = []34 unmodified linesreturn trajectoriesdef compute_returns_and_advantages(rewards, dones, gamma=0.99, standardize=True):"""Compute discounted returns and REINFORCE-style baseline advantages.Advantages are centered and optionally standardised."""n = len(rewards)returns = [0.0]*nrunning = 0.031 unmodified linesmessages = [{"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=2048, truncation=True).to("cuda")outputs = model(**inputs)logits = outputs.logitsaction_ids = tokenizer.encode(action, add_special_tokens=False)13 unmodified linesif not logprobs: continuenew_logprob = sum(logprobs)avg_entropy = entropy / len(logprobs) if logprobs else 0.0log_ratio = torch.clamp(new_logprob - old_logprob, min=-10.0, max=10.0) # ← guardratio = torch.exp(log_ratio)surr1 = ratio * advantagesurr2 = torch.clamp(ratio, 1 - clip_epsilon, 1 + clip_epsilon) * advantagepolicy_loss = -torch.min(surr1, surr2)13 unmodified linesdef evaluate_policy(env, model, tokenizer, n_episodes=3, max_steps=6,task_levels=None, verbose=False):"""Evaluate the current policy across task levels. Returns metrics + optional traces."""model.eval()if task_levels is None:task_levels = list(BUG_DB.keys())total_rewards = []traces = [] # human-readable behavior logsfor ep in range(n_episodes):task = task_levels[ep % len(task_levels)]env.set_task(task)3 unmodified linesif verbose:actions_taken = []for a in traj.actions:try:actions_taken.append(json.loads(a).get("action_type", "?"))except Exception:actions_taken.append("?")traces.append({"task": task,"reward": round(ep_reward, 4),9 unmodified lines}# ======================================================================# MANUAL WARM-UP (no SFTTrainer → no multiprocessing OOM)# ======================================================================def json_warmup(model, tokenizer, json_path="training_data.json",n_episodes=20, epochs=2, lr=2e-5):"""Supervised warm-up from pre-generated expert demonstrations.Uses raw cross-entropy on action tokens with manual gradient steps.NO SFTTrainer, NO multiprocessing – runs safely on any GPU."""print("\n" + "="*60)print("SUPERVISED WARM-UP: training_data.json (manual cross-entropy)")print("="*60)1 unmodified linewith open(json_path, encoding="utf-8") as f:data = json.load(f)# Each episode = 7 steps. Select n_episodes worth.steps_per_episode = 7max_examples = n_episodes * steps_per_episodeif max_examples < len(data):4 unmodified linesmodel.train()warmup_opt = AdamW(model.parameters(), lr=lr)warmup_losses = [] # per-epoch avg lossfor epoch in range(epochs):random.shuffle(data)4 unmodified linesprompt = example["prompt"]action = example["action"]# ---- tokenize full sequence (prompt + action) ----messages = [{"role": "user", "content": prompt},{"role": "assistant", "content": action},]full_text = tokenizer.apply_chat_template(messages, tokenize=False)inputs = tokenizer(full_text, return_tensors="pt", max_length=2048, truncation=True).to("cuda")# ---- find where the action tokens start ----prompt_only = tokenizer.apply_chat_template([{"role": "user", "content": prompt}],tokenize=False, add_generation_prompt=True3 unmodified linestotal_len = inputs.input_ids.shape[1]if prompt_len >= total_len:continue # prompt was truncated away, skip# ---- cross-entropy on action tokens only ----outputs = model(**inputs)logits = outputs.logits# next-token prediction: logits[t] predicts token[t+1]shift_logits = logits[0, prompt_len - 1 : total_len - 1]shift_labels = inputs.input_ids[0, prompt_len : total_len]29 unmodified lines# ======================================================================# MAIN TRAINING PIPELINE# ======================================================================def train_ppo():# --- Hyperparameters ---n_iterations = 15 # enough for a clear upward trendtrajectories_per_iter = 6 # on-policy data per iterationn_epochs = 2max_steps = 8learning_rate = 3e-51 unmodified lineentropy_coef = 0.01gamma = 0.99# --- Pre-load embedder before LLM (Issue #13) ---from rltool import ToolBoxprint("Pre-loading sentence-transformer embedder...")ToolBox._get_embedder()print("✓ Embedder ready")# --- Load model ---print("Loading model...")model, tokenizer = load_model()if not test_model_sanity(model, tokenizer):returnenv = CodeReviewEnv()task_levels = list(BUG_DB.keys())# ==================================================================# PHASE 0: BASELINE (untrained policy)# ==================================================================print("\n" + "="*60)print("PHASE 0 – BASELINE EVALUATION (untrained)")print("="*60)8 unmodified linesprint(f" task={t['task']:8s} reward={t['reward']:+.4f} "f"steps={t['steps']} actions={t['actions']}")# ==================================================================# PHASE 1: SUPERVISED WARM-UP (expert demos, manual CE)# ==================================================================warmup_losses = json_warmup(model, tokenizer,json_path="training_data.json",n_episodes=30, # 140 examples (20 × 7 steps)epochs=3,lr=2e-5,)# Post-warmup evaluationprint("="*60)print("POST WARM-UP EVALUATION")print("="*60)8 unmodified linesprint(f" task={t['task']:8s} reward={t['reward']:+.4f} "f"steps={t['steps']} actions={t['actions']}")# ==================================================================# PHASE 2: TRUE RL – PPO (on-policy, real environment interaction)# ==================================================================optimizer = AdamW(model.parameters(), lr=learning_rate)print(f"\n{'='*60}")print(f"PHASE 2 – PPO TRAINING: {n_iterations} iterations × "f"{trajectories_per_iter} trajectories (true RL)")print(f"{'='*60}\n")reward_history = []eval_history = []loss_history = []policy_loss_history = []entropy_history = []for iteration in range(n_iterations):print(f"\n--- PPO Iteration {iteration + 1}/{n_iterations} ---")# Collect on-policy trajectories from REAL environmenttrajectories = collect_trajectories(env, model, tokenizer, trajectories_per_iter, max_steps,task_levels=task_levels, task_weights=None2 unmodified linesreward_history.append(avg_reward)print(f" Collect avg reward: {avg_reward:+.4f}")# PPO policy gradient updatemetrics = ppo_update(trajectories, model, tokenizer, optimizer,n_epochs=n_epochs, clip_epsilon=clip_epsilon,entropy_coef=entropy_coef, gamma=gamma)loss_history.append(float(metrics["loss"]))policy_loss_history.append(float(metrics["policy_loss"]))entropy_history.append(float(metrics["entropy"]))print(f" Update loss={metrics['loss']:.4f} "f"policy={metrics['policy_loss']:.4f} "f"entropy={metrics['entropy']:.4f}")# Evaluate greedy policy after updateeval_m = evaluate_policy(env, model, tokenizer, n_episodes=3,max_steps=max_steps, task_levels=task_levels,verbose=False)2 unmodified linesprint(f" Eval avg reward: {eval_m['avg_reward']:+.4f} "f"(Δ baseline: {delta:+.4f})")# ==================================================================# PHASE 3: FINAL EVALUATION (proof of learning)# ==================================================================print("\n" + "="*60)print("PHASE 3 – FINAL EVALUATION (after all training)")print("="*60)25 unmodified linesprint(f" ✗ No overall improvement detected")print(f"{'='*60}")# ==================================================================# PLOTS# ==================================================================iters = list(range(1, n_iterations + 1))# --- 1. Warm-up loss curve ---if warmup_losses:fig, ax = plt.subplots(figsize=(7, 4))ax.plot(range(1, len(warmup_losses) + 1), warmup_losses,marker="o", linewidth=2, color="tab:purple")ax.set_title("Warm-up Loss (supervised, per epoch)",fontsize=13, fontweight="bold")ax.set_xlabel("Epoch")ax.set_ylabel("Cross-Entropy Loss")ax.grid(alpha=0.3)fig.tight_layout()fig.savefig("warmup_loss.png", dpi=150)plt.close(fig)# --- 2. PPO reward curve ---fig, ax = plt.subplots(figsize=(9, 5))ax.plot(iters, reward_history, marker="o", linewidth=2,label="Collect reward", color="tab:blue")ax.plot(iters, eval_history, marker="s", linewidth=2, linestyle="--",3 unmodified linesax.axhline(y=warmup_reward, color="tab:purple", linestyle=":",linewidth=1.5, label=f"Post-warmup ({warmup_reward:+.3f})")ax.set_title("PPO Reward per Iteration", fontsize=14, fontweight="bold")ax.set_xlabel("Iteration")ax.set_ylabel("Average Reward")ax.legend(loc="best", fontsize=8)ax.grid(alpha=0.3)fig.tight_layout()fig.savefig("reward_curve.png", dpi=150)plt.close(fig)# --- 3. PPO loss curve ---fig, ax = plt.subplots(figsize=(9, 5))ax.plot(iters, loss_history, marker="o", linewidth=2,label="Total loss", color="tab:red")ax.plot(iters, policy_loss_history, marker="^", linewidth=2, linestyle="--",label="Policy loss", color="tab:orange")ax.set_title("PPO Loss per Iteration", fontsize=14, fontweight="bold")ax.set_xlabel("Iteration")ax.set_ylabel("Loss")ax.legend(loc="best")ax.grid(alpha=0.3)fig.tight_layout()fig.savefig("loss_curve.png", dpi=150)plt.close(fig)# --- 4. Combined 3-panel summary ---fig, axes = plt.subplots(1, 3, figsize=(18, 5))# Panel A: warm-up lossif warmup_losses:axes[0].plot(range(1, len(warmup_losses) + 1), warmup_losses,marker="o", linewidth=2, color="tab:purple")axes[0].set_title("A. Warm-up Loss ↓")axes[0].set_xlabel("Epoch")axes[0].set_ylabel("CE Loss")axes[0].grid(alpha=0.3)# Panel B: PPO rewardaxes[1].plot(iters, reward_history, marker="o", linewidth=2,color="tab:blue", label="Collect")axes[1].plot(iters, eval_history, marker="s", linewidth=2,linestyle="--", color="tab:green", label="Eval")axes[1].axhline(y=baseline_reward, color="tab:gray", linestyle=":",linewidth=1.5, label="Baseline")axes[1].axhline(y=warmup_reward, color="tab:purple", linestyle=":",linewidth=1.5, label="Post-warmup")axes[1].set_title("B. PPO Reward ↑")axes[1].set_xlabel("Iteration")axes[1].set_ylabel("Avg Reward")axes[1].legend(fontsize=7)axes[1].grid(alpha=0.3)# Panel C: PPO lossaxes[2].plot(iters, loss_history, marker="o", linewidth=2,color="tab:red", label="Total")axes[2].plot(iters, policy_loss_history, marker="^", linewidth=2,linestyle="--", color="tab:orange", label="Policy")axes[2].set_title("C. PPO Loss ↓")axes[2].set_xlabel("Iteration")axes[2].set_ylabel("Loss")axes[2].legend(fontsize=7)axes[2].grid(alpha=0.3)fig.suptitle("Code Review Agent – Full Training Evidence",fontsize=14, fontweight="bold")fig.tight_layout()fig.savefig("training_summary.png", dpi=150)plt.close(fig)print("Plots saved: warmup_loss.png, reward_curve.png, ""loss_curve.png, training_summary.png")print("="*60)if __name__ == "__main__":12345674 unmodified lines1213141516171819202122232425262746 unmodified lines74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191 unmodified line12112212312412512612716 unmodified lines14414514614714814915025 unmodified lines17617717817918018132 unmodified lines2142152162172182193 unmodified lines2232242252262272282298 unmodified lines2382392402412422433 unmodified lines2472482492502512522532542552561 unmodified line2582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353362 unmodified lines3393403413423433443451 unmodified line3473483493503513523535 unmodified lines3593603613623633643653 unmodified lines36937037137237337434 unmodified lines40941041141241341431 unmodified lines44644744844945045145213 unmodified lines46646746846947047147213 unmodified lines4864874884894904914924934944954963 unmodified lines5005015025035045055065079 unmodified lines5175185195205215225235245251 unmodified line5275285295305315324 unmodified lines5375385395405415425434 unmodified lines5485495505515525535545555565575585595603 unmodified lines56456556656756856957057157257357429 unmodified lines6046056066076086096106116121 unmodified line6146156166176186196206216226236246256266276286296306316328 unmodified lines6416426436446456466476486496508 unmodified lines6596606616626636646656666676686696706716726732 unmodified lines6766776786796806816826836846856866876886896906912 unmodified lines69469569669769869925 unmodified lines7257267277287297307317327337347357367377387397407417427433 unmodified lines747748749750751752753754755756757758759760761762763764765# training.py – Vanilla bitsandbytes QLoRA + custom PPO (no unsloth, no Triton)import osos.environ["TOKENIZERS_PARALLELISM"] = "false"import jsonimport torchimport torch.nn.functional as F4 unmodified linesimport reimport randomimport matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltfrom transformers import (AutoModelForCausalLM,AutoTokenizer,BitsAndBytesConfig,TrainingArguments)from peft import LoraConfig, get_peft_model, TaskTypefrom environment import CodeReviewEnvfrom redteam import BUG_DB46 unmodified linesdef map_to_env(action: AgentAction):return model_map_to_env(action.action_type, action.content)# ======================================================================# Model loading – no unsloth, no Triton kernels# ======================================================================def load_model():model_name = "microsoft/Phi-3-mini-4k-instruct"bnb_config = BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_compute_dtype=torch.bfloat16,bnb_4bit_use_double_quant=True,bnb_4bit_quant_type="nf4",)model = AutoModelForCausalLM.from_pretrained(model_name,quantization_config=bnb_config,device_map="auto",trust_remote_code=True,torch_dtype=torch.bfloat16,)tokenizer = AutoTokenizer.from_pretrained(model_name)tokenizer.pad_token = tokenizer.eos_tokenlora_config = LoraConfig(r=16,lora_alpha=32,target_modules=["q_proj", "k_proj", "v_proj", "o_proj","gate_proj", "up_proj", "down_proj"],lora_dropout=0.0,bias="none",task_type=TaskType.CAUSAL_LM,)model = get_peft_model(model, lora_config)return model, tokenizer# ======================================================================def test_model_sanity(model, tokenizer) -> bool:print("\n" + "="*60)print("SANITY CHECK: Testing base model generation")1 unmodified linetest_prompt = "Hello, how are you?"messages = [{"role": "user", "content": test_prompt}]formatted = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)inputs = tokenizer(formatted, return_tensors="pt", max_length=256, truncation=True).to("cuda")with torch.no_grad():outputs = model.generate(**inputs,16 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 ""25 unmodified lines" 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"32 unmodified lines" return True")return ("def fix(data):\n"" if data is None:\n"3 unmodified linesdef _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"}'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(3 unmodified lines})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 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.The developer has a **{author_personality}** personality and will only accept if you provide solid evidence:- Tests pass (high pass ratio)- Lint is clean (zero errors)- Documentation or references are provided- Your reasoning is clear, uses words like "because" or "therefore", and is detailed (over 30 words if needed)Workflow:1. Use `inspect` to understand the code.2. Use `run_tests` and `run_linter` to gather evidence.3. Use `query_docs` when you need references or language-specific guidance.4. Propose a fix (`fix`) and explain why it works (`comment` or `question`).5. If the developer pushes back, read their response carefully and address their specific concern.6. Once convinced, use `done` to finish.Code:{obs.code_snippet}Author says:{author_msg if author_msg else "(no response yet – start with inspection)"}Last tool output:{tool_output if tool_output else "(none)"}Available actions:run_tests, run_linter, inspect, query_docs, fix, comment, question, doneRespond ONLY in JSON:{{"action_type": "...", "content": "..."}}"""if history_lines:history = "\n".join(history_lines[-6:])prompt += f"\n\nPrevious steps:\n{history}"return prompt# ======================================================================@dataclassclass Trajectory:states: List[str]actions: List[str]rewards: List[float]logprobs: List[float]dones: List[bool]def __len__(self): return len(self.states)def generate_action_with_logprob(prompt, model, tokenizer, temperature=0.0, max_retries=2):messages = [{"role": "user", "content": prompt}]formatted = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)# 1024 max length, no unslothinputs = tokenizer(formatted, return_tensors="pt", max_length=1024, truncation=True).to("cuda")for attempt in range(max_retries):with torch.no_grad():outputs = model.generate(**inputs,max_new_tokens=128,do_sample=(temperature > 0),temperature=max(temperature, 0.01) if temperature > 0 else 1.0,min_new_tokens=1,2 unmodified lines)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):1 unmodified linetoken_logprob = F.log_softmax(token_logits, dim=-1)[token_id].item()logprobs.append(token_logprob)total_logprob = sum(logprobs) if logprobs else -100.0if not action_text:fallback_actions = ['{"action_type": "run_tests"}',5 unmodified linestotal_logprob = -50.0print(f"[WARN] Empty generation → using fallback: {action_text}")return action_text, total_logprobtry:json.loads(action_text)return action_text, total_logprob3 unmodified linescontinuereturn '{"action_type":"skip"}', -100.0def collect_trajectory(env, model, tokenizer, max_steps=6, temperature=0.0):obs = env.reset()history_lines = []34 unmodified linesreturn trajectoriesdef compute_returns_and_advantages(rewards, dones, gamma=0.99, standardize=True):n = len(rewards)returns = [0.0]*nrunning = 0.031 unmodified linesmessages = [{"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=1024, truncation=True).to("cuda")outputs = model(**inputs)logits = outputs.logitsaction_ids = tokenizer.encode(action, add_special_tokens=False)13 unmodified linesif 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)13 unmodified linesdef evaluate_policy(env, model, tokenizer, n_episodes=3, max_steps=6,task_levels=None, verbose=False):model.eval()if task_levels is None:task_levels = list(BUG_DB.keys())total_rewards = []traces = []for ep in range(n_episodes):task = task_levels[ep % len(task_levels)]env.set_task(task)3 unmodified linesif verbose:actions_taken = []for a in traj.actions:try: actions_taken.append(json.loads(a).get("action_type", "?"))except: actions_taken.append("?")traces.append({"task": task,"reward": round(ep_reward, 4),9 unmodified lines}# ======================================================================# Manual warm-up from JSON (no SFTTrainer, no Unsloth)def json_warmup(model, tokenizer, json_path="training_data.json",n_episodes=25, epochs=3, lr=2e-5):print("\n" + "="*60)print("SUPERVISED WARM-UP: training_data.json (manual cross-entropy)")print("="*60)1 unmodified linewith open(json_path, encoding="utf-8") as f:data = json.load(f)steps_per_episode = 7max_examples = n_episodes * steps_per_episodeif max_examples < len(data):4 unmodified linesmodel.train()warmup_opt = AdamW(model.parameters(), lr=lr)warmup_losses = []for epoch in range(epochs):random.shuffle(data)4 unmodified linesprompt = example["prompt"]action = example["action"]messages = [{"role": "user", "content": prompt},{"role": "assistant", "content": action},]full_text = tokenizer.apply_chat_template(messages, tokenize=False)inputs = tokenizer(full_text, return_tensors="pt", max_length=1024, truncation=True).to("cuda")prompt_only = tokenizer.apply_chat_template([{"role": "user", "content": prompt}],tokenize=False, add_generation_prompt=True3 unmodified linestotal_len = inputs.input_ids.shape[1]if prompt_len >= total_len:continueoutputs = model(**inputs)logits = outputs.logitsshift_logits = logits[0, prompt_len - 1 : total_len - 1]shift_labels = inputs.input_ids[0, prompt_len : total_len]29 unmodified lines# ======================================================================# MAIN TRAINING PIPELINEdef train_ppo():n_iterations = 15trajectories_per_iter = 6n_epochs = 2max_steps = 8learning_rate = 3e-51 unmodified lineentropy_coef = 0.01gamma = 0.99# Pre-load embedder (unchanged)from rltool import ToolBoxprint("Pre-loading sentence-transformer embedder...")ToolBox._get_embedder()print("✓ Embedder ready")model, tokenizer = load_model()if not test_model_sanity(model, tokenizer):returnenv = CodeReviewEnv()task_levels = list(BUG_DB.keys())# Phase 0: baselineprint("\n" + "="*60)print("PHASE 0 – BASELINE EVALUATION (untrained)")print("="*60)8 unmodified linesprint(f" task={t['task']:8s} reward={t['reward']:+.4f} "f"steps={t['steps']} actions={t['actions']}")# Phase 1: supervised warm-upwarmup_losses = json_warmup(model, tokenizer, json_path="training_data.json",n_episodes=25, epochs=3, lr=2e-5)print("="*60)print("POST WARM-UP EVALUATION")print("="*60)8 unmodified linesprint(f" task={t['task']:8s} reward={t['reward']:+.4f} "f"steps={t['steps']} actions={t['actions']}")optimizer = AdamW(model.parameters(), lr=learning_rate)print(f"\n{'='*60}")print(f"PHASE 2 – PPO TRAINING: {n_iterations} iterations × "f"{trajectories_per_iter} trajectories (true RL)")print(f"{'='*60}\n")reward_history, eval_history, loss_history = [], [], []for iteration in range(n_iterations):print(f"\n--- PPO Iteration {iteration + 1}/{n_iterations} ---")trajectories = collect_trajectories(env, model, tokenizer, trajectories_per_iter, max_steps,task_levels=task_levels, task_weights=None2 unmodified linesreward_history.append(avg_reward)print(f" Collect avg reward: {avg_reward:+.4f}")metrics = ppo_update(trajectories, model, tokenizer, optimizer,n_epochs=n_epochs, clip_epsilon=clip_epsilon,entropy_coef=entropy_coef, gamma=gamma)loss_history.append(float(metrics["loss"]))print(f" Update loss={metrics['loss']:.4f} "f"policy={metrics['policy_loss']:.4f} "f"entropy={metrics['entropy']:.4f}")eval_m = evaluate_policy(env, model, tokenizer, n_episodes=3,max_steps=max_steps, task_levels=task_levels,verbose=False)2 unmodified linesprint(f" Eval avg reward: {eval_m['avg_reward']:+.4f} "f"(Δ baseline: {delta:+.4f})")print("\n" + "="*60)print("PHASE 3 – FINAL EVALUATION (after all training)")print("="*60)25 unmodified linesprint(f" ✗ No overall improvement detected")print(f"{'='*60}")# Plotsiters = list(range(1, n_iterations + 1))if warmup_losses:fig, ax = plt.subplots(figsize=(7, 4))ax.plot(range(1, len(warmup_losses)+1), warmup_losses,marker="o", linewidth=2, color="tab:purple")ax.set_title("Warm-up Loss (supervised, per epoch)", fontsize=13, fontweight="bold")ax.set_xlabel("Epoch"); ax.set_ylabel("Cross-Entropy Loss")ax.grid(alpha=0.3); fig.tight_layout()fig.savefig("warmup_loss.png", dpi=150); plt.close(fig)fig, ax = plt.subplots(figsize=(9,5))ax.plot(iters, reward_history, marker="o", linewidth=2,label="Collect reward", color="tab:blue")ax.plot(iters, eval_history, marker="s", linewidth=2, linestyle="--",3 unmodified linesax.axhline(y=warmup_reward, color="tab:purple", linestyle=":",linewidth=1.5, label=f"Post-warmup ({warmup_reward:+.3f})")ax.set_title("PPO Reward per Iteration", fontsize=14, fontweight="bold")ax.set_xlabel("Iteration"); ax.set_ylabel("Average Reward")ax.legend(loc="best", fontsize=8); ax.grid(alpha=0.3)fig.tight_layout(); fig.savefig("reward_curve.png", dpi=150); plt.close(fig)fig, ax = plt.subplots(figsize=(9,5))ax.plot(iters, loss_history, marker="o", linewidth=2,label="Total loss", color="tab:red")ax.set_title("PPO Loss per Iteration", fontsize=14, fontweight="bold")ax.set_xlabel("Iteration"); ax.set_ylabel("Loss")ax.legend(loc="best"); ax.grid(alpha=0.3)fig.tight_layout(); fig.savefig("loss_curve.png", dpi=150); plt.close(fig)print("Plots saved: warmup_loss.png, reward_curve.png, loss_curve.png")print("="*60)if __name__ == "__main__":
training.py+126-297