File size: 10,682 Bytes
b1100bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""StabilizerForge environment.

Episode loop:
  reset(task_id?)        -> sample/load a task; emit initial observation
  step(action)           -> apply one Clifford gate, or FINALIZE
                            returns dense shaping reward per step,
                            full terminal reward at FINALIZE.
"""
from __future__ import annotations

import json
import os
import random
from pathlib import Path
from typing import Any
from uuid import uuid4

from openenv.core.env_server.interfaces import Environment
from openenv.core.env_server.types import State

try:
    from ..models import StabilizerAction, StabilizerObservation
    from .verifier import match_fraction
except ImportError:  # pragma: no cover  (in-container imports without package context)
    from models import StabilizerAction, StabilizerObservation
    from server.verifier import match_fraction


# Reward weights (keep aligned with README)
W_MATCH = 0.4
W_GATE_EFF = 0.2
W_TWOQ_EFF = 0.2
W_CONN = 0.1
W_FORMAT = 0.1
SHAPING_COEF = 0.05  # per-step Δmatch_fraction shaping
MAX_CONSECUTIVE_VIOLATIONS = 5


def _default_tasks_path() -> str:
    """Resolve the default tasks file. Looks for env var, then sibling tasks.jsonl."""
    env_path = os.environ.get("STABILIZER_FORGE_TASKS")
    if env_path:
        return env_path
    here = Path(__file__).resolve().parent.parent  # stabilizer_forge/
    candidate = here / "tasks.jsonl"
    if candidate.exists():
        return str(candidate)
    # Fallback: project root
    return str(here.parent / "tasks.jsonl")


def _load_tasks(path: str) -> list[dict]:
    p = Path(path)
    if not p.exists():
        return []
    tasks: list[dict] = []
    with p.open() as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            tasks.append(json.loads(line))
    return tasks


def _gate_to_stim(action: StabilizerAction) -> str:
    """Render a single action as one line of Stim text."""
    if action.op in {"H", "S"}:
        return f"{action.op} {action.qubits[0]}"
    if action.op == "CX":
        return f"CX {action.qubits[0]} {action.qubits[1]}"
    raise ValueError(f"Cannot render gate: {action.op}")


def _validate_action(
    action: StabilizerAction, n_qubits: int
) -> tuple[bool, str]:
    """Schema/range validation. Returns (is_valid, error_msg)."""
    if action.op == "FINALIZE":
        if action.qubits:
            return False, "FINALIZE takes no qubits."
        return True, ""
    if action.op in {"H", "S"}:
        if len(action.qubits) != 1:
            return False, f"{action.op} requires exactly 1 qubit, got {len(action.qubits)}."
        q = action.qubits[0]
        if not (0 <= q < n_qubits):
            return False, f"qubit {q} out of range [0, {n_qubits})."
        return True, ""
    if action.op == "CX":
        if len(action.qubits) != 2:
            return False, f"CX requires exactly 2 qubits, got {len(action.qubits)}."
        c, t = action.qubits
        if c == t:
            return False, "CX control and target must differ."
        for q in (c, t):
            if not (0 <= q < n_qubits):
                return False, f"qubit {q} out of range [0, {n_qubits})."
        return True, ""
    return False, f"unknown op {action.op}"


class StabilizerForgeEnvironment(Environment):
    """Single-agent env: emit Clifford gates to encode a target stabilizer code."""

    SUPPORTS_CONCURRENT_SESSIONS: bool = True

    def __init__(self, tasks_path: str | None = None):
        super().__init__()
        self._tasks_path = tasks_path or _default_tasks_path()
        self._tasks = _load_tasks(self._tasks_path)
        self._task: dict[str, Any] | None = None
        self._gates: list[str] = []
        self._cnot_count = 0
        self._nonadj_cnot_count = 0
        self._format_violations = 0
        self._consecutive_violations = 0
        self._last_match_fraction = 0.0
        self._last_match_results: list[bool] = []
        self._finalized = False
        self._rng = random.Random()
        self._state = State(episode_id=str(uuid4()), step_count=0)

    # ---------- Helpers ----------

    def _circuit_text(self) -> str:
        return "\n".join(self._gates)

    def _is_adjacent(self, a: int, b: int) -> bool:
        edges = self._task.get("connectivity_edges") if self._task else None
        if edges is None:
            return True  # all-to-all
        edge_set = {tuple(sorted(e)) for e in edges}
        return tuple(sorted((a, b))) in edge_set

    def _compute_match(self) -> tuple[float, list[bool]]:
        if not self._task:
            return 0.0, []
        text = self._circuit_text()
        n = self._task["n_qubits"]
        targets = self._task["target_stabilizers"]
        frac, results_dict = match_fraction(text, targets, n)
        ordered = [results_dict[s] for s in targets]
        return frac, ordered

    def _make_obs(
        self,
        *,
        reward: float,
        done: bool,
        last_action_valid: bool = True,
        last_action_error: str = "",
    ) -> StabilizerObservation:
        assert self._task is not None
        bench = int(self._task.get("benchmark_optimum", 0) or 0)
        return StabilizerObservation(
            task_id=self._task["task_id"],
            target_stabilizers=list(self._task["target_stabilizers"]),
            n_qubits=int(self._task["n_qubits"]),
            connectivity_edges=self._task.get("connectivity_edges"),
            gates_so_far=list(self._gates),
            current_circuit=self._circuit_text(),
            current_match=list(self._last_match_results),
            match_fraction=float(self._last_match_fraction),
            gates_emitted=len(self._gates),
            cnot_count=self._cnot_count,
            nonadj_cnot_count=self._nonadj_cnot_count,
            gate_budget=int(self._task.get("gate_budget", 2 * max(1, bench))),
            gate_budget_remaining=max(
                0,
                int(self._task.get("gate_budget", 2 * max(1, bench))) - len(self._gates),
            ),
            benchmark_optimum=bench,
            benchmark_optimum_2q=int(self._task.get("benchmark_optimum_2q", 0) or 0),
            format_violations=self._format_violations,
            consecutive_violations=self._consecutive_violations,
            last_action_valid=last_action_valid,
            last_action_error=last_action_error,
            step_count=self._state.step_count,
            finalized=self._finalized,
            done=done,
            reward=reward,
        )

    def _pick_task(self, task_id: str | None, seed: int | None) -> dict[str, Any]:
        if task_id is not None:
            for t in self._tasks:
                if t.get("task_id") == task_id:
                    return t
            raise ValueError(f"task_id '{task_id}' not found in {self._tasks_path}")
        if not self._tasks:
            raise RuntimeError(
                f"No tasks loaded from {self._tasks_path}. "
                "Set STABILIZER_FORGE_TASKS or place tasks.jsonl next to the env."
            )
        rng = random.Random(seed) if seed is not None else self._rng
        return rng.choice(self._tasks)

    # ---------- Gym API ----------

    def reset(
        self,
        seed: int | None = None,
        episode_id: str | None = None,
        task_id: str | None = None,
        **kwargs: Any,
    ) -> StabilizerObservation:
        if seed is not None:
            self._rng = random.Random(seed)
        self._task = self._pick_task(task_id=task_id, seed=seed)

        self._gates = []
        self._cnot_count = 0
        self._nonadj_cnot_count = 0
        self._format_violations = 0
        self._consecutive_violations = 0
        self._finalized = False
        self._state = State(
            episode_id=episode_id or str(uuid4()), step_count=0
        )

        # Initial match (empty circuit on |0...0>)
        self._last_match_fraction, self._last_match_results = self._compute_match()
        return self._make_obs(reward=0.0, done=False)

    def step(self, action: StabilizerAction, **kwargs: Any) -> StabilizerObservation:  # type: ignore[override]
        if self._task is None:
            raise RuntimeError("step() called before reset().")
        self._state.step_count += 1

        n_qubits = int(self._task["n_qubits"])
        gate_budget = int(
            self._task.get(
                "gate_budget", 2 * max(1, int(self._task.get("benchmark_optimum", 1)))
            )
        )

        # --- Validate ---
        ok, err = _validate_action(action, n_qubits)
        if not ok:
            self._format_violations += 1
            self._consecutive_violations += 1
            done = (
                self._consecutive_violations >= MAX_CONSECUTIVE_VIOLATIONS
                or len(self._gates) >= gate_budget
            )
            return self._make_obs(
                reward=W_FORMAT * -1.0,
                done=done,
                last_action_valid=False,
                last_action_error=err,
            )

        self._consecutive_violations = 0

        # --- FINALIZE: terminal reward ---
        if action.op == "FINALIZE":
            self._finalized = True
            self._last_match_fraction, self._last_match_results = self._compute_match()
            bench = max(1, int(self._task.get("benchmark_optimum", 1)))
            bench_2q = max(1, int(self._task.get("benchmark_optimum_2q", bench)))
            gate_eff = max(0.0, 1.0 - len(self._gates) / (1.5 * bench))
            twoq_eff = max(0.0, 1.0 - self._cnot_count / (1.5 * bench_2q))
            terminal = (
                W_MATCH * self._last_match_fraction
                + W_GATE_EFF * gate_eff
                + W_TWOQ_EFF * twoq_eff
            )
            return self._make_obs(reward=terminal, done=True)

        # --- Apply gate ---
        gate_str = _gate_to_stim(action)
        self._gates.append(gate_str)

        conn_penalty = 0.0
        if action.op == "CX":
            self._cnot_count += 1
            if not self._is_adjacent(action.qubits[0], action.qubits[1]):
                self._nonadj_cnot_count += 1
                conn_penalty = -1.0

        prev_match = self._last_match_fraction
        self._last_match_fraction, self._last_match_results = self._compute_match()
        delta = self._last_match_fraction - prev_match

        # Termination if we exceed budget without finalizing
        done = len(self._gates) >= gate_budget

        step_reward = SHAPING_COEF * delta + W_CONN * conn_penalty
        return self._make_obs(reward=step_reward, done=done)

    @property
    def state(self) -> State:
        return self._state