File size: 7,686 Bytes
498f80b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
"""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