"""Turn scored traces into training data. Three exports, all keyed off the same JSONL the trace runner produces: * ``export_sft`` -- best trace per task, as chat-format SFT pairs * ``export_preference``-- within-task (best, worst) pairs where the reward gap clears a threshold; usable for DPO-style work * ``export_grpo`` -- every scored trace with its reward, for reward modelling and for sanity-checking the reward function Nothing here re-runs a model; it reads traces and writes JSONL. """ import json import logging import os from typing import Any, Dict, Iterable, List, Optional, Tuple logger = logging.getLogger("guac_coder.trace_export") def load_traces(path: str) -> List[Dict[str, Any]]: """Read a traces JSONL file.""" rows = [] with open(path, "r", encoding="utf-8") as fh: for line in fh: line = line.strip() if line: rows.append(json.loads(line)) return rows def _scored(traces: Iterable[Dict[str, Any]]) -> List[Dict[str, Any]]: """Traces that produced *parseable* code and therefore a usable reward. A truthiness check on ``code`` is not enough: truncated generations and stray prose also carry a reward. Exporting them would teach the model to emit code that does not parse, so the validity gate is applied here too. """ from guac_coder.grpo_rewards import is_valid_python return [ t for t in traces if t.get("total_reward") is not None and t.get("code") and is_valid_python(t["code"]) ] def group_by_task(traces: Iterable[Dict[str, Any]]) -> Dict[Tuple[str, int], List[Dict[str, Any]]]: """Group traces by (model, task_id) so comparisons are like-for-like.""" groups: Dict[Tuple[str, int], List[Dict[str, Any]]] = {} for t in traces: groups.setdefault((t["model"], t["task_id"]), []).append(t) return groups def _task_prompt(trace: Dict[str, Any]) -> str: """Rebuild the prompt from the task text so exports are self-contained.""" from guac_coder.data import build_prompt return build_prompt(trace["task"]) def export_sft( traces: List[Dict[str, Any]], output_path: str, min_reward: Optional[float] = None, ) -> int: """Write the highest-reward trace per task as an SFT pair. With ``min_reward`` set, tasks whose best trace falls below it are skipped; that keeps obviously-bad generations out of the fine-tuning set. """ best_per_task: Dict[Tuple[str, int], Dict[str, Any]] = {} for t in _scored(traces): key = (t["model"], t["task_id"]) current = best_per_task.get(key) if current is None or t["total_reward"] > current["total_reward"]: best_per_task[key] = t written = 0 skipped = 0 os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) with open(output_path, "w", encoding="utf-8") as fh: for key, t in sorted(best_per_task.items(), key=lambda kv: kv[0][1]): if min_reward is not None and t["total_reward"] < min_reward: skipped += 1 continue record = { "messages": [ {"role": "system", "content": _task_prompt(t)}, {"role": "user", "content": t["task"]}, {"role": "assistant", "content": t["code"]}, ], "meta": { "source_model": t["model"], "task_id": t["task_id"], "total_reward": t["total_reward"], "rater": t.get("rater", "static"), "code_source": t["code_source"], }, } fh.write(json.dumps(record) + "\n") written += 1 logger.info( "SFT: wrote %d pairs to %s (skipped %d below min_reward)", written, output_path, skipped, ) return written def export_preference( traces: List[Dict[str, Any]], output_path: str, min_gap: float = 0.15, ) -> int: """Write (chosen, rejected) pairs where one trace clearly beats another. Pairs come from the same model and task so the comparison is meaningful; ``min_gap`` forces a real separation rather than noise. """ written = 0 os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) with open(output_path, "w", encoding="utf-8") as fh: for (model, task_id), rows in sorted(group_by_task(traces).items()): scored = _scored(rows) if len(scored) < 2: continue ranked = sorted(scored, key=lambda t: t["total_reward"], reverse=True) chosen, rejected = ranked[0], ranked[-1] gap = chosen["total_reward"] - rejected["total_reward"] if gap < min_gap: continue record = { "prompt": _task_prompt(chosen), "task": chosen["task"], "chosen": chosen["code"], "rejected": rejected["code"], "chosen_reward": chosen["total_reward"], "rejected_reward": rejected["total_reward"], "gap": round(gap, 4), "meta": {"source_model": model, "task_id": task_id}, } fh.write(json.dumps(record) + "\n") written += 1 logger.info("Preference: wrote %d pairs to %s", written, output_path) return written def export_grpo( traces: List[Dict[str, Any]], output_path: str, include_unscored: bool = False, ) -> int: """Write every trace with its reward and per-rule breakdown.""" rows = traces if include_unscored else _scored(traces) os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) with open(output_path, "w", encoding="utf-8") as fh: for t in rows: record = { "prompt": _task_prompt(t), "task": t["task"], "completion": t["code"], "reward": t["total_reward"], "rules": t.get("rules", {}), "meta": { "source_model": t["model"], "task_id": t["task_id"], "sample_index": t["sample_index"], "code_source": t["code_source"], }, } fh.write(json.dumps(record) + "\n") logger.info("GRPO: wrote %d records to %s", len(rows), output_path) return len(rows) def export_all( traces_path: str, output_dir: str, min_reward: Optional[float] = None, min_gap: float = 0.15, ) -> Dict[str, Any]: """Run all three exports and return a manifest of what was written.""" traces = load_traces(traces_path) os.makedirs(output_dir, exist_ok=True) sft_path = os.path.join(output_dir, "sft_pairs.jsonl") pref_path = os.path.join(output_dir, "preference_pairs.jsonl") grpo_path = os.path.join(output_dir, "grpo_records.jsonl") n_sft = export_sft(traces, sft_path, min_reward=min_reward) n_pref = export_preference(traces, pref_path, min_gap=min_gap) n_grpo = export_grpo(traces, grpo_path) manifest = { "traces_path": traces_path, "n_traces": len(traces), "n_scored": len(_scored(traces)), "sft": {"path": sft_path, "n": n_sft}, "preference": {"path": pref_path, "n": n_pref}, "grpo": {"path": grpo_path, "n": n_grpo}, } with open(os.path.join(output_dir, "manifest.json"), "w", encoding="utf-8") as fh: json.dump(manifest, fh, indent=2) logger.info("Export manifest written to %s", output_dir) return manifest