File size: 10,574 Bytes
db03c40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad39f2a
db03c40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""Run the bio-experiment environment with a quantized Unsloth model."""

from __future__ import annotations

import json
import os
import time
from typing import Any, Dict, Optional

from models import ActionType, ExperimentAction
from server.hackathon_environment import BioExperimentEnvironment
from training_unsloth import (
    DEFAULT_MAX_SEQ_LENGTH,
    generate_action_with_model,
    load_model_artifacts,
)
from training_script import DEFAULT_COMPLETION_TOKEN_BUDGET

import run_agent as base

MODEL_ID = os.getenv("RUN_AGENT_UNSLOTH_MODEL_ID", "unsloth/Qwen3.5-2B-GGUF")
MAX_EPISODE_STEPS = int(
    os.getenv("RUN_AGENT_UNSLOTH_MAX_EPISODE_STEPS", str(base.MAX_EPISODE_STEPS))
)
MAX_NEW_TOKENS = int(
    os.getenv(
        "RUN_AGENT_UNSLOTH_MAX_NEW_TOKENS",
        str(DEFAULT_COMPLETION_TOKEN_BUDGET),
    )
)
MAX_SEQ_LENGTH = int(
    os.getenv("RUN_AGENT_UNSLOTH_MAX_SEQ_LENGTH", str(DEFAULT_MAX_SEQ_LENGTH))
)
TRUST_REMOTE_CODE = (
    os.getenv("RUN_AGENT_UNSLOTH_TRUST_REMOTE_CODE", "1").strip().lower()
    not in {"0", "false", "off"}
)
LOAD_IN_4BIT = (
    os.getenv("RUN_AGENT_UNSLOTH_LOAD_IN_4BIT", "1").strip().lower()
    not in {"0", "false", "off"}
)
FAST_INFERENCE = (
    os.getenv("RUN_AGENT_UNSLOTH_FAST_INFERENCE", "0").strip().lower()
    not in {"0", "false", "off"}
)


def check_dashboard_command() -> Optional[Dict[str, Any]]:
    try:
        raw = base.DASHBOARD_CMD_PATH.read_text(encoding="utf-8")
        base.DASHBOARD_CMD_PATH.unlink(missing_ok=True)
        return json.loads(raw)
    except (FileNotFoundError, json.JSONDecodeError):
        return None


def run_episode(

    model: Any,

    tokenizer: Any,

    *,

    scenario_name: Optional[str] = None,

    custom_ground_truth: Optional[Dict[str, Any]] = None,

) -> None:
    env = BioExperimentEnvironment(scenario_name=scenario_name)
    obs = env.reset()

    if custom_ground_truth and env._latent:
        gt = custom_ground_truth
        bio = env._latent.biology
        if gt.get("true_markers"):
            bio.true_markers = gt["true_markers"]
        if gt.get("causal_mechanisms"):
            bio.causal_mechanisms = gt["causal_mechanisms"]
        if gt.get("true_pathways"):
            bio.true_pathways = {
                key: float(value) for key, value in gt["true_pathways"].items()
            }

    base.log("\n" + "=" * 70)
    base.log(f"TASK: {obs.task.problem_statement}")
    base.log(f"Conditions: {obs.task.conditions}")
    base.log(
        f"Budget: ${obs.task.budget_limit:,.0f} | "
        f"Time: {obs.task.time_limit_days:.0f} days"
    )
    base.log("Runtime: Unsloth quantized generation")
    base.log("=" * 70)

    cumulative_reward = 0.0
    base.write_dashboard_state(env, obs, step=0, cumulative_reward=0.0)

    for step in range(MAX_EPISODE_STEPS):
        cmd = check_dashboard_command()
        if cmd and cmd.get("action") == "restart":
            base.log("\n[DASHBOARD] Restart requested - ending episode early.")
            break

        t0 = time.time()
        result = generate_action_with_model(
            model,
            tokenizer,
            obs,
            max_new_tokens=MAX_NEW_TOKENS,
            temperature=0.2,
            top_p=0.9,
            do_sample=True,
        )
        response = result["response_text"]
        action = result["action"]
        gen_time = time.time() - t0

        is_last_step = step == MAX_EPISODE_STEPS - 1
        if action is None:
            if is_last_step:
                base.log("\n  [!] Parse failed on final step - forcing synthesize_conclusion.")
                action = ExperimentAction(
                    action_type=ActionType.SYNTHESIZE_CONCLUSION,
                    justification="forced terminal conclusion",
                    confidence=0.5,
                )
            else:
                base.log(
                    f"\n  [!] Parse failed, skipping step. Raw: {response[:150]}"
                )
                continue

        completed_types = {
            record.action_type for record in obs.pipeline_history if record.success
        }
        failed_types = {
            record.action_type for record in obs.pipeline_history if not record.success
        }

        if base.should_force_terminal_conclusion(action, completed_types):
            base.log(
                f"\n  [!] repeated completed meta step {action.action_type.value} "
                f"- forcing synthesize_conclusion."
            )
            action = ExperimentAction(
                action_type=ActionType.SYNTHESIZE_CONCLUSION,
                justification="repeated completed meta step forced terminal conclusion",
                confidence=action.confidence,
            )
            completed_types = {
                record.action_type for record in obs.pipeline_history if record.success
            }

        skip_reason = None
        if action.action_type in completed_types:
            skip_reason = f"blocked repeat of completed step {action.action_type.value}"
        elif action.action_type in failed_types:
            if base.should_block_failed_reattempt(obs.pipeline_history, action.action_type):
                skip_reason = (
                    f"blocked re-attempt of failed step {action.action_type.value}"
                )

        if skip_reason:
            if is_last_step:
                base.log(
                    f"\n  [!] {skip_reason} on final step - forcing synthesize_conclusion."
                )
                action = ExperimentAction(
                    action_type=ActionType.SYNTHESIZE_CONCLUSION,
                    justification="forced terminal conclusion",
                    confidence=0.5,
                )
            else:
                base.log(f"\n  [!] {skip_reason}, skipping step.")
                continue

        if is_last_step and action.action_type != ActionType.SYNTHESIZE_CONCLUSION:
            base.log(
                f"\n  [!] Final step - overriding {action.action_type.value} "
                "with synthesize_conclusion."
            )
            action = ExperimentAction(
                action_type=ActionType.SYNTHESIZE_CONCLUSION,
                justification="forced terminal conclusion",
                confidence=action.confidence,
            )

        action = base.ensure_conclusion_claims(obs, action)

        base.log(f"\nStep {step + 1}: {action.action_type.value}  ({gen_time:.1f}s)")
        if action.justification:
            base.log(f"  Rationale: {action.justification}")
        else:
            base.log("  Rationale: [model did not provide one]")
        if action.parameters:
            base.log(f"  Parameters: {base.compact_preview(action.parameters, 200)}")
        elif response:
            base.log(
                "  Model response: "
                f"{base.compact_preview(response, base.MODEL_RESPONSE_PREVIEW_CHARS)}"
            )

        obs = env.step(action)

        if obs.latest_output:
            latest_output = obs.latest_output
            status = "OK" if latest_output.success else "FAIL"
            base.log(f"  [{status}] {latest_output.summary}")
            if latest_output.warnings:
                base.log(f"  Warnings: {latest_output.warnings}")

        step_reward = obs.reward
        cumulative_reward += step_reward
        base.log(f"  Reward: {step_reward:+.3f}  (cum: {cumulative_reward:+.3f})")
        base.log(
            f"  Budget: ${obs.resource_usage.budget_remaining:,.0f} | "
            f"Time: {obs.resource_usage.time_remaining_days:.0f}d"
        )

        base.write_dashboard_state(
            env,
            obs,
            step=step + 1,
            cumulative_reward=cumulative_reward,
            model_response=response,
            action=action,
            gen_time=gen_time,
            episode_done=obs.done,
        )

        if obs.rule_violations:
            base.log(f"  Violations: {obs.rule_violations}")
        if obs.done:
            break

    base.log(f"\n{'=' * 70}")
    base.log("EPISODE COMPLETE" if obs.done else f"MAX STEPS ({MAX_EPISODE_STEPS})")
    base.log(f"  Steps: {obs.step_index}")
    base.log(f"  Total reward: {cumulative_reward:+.3f}")
    base.log(f"  Budget used: ${obs.resource_usage.budget_used:,.0f}")
    base.log(f"  Time used: {obs.resource_usage.time_used_days:.0f} days")
    if obs.conclusions:
        base.log("  Conclusions:")
        for conclusion in obs.conclusions:
            base.log(
                f"    [{conclusion.claim_type}, conf={conclusion.confidence:.2f}] "
                f"{conclusion.claim}"
            )
            if conclusion.top_markers:
                base.log(f"      Markers: {conclusion.top_markers}")
            if conclusion.causal_mechanisms:
                base.log(f"      Mechanisms: {conclusion.causal_mechanisms}")
            if conclusion.predicted_pathways:
                base.log(f"      Pathways: {conclusion.predicted_pathways}")
    base.log("=" * 70)


def main() -> None:
    runtime = base.resolve_torch_runtime()
    base.log(
        f"Using Unsloth runtime: device={runtime['device']} "
        f"name={runtime['device_name']} dtype={runtime['dtype']}"
    )
    tokenizer, model = load_model_artifacts(
        MODEL_ID,
        trust_remote_code=TRUST_REMOTE_CODE,
        max_seq_length=MAX_SEQ_LENGTH,
        load_in_4bit=LOAD_IN_4BIT,
        fast_inference=FAST_INFERENCE,
        prepare_for_inference=True,
    )
    base.DASHBOARD_CMD_PATH.unlink(missing_ok=True)
    run_episode(model, tokenizer)

    while True:
        base.log("\nWaiting for dashboard command (restart / new task) ...")
        while True:
            cmd = check_dashboard_command()
            if cmd:
                break
            time.sleep(1.0)

        action_type = cmd.get("action", "restart")
        if action_type == "quit":
            base.log("Quit requested.")
            break

        scenario = cmd.get("scenario_name")
        ground_truth = cmd.get("ground_truth")
        base.log(f"\n[DASHBOARD] {action_type} - scenario={scenario}")
        run_episode(
            model,
            tokenizer,
            scenario_name=scenario,
            custom_ground_truth=ground_truth,
        )


if __name__ == "__main__":
    main()