File size: 5,899 Bytes
bf9e424
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generate a MolForge SFT JSONL dataset with rare-action coverage.

Most records come from the deterministic team policy so the examples are
grounded in real environment trajectories. A smaller coverage slice is added
for rare but valid schema variants such as defer, each assay tool, and edit
subtypes so SFT teaches the model the whole action surface.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path
from typing import Iterable

PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from inference_common import (  # noqa: E402
    SYSTEM_PROMPT,
    MolForgeAction,
    MolForgeObservation,
    attach_reasoning_fields,
    attach_team_messages,
    build_model_payload,
    heuristic_team_action,
)
from scenarios import DEFAULT_TOOL_COSTS  # noqa: E402
from server.molforge_environment import MolForgeEnvironment  # noqa: E402


def main() -> None:
    parser = argparse.ArgumentParser(description="Generate MolForge all-action SFT JSONL.")
    parser.add_argument("--episodes", type=int, default=90)
    parser.add_argument("--max-turns", type=int, default=10)
    parser.add_argument("--output", default="data/molforge_sft_all_actions.jsonl")
    parser.add_argument(
        "--randomized",
        action="store_true",
        help="Enable MolForge training randomization while collecting policy traces.",
    )
    args = parser.parse_args()

    if args.randomized:
        os.environ["MOLFORGE_TRAINING_RANDOMIZATION"] = "1"

    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    env = MolForgeEnvironment()
    records = []

    for _ in range(args.episodes):
        observation = env.reset()
        for _ in range(args.max_turns):
            if observation.done:
                break
            action = heuristic_team_action(observation)
            records.append(make_record(observation, action, source="policy_trace"))
            observation = env.step(action)

    for observation, action in curated_coverage_examples():
        action = attach_reasoning_fields(observation, action)
        action = attach_team_messages(observation, action)
        records.append(make_record(observation, action, source="coverage_example"))

    with output_path.open("w", encoding="utf-8") as handle:
        for record in records:
            handle.write(json.dumps(record, ensure_ascii=True) + "\n")

    print(
        json.dumps(
            {
                "output": str(output_path),
                "records": len(records),
                "coverage_records": sum(
                    1 for record in records if record["metadata"]["source"] == "coverage_example"
                ),
            },
            indent=2,
        )
    )


def curated_coverage_examples() -> Iterable[tuple[MolForgeObservation, MolForgeAction]]:
    env = MolForgeEnvironment()
    observations = [env.reset(), env.reset(), env.reset()]

    for observation in observations:
        yield observation, MolForgeAction(
            action_type="defer",
            acting_role="lead_chemist",
            rationale="Hold this turn because the team needs a cleaner evidence-backed move.",
        )

    easy, medium, hard = observations

    yield easy, MolForgeAction(
        action_type="edit",
        acting_role="lead_chemist",
        edit_type="add_fragment",
        slot="back_pocket",
        fragment="cyano",
        rationale="Add a compact cyano handle to improve potency without large lipophilic risk.",
    )
    yield medium, MolForgeAction(
        action_type="edit",
        acting_role="lead_chemist",
        edit_type="remove",
        slot="back_pocket",
        rationale="Remove the risky back-pocket group and return to a simpler default handle.",
    )
    yield hard, MolForgeAction(
        action_type="edit",
        acting_role="lead_chemist",
        edit_type="undo_last_edit",
        slot="solvent_tail",
        rationale="Undo the last tail change when the visible evidence suggests it raised risk.",
    )

    for observation in observations:
        for tool_name in DEFAULT_TOOL_COSTS:
            yield observation, MolForgeAction(
                action_type="run_assay",
                acting_role="assay_planner",
                tool_name=tool_name,
                rationale=f"Run {tool_name} to close a visible evidence gap before committing.",
            )

    yield hard, MolForgeAction(
        action_type="restart",
        acting_role="lead_chemist",
        rationale="Restart early because the hard scenario starts in a trap series.",
    )
    yield easy, MolForgeAction(
        action_type="submit",
        acting_role="lead_chemist",
        rationale="Submit only when visible evidence is sufficient and budget should be preserved.",
    )


def make_record(
    observation: MolForgeObservation,
    action: MolForgeAction,
    *,
    source: str,
) -> dict[str, object]:
    return {
        "messages": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {
                "role": "user",
                "content": json.dumps(
                    build_model_payload(observation, compact=False),
                    separators=(",", ":"),
                ),
            },
            {
                "role": "assistant",
                "content": json.dumps(
                    action.model_dump(exclude_none=True),
                    separators=(",", ":"),
                ),
            },
        ],
        "metadata": {
            "source": source,
            "scenario_id": observation.scenario_id,
            "difficulty": observation.difficulty,
            "step_index": observation.step_index,
            "action_type": action.action_type,
        },
    }


if __name__ == "__main__":
    main()