poseidon666 commited on
Commit
0fc908f
·
verified ·
1 Parent(s): 28f016b

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. openenv.yaml +1 -1
  2. server/app.py +165 -81
openenv.yaml CHANGED
@@ -3,7 +3,7 @@ name: quantum_circuit_optimizer
3
  type: space
4
  runtime: fastapi
5
  app: server.app:app
6
- port: 8000
7
  description: >-
8
  Noise-aware, hardware-constrained quantum circuit optimization environment.
9
  Train RL agents to design quantum circuits that maximize fidelity to target
 
3
  type: space
4
  runtime: fastapi
5
  app: server.app:app
6
+ port: 7860
7
  description: >-
8
  Noise-aware, hardware-constrained quantum circuit optimization environment.
9
  Train RL agents to design quantum circuits that maximize fidelity to target
server/app.py CHANGED
@@ -1,63 +1,92 @@
1
- # -*- coding: utf-8 -*-
 
 
 
 
 
2
  """
3
- FastAPI server with Gradio UI for the Quantum Circuit Optimization Environment.
 
 
 
 
 
 
 
4
 
5
- Deployment spec:
6
- - Root endpoint: GET / → health check JSON
7
- - Gradio UI: mounted at /
8
- - Port: 7860 (managed externally by HF Spaces)
 
9
  """
10
 
11
- import json
12
  import logging
13
  import os
14
- import sys
15
-
16
- # sys.path bootstrap so this file can be run directly
17
- _HERE = os.path.dirname(os.path.abspath(__file__))
18
- _ROOT = os.path.dirname(_HERE)
19
- for _p in (_ROOT, _HERE):
20
- if _p not in sys.path:
21
- sys.path.insert(0, _p)
22
 
23
- from fastapi import FastAPI
24
  import gradio as gr
25
-
26
- from models import ActionType, GateType, QuantumAction, QuantumObservation
27
- from server.my_env_environment import QuantumCircuitEnvironment
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  logging.basicConfig(level=logging.INFO)
30
  logger = logging.getLogger(__name__)
31
 
32
  # ---------------------------------------------------------------------------
33
- # FastAPI base app
34
  # ---------------------------------------------------------------------------
35
- fastapi_app = FastAPI(title="Quantum Circuit Optimizer")
36
 
37
- @fastapi_app.get("/health")
38
- def health():
39
- return {"status": "ok", "message": "Quantum Circuit Optimizer is running"}
 
 
40
 
41
- @fastapi_app.get("/api/info")
42
- def info():
43
- return {
44
- "name": "Quantum Circuit Optimization Environment",
45
- "version": "1.0.0",
46
- "gradio_ui": "Available at root path /"
47
- }
48
 
49
  # ---------------------------------------------------------------------------
50
- # Global environment instance (for Gradio UI)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  # ---------------------------------------------------------------------------
52
- env = QuantumCircuitEnvironment(seed=42)
53
 
54
- # Gradio State
55
  current_obs = None
56
  step_history: list = []
57
 
58
-
59
  # ---------------------------------------------------------------------------
60
- # Helpers
61
  # ---------------------------------------------------------------------------
62
 
63
  def _format_circuit(obs) -> str:
@@ -66,10 +95,10 @@ def _format_circuit(obs) -> str:
66
  return "(empty circuit)"
67
  lines = []
68
  for i, g in enumerate(obs.circuit_gates):
69
- gate = g.get("gate", "?")
70
  qubits = g.get("qubits", [])
71
- param = g.get("parameter")
72
- q_str = ",".join(str(q) for q in qubits)
73
  if param is not None:
74
  lines.append(f" {i+1:>2}. {gate}({q_str}, θ={param:.4f})")
75
  else:
@@ -82,11 +111,11 @@ def _format_scores(obs) -> str:
82
  if not obs:
83
  return ""
84
  meta = obs.metadata or {}
85
- fid = round(meta.get("fidelity_score", obs.fidelity), 4)
86
- eff = round(meta.get("efficiency_score", 0), 4)
87
- noi = round(meta.get("noise_score", 0), 4)
88
- con = round(meta.get("constraints_score", 0), 4)
89
- agg = round(meta.get("aggregate_score", obs.score), 4)
90
  return (
91
  f"Fidelity: {fid}\n"
92
  f"Efficiency: {eff}\n"
@@ -113,24 +142,20 @@ def _status(obs, extra: str = "") -> str:
113
 
114
 
115
  # ---------------------------------------------------------------------------
116
- # Gradio callbacks
117
  # ---------------------------------------------------------------------------
118
 
119
  TASK_MAP = {
120
- "Bell State (Easy)": "easy",
121
- "GHZ State (Medium)": "medium",
122
- "Unitary Approx (Hard)": "hard",
123
- "Imperfect but Efficient": "efficient",
124
- "Noise-Dominant": "noisy",
125
- "Budgeted Optimization": "budget",
126
- "Approximate Target": "approx",
127
  }
128
 
129
 
130
  def do_reset(task_name):
131
  global current_obs, step_history
132
  task_id = TASK_MAP.get(task_name, "easy")
133
- current_obs = env.reset(task_id=task_id)
134
  step_history = []
135
  return (
136
  _status(current_obs, f"Reset to: {task_name}"),
@@ -149,17 +174,15 @@ def do_step(action_type, gate_type, qubit_0, qubit_1, parameter):
149
  return _status(current_obs), _format_circuit(current_obs), _format_scores(current_obs), "\n".join(step_history)
150
 
151
  try:
152
- at = ActionType(action_type)
153
- gate = None
154
  qubits = []
155
- param = None
156
 
157
  if at == ActionType.ADD:
158
  gate = GateType(gate_type) if gate_type else None
159
  if gate in (GateType.CNOT,):
160
  qubits = [int(qubit_0), int(qubit_1)]
161
- elif gate is not None and gate.value == "SWAP":
162
- qubits = [int(qubit_0), int(qubit_1)]
163
  else:
164
  qubits = [int(qubit_0)]
165
  if gate in (GateType.RX, GateType.RZ) and parameter is not None:
@@ -172,8 +195,8 @@ def do_step(action_type, gate_type, qubit_0, qubit_1, parameter):
172
  if parameter is not None:
173
  param = float(parameter)
174
 
175
- action = QuantumAction(action_type=at, gate=gate, qubits=qubits, parameter=param)
176
- current_obs = env.step(action)
177
 
178
  except Exception as exc:
179
  logger.exception("Step error: %s", exc)
@@ -210,51 +233,112 @@ def do_step(action_type, gate_type, qubit_0, qubit_1, parameter):
210
 
211
  def create_gradio_app() -> gr.Blocks:
212
  with gr.Blocks(title="Quantum Circuit Optimizer") as demo:
 
 
 
 
 
 
 
 
 
 
213
 
214
- gr.Markdown("## Quantum Circuit Optimizer\nBuild circuits step-by-step. Maximize fidelity with the target state.")
215
-
216
- # ---- Controls ----
217
  with gr.Row():
218
- task_dd = gr.Dropdown(choices=list(TASK_MAP.keys()), value="Bell State (Easy)", label="Task")
219
  reset_btn = gr.Button("Reset Environment", variant="primary")
220
 
221
  with gr.Row():
222
  action_dd = gr.Dropdown(choices=["ADD", "REMOVE", "SWAP", "PARAM", "STOP"], value="ADD", label="Action Type")
223
- gate_dd = gr.Dropdown(choices=["H", "X", "CNOT", "RX", "RZ"], value="H", label="Gate (for ADD)")
224
 
225
  with gr.Row():
226
- qubit_0 = gr.Number(value=0, label="Qubit 0", precision=0)
227
- qubit_1 = gr.Number(value=1, label="Qubit 1 (CNOT/SWAP)", precision=0)
228
  parameter = gr.Number(value=None, label="Parameter (RX/RZ angle)", precision=4)
229
 
230
  step_btn = gr.Button("Execute Step", variant="secondary")
231
 
232
- # ---- Outputs ----
233
- status_out = gr.Textbox(label="Status", lines=3, interactive=False)
234
- circuit_out = gr.Textbox(label="Circuit", lines=10, interactive=False)
235
- scores_out = gr.Textbox(label="Scores", lines=6, interactive=False)
236
- history_out = gr.Textbox(label="Step History", lines=8, interactive=False)
237
 
238
- # ---- Events ----
239
  OUTS = [status_out, circuit_out, scores_out, history_out]
240
 
241
- reset_btn.click(fn=do_reset, inputs=[task_dd], outputs=OUTS)
242
- step_btn.click( fn=do_step, inputs=[action_dd, gate_dd, qubit_0, qubit_1, parameter], outputs=OUTS)
243
 
244
  return demo
245
 
246
 
247
  # ---------------------------------------------------------------------------
248
- # Create Gradio app and mount to FastAPI
249
  # ---------------------------------------------------------------------------
 
250
  demo = create_gradio_app()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
251
 
252
- # Mount Gradio to FastAPI at root path
253
- app = gr.mount_gradio_app(fastapi_app, demo, path="/")
254
 
255
  # ---------------------------------------------------------------------------
256
- # Entry Point (for local testing only)
257
  # ---------------------------------------------------------------------------
258
- if __name__ == "__main__":
 
 
 
259
  import uvicorn
260
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
  """
8
+ FastAPI application with Gradio UI for the Quantum Circuit Optimization Environment.
9
+
10
+ This module creates an HTTP server that exposes the QuantumCircuitEnvironment
11
+ with both OpenEnv API endpoints and a custom Gradio UI.
12
+
13
+ Usage:
14
+ # Development (with auto-reload):
15
+ uvicorn server.app:app --reload --host 0.0.0.0 --port 7860
16
 
17
+ # Production:
18
+ uvicorn server.app:app --host 0.0.0.0 --port 7860
19
+
20
+ # Or run directly:
21
+ python server/app.py --port 7860
22
  """
23
 
 
24
  import logging
25
  import os
26
+ from pathlib import Path
 
 
 
 
 
 
 
27
 
 
28
  import gradio as gr
29
+ from fastapi import FastAPI
30
+ from fastapi.middleware.cors import CORSMiddleware
31
+ from fastapi.responses import HTMLResponse, RedirectResponse
32
+
33
+ try:
34
+ from openenv.core.env_server.http_server import create_app
35
+ except Exception as e:
36
+ raise ImportError(
37
+ "openenv is required for the web interface. Install dependencies with 'uv sync'"
38
+ ) from e
39
+
40
+ try:
41
+ from ..models import ActionType, GateType, QuantumAction, QuantumObservation
42
+ from .my_env_environment import QuantumCircuitEnvironment
43
+ except (ImportError, ModuleNotFoundError):
44
+ from models import ActionType, GateType, QuantumAction, QuantumObservation
45
+ from server.my_env_environment import QuantumCircuitEnvironment
46
 
47
  logging.basicConfig(level=logging.INFO)
48
  logger = logging.getLogger(__name__)
49
 
50
  # ---------------------------------------------------------------------------
51
+ # Environment factory
52
  # ---------------------------------------------------------------------------
 
53
 
54
+ def make_env():
55
+ """Factory function to create a new environment instance."""
56
+ env = QuantumCircuitEnvironment(seed=42)
57
+ env.reset(task_id="easy")
58
+ return env
59
 
 
 
 
 
 
 
 
60
 
61
  # ---------------------------------------------------------------------------
62
+ # Create OpenEnv FastAPI app
63
+ # ---------------------------------------------------------------------------
64
+
65
+ app = create_app(
66
+ make_env,
67
+ QuantumAction,
68
+ QuantumObservation,
69
+ env_name="quantum_circuit_env",
70
+ max_concurrent_envs=10,
71
+ )
72
+
73
+ app.add_middleware(
74
+ CORSMiddleware,
75
+ allow_origins=["*"],
76
+ allow_methods=["*"],
77
+ allow_headers=["*"],
78
+ )
79
+
80
+ # ---------------------------------------------------------------------------
81
+ # Gradio UI State (for interactive UI)
82
  # ---------------------------------------------------------------------------
 
83
 
84
+ ui_env = QuantumCircuitEnvironment(seed=42)
85
  current_obs = None
86
  step_history: list = []
87
 
 
88
  # ---------------------------------------------------------------------------
89
+ # Gradio Helper Functions
90
  # ---------------------------------------------------------------------------
91
 
92
  def _format_circuit(obs) -> str:
 
95
  return "(empty circuit)"
96
  lines = []
97
  for i, g in enumerate(obs.circuit_gates):
98
+ gate = g.get("gate", "?")
99
  qubits = g.get("qubits", [])
100
+ param = g.get("parameter")
101
+ q_str = ",".join(str(q) for q in qubits)
102
  if param is not None:
103
  lines.append(f" {i+1:>2}. {gate}({q_str}, θ={param:.4f})")
104
  else:
 
111
  if not obs:
112
  return ""
113
  meta = obs.metadata or {}
114
+ fid = round(meta.get("fidelity_score", obs.fidelity), 4)
115
+ eff = round(meta.get("efficiency_score", 0), 4)
116
+ noi = round(meta.get("noise_score", 0), 4)
117
+ con = round(meta.get("constraints_score", 0), 4)
118
+ agg = round(meta.get("aggregate_score", obs.score), 4)
119
  return (
120
  f"Fidelity: {fid}\n"
121
  f"Efficiency: {eff}\n"
 
142
 
143
 
144
  # ---------------------------------------------------------------------------
145
+ # Gradio Callbacks
146
  # ---------------------------------------------------------------------------
147
 
148
  TASK_MAP = {
149
+ "Bell State (Easy)": "easy",
150
+ "GHZ State (Medium)": "medium",
151
+ "Unitary Approx (Hard)": "hard",
 
 
 
 
152
  }
153
 
154
 
155
  def do_reset(task_name):
156
  global current_obs, step_history
157
  task_id = TASK_MAP.get(task_name, "easy")
158
+ current_obs = ui_env.reset(task_id=task_id)
159
  step_history = []
160
  return (
161
  _status(current_obs, f"Reset to: {task_name}"),
 
174
  return _status(current_obs), _format_circuit(current_obs), _format_scores(current_obs), "\n".join(step_history)
175
 
176
  try:
177
+ at = ActionType(action_type)
178
+ gate = None
179
  qubits = []
180
+ param = None
181
 
182
  if at == ActionType.ADD:
183
  gate = GateType(gate_type) if gate_type else None
184
  if gate in (GateType.CNOT,):
185
  qubits = [int(qubit_0), int(qubit_1)]
 
 
186
  else:
187
  qubits = [int(qubit_0)]
188
  if gate in (GateType.RX, GateType.RZ) and parameter is not None:
 
195
  if parameter is not None:
196
  param = float(parameter)
197
 
198
+ action = QuantumAction(action_type=at, gate=gate, qubits=qubits, parameter=param)
199
+ current_obs = ui_env.step(action)
200
 
201
  except Exception as exc:
202
  logger.exception("Step error: %s", exc)
 
233
 
234
  def create_gradio_app() -> gr.Blocks:
235
  with gr.Blocks(title="Quantum Circuit Optimizer") as demo:
236
+ gr.Markdown(
237
+ """# Quantum Circuit Optimizer
238
+ Build quantum circuits step-by-step to maximize fidelity with target states.
239
+
240
+ **Available Tasks:**
241
+ - Bell State (Easy): 2 qubits, no noise
242
+ - GHZ State (Medium): 3 qubits, depolarizing noise
243
+ - Unitary Approximation (Hard): 2 qubits, thermal noise
244
+ """
245
+ )
246
 
 
 
 
247
  with gr.Row():
248
+ task_dd = gr.Dropdown(choices=list(TASK_MAP.keys()), value="Bell State (Easy)", label="Task")
249
  reset_btn = gr.Button("Reset Environment", variant="primary")
250
 
251
  with gr.Row():
252
  action_dd = gr.Dropdown(choices=["ADD", "REMOVE", "SWAP", "PARAM", "STOP"], value="ADD", label="Action Type")
253
+ gate_dd = gr.Dropdown(choices=["H", "X", "CNOT", "RX", "RZ"], value="H", label="Gate (for ADD)")
254
 
255
  with gr.Row():
256
+ qubit_0 = gr.Number(value=0, label="Qubit 0", precision=0)
257
+ qubit_1 = gr.Number(value=1, label="Qubit 1 (CNOT/SWAP)", precision=0)
258
  parameter = gr.Number(value=None, label="Parameter (RX/RZ angle)", precision=4)
259
 
260
  step_btn = gr.Button("Execute Step", variant="secondary")
261
 
262
+ status_out = gr.Textbox(label="Status", lines=3, interactive=False)
263
+ circuit_out = gr.Textbox(label="Circuit", lines=10, interactive=False)
264
+ scores_out = gr.Textbox(label="Scores", lines=6, interactive=False)
265
+ history_out = gr.Textbox(label="Step History", lines=8, interactive=False)
 
266
 
 
267
  OUTS = [status_out, circuit_out, scores_out, history_out]
268
 
269
+ reset_btn.click(fn=do_reset, inputs=[task_dd], outputs=OUTS)
270
+ step_btn.click(fn=do_step, inputs=[action_dd, gate_dd, qubit_0, qubit_1, parameter], outputs=OUTS)
271
 
272
  return demo
273
 
274
 
275
  # ---------------------------------------------------------------------------
276
+ # Mount Gradio UI and add custom endpoints
277
  # ---------------------------------------------------------------------------
278
+
279
  demo = create_gradio_app()
280
+ app = gr.mount_gradio_app(app, demo, path="/ui")
281
+
282
+
283
+ @app.get("/")
284
+ async def root():
285
+ """Root endpoint - redirect to Gradio UI."""
286
+ return RedirectResponse(url="/ui")
287
+
288
+
289
+ @app.get("/health")
290
+ async def health():
291
+ """Health check endpoint."""
292
+ return {"status": "ok", "environment": "quantum_circuit_optimizer"}
293
+
294
+
295
+ @app.get("/tasks")
296
+ async def list_tasks():
297
+ """List available quantum circuit optimization tasks."""
298
+ return {
299
+ "tasks": [
300
+ {
301
+ "id": "easy",
302
+ "name": "Bell State",
303
+ "description": "Generate Bell state (|00>+|11>)/sqrt(2) - 2 qubits, no noise",
304
+ "qubits": 2,
305
+ "difficulty": "easy"
306
+ },
307
+ {
308
+ "id": "medium",
309
+ "name": "GHZ State",
310
+ "description": "Generate GHZ state (|000>+|111>)/sqrt(2) - 3 qubits, depolarizing noise",
311
+ "qubits": 3,
312
+ "difficulty": "medium"
313
+ },
314
+ {
315
+ "id": "hard",
316
+ "name": "Unitary Approximation",
317
+ "description": "Approximate Ry(pi/3)@Rz(pi/4).CNOT - 2 qubits, thermal noise",
318
+ "qubits": 2,
319
+ "difficulty": "hard"
320
+ }
321
+ ]
322
+ }
323
 
 
 
324
 
325
  # ---------------------------------------------------------------------------
326
+ # Entry Point
327
  # ---------------------------------------------------------------------------
328
+
329
+ def main():
330
+ """Run the quantum circuit optimization server from the command line."""
331
+ import argparse
332
  import uvicorn
333
+
334
+ parser = argparse.ArgumentParser(description="Quantum Circuit Optimization Environment Server")
335
+ parser.add_argument("--host", default="0.0.0.0", help="Host to bind to")
336
+ parser.add_argument("--port", type=int, default=7860, help="Port to bind to")
337
+ parser.add_argument("--reload", action="store_true", help="Enable auto-reload")
338
+ args = parser.parse_args()
339
+
340
+ uvicorn.run(app, host=args.host, port=args.port, reload=args.reload)
341
+
342
+
343
+ if __name__ == "__main__":
344
+ main()