Spaces:
Sleeping
Sleeping
File size: 8,772 Bytes
0f31dfd 3699e1a 0f31dfd 3699e1a 0f31dfd 3699e1a 0f31dfd 3699e1a 0f31dfd 3699e1a 0f31dfd 3699e1a 0f31dfd 3699e1a 0f31dfd 3699e1a 0f31dfd 3699e1a 0f31dfd 3699e1a 0f31dfd 3699e1a 1e82ffa 3699e1a 1e82ffa 0f31dfd 1e82ffa 0f31dfd 3699e1a 0f31dfd 3699e1a 0f31dfd 1e82ffa 0f31dfd 3699e1a 0f31dfd 3699e1a 0f31dfd 1e82ffa 0f31dfd 1e82ffa 0f31dfd | 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 | import gradio as gr
import requests
import json
import time
import os
from huggingface_hub import HfApi
BASE_URL = "https://lap-quantum-qpu-1-api.hf.space"
HF_TOKEN = os.getenv("HF_TOKEN", "")
REPO_ID = "Reality123b/qpu1-experiments"
def run_on_qpu(code, timeout=120):
try:
resp = requests.post(
f"{BASE_URL}/script",
json={"code": code, "session_id": "qpu1-experiments"},
timeout=timeout,
headers={"Content-Type": "application/json"}
)
result = resp.json()
if result.get("success"):
return result.get("output", "No output")
return f"Error: {result.get('error', 'Unknown error')}"
except Exception as e:
return f"Connection error: {str(e)}"
def health_check():
try:
resp = requests.get(f"{BASE_URL}/health", timeout=10)
return json.dumps(resp.json(), indent=2)
except Exception as e:
return f"Error: {str(e)}"
def run_bell_state():
return run_on_qpu('q = Qreg(2)\nq.H(0)\nq.CNOT(0, 1)\nprint(q.measure())')
def run_ghz(n_qubits):
n = int(n_qubits)
cnots = "\n".join([f"q.CNOT(0, {i})" for i in range(1, n)])
return run_on_qpu(f"q = Qreg({n})\nq.H(0)\n{cnots}\nprint(q.measure())")
def run_superposition(n_qubits):
n = int(n_qubits)
code = f"q = Qreg({n})\nq.H_all()\nresult = q.measure()\nprint(f'Result: {{result[:80]}}...')\nprint(f'Total qubits: {n}')\nprint(f'Ones: {{result.count(\"1\")}}/{n}')"
return run_on_qpu(code)
def run_bell_correlation(trials):
n = int(trials)
code = f"n={n}\ncorr=0\nfor _ in range(n):\n q=Qreg(2)\n q.H(0)\n q.CNOT(0,1)\n r=q.measure()\n if r in['00','11']:corr+=1\nprint(f'Correlation: {{corr/n*100:.1f}}%')\nprint(f'Correlated pairs: {{corr}}/{n}')"
return run_on_qpu(code)
def run_long_range(n_qubits):
n = int(n_qubits)
code = f"import time\nq = Qreg({n})\nq.H(0)\nq.CNOT(0, {n-1})\nstart = time.time()\nresult = q.measure()\nelapsed = time.time() - start\nprint(f'Qubits: {n:,}')\nprint(f'Measurement time: {{elapsed*1000:.1f}}ms')\nprint(f'Qubit 0: {{result[0]}}')\nprint(f'Qubit {n-1:,}: {{result[{n-1}]}}')\nprint(f'Entangled: {{result[0] == result[{n-1}]}}')"
return run_on_qpu(code, timeout=300)
def run_benchmark():
code = "import time\nq = Qreg(100000)\nstart = time.time()\nfor _ in range(1000):\n q.H(0)\nelapsed = time.time() - start\nprint(f'1000 H gates on 100K qubit register')\nprint(f'Time: {elapsed*1000:.1f}ms')\nprint(f'Gate speed: {1000/elapsed/1e6:.1f}M gates/s')"
return run_on_qpu(code)
def run_teleportation():
code = "q = Qreg(3)\nq.X(0)\nq.H(1)\nq.CNOT(1, 2)\nq.CNOT(0, 1)\nq.H(0)\nresult = q.measure()\nprint(f'Full state: {result}')\nprint(f'Qubit 2 (teleported): {result[2]}')"
return run_on_qpu(code)
def run_deutsch_jozsa():
code = "q = Qreg(2)\nq.X(1)\nq.H(0)\nq.H(1)\nq.CNOT(0, 1)\nq.H(0)\nresult = q.measure()\nverdict = 'BALANCED' if result[0] == '1' else 'CONSTANT'\nprint(f'Measurement: {result}')\nprint(f'Function is: {verdict}')"
return run_on_qpu(code)
def run_bernstein_vazirani():
code = "q = Qreg(4)\nq.X(3)\nq.H(0)\nq.H(1)\nq.H(2)\nq.H(3)\nq.CNOT(0, 3)\nq.CNOT(2, 3)\nq.H(0)\nq.H(1)\nq.H(2)\nresult = q.measure()\nsecret = result[:3]\nprint(f'Full measurement: {result}')\nprint(f'Recovered secret: {secret}')\nprint(f'Expected: 101')\nprint(f'Correct: {secret == \"101\"}')"
return run_on_qpu(code)
def run_custom_code(code):
return run_on_qpu(code)
def run_all_experiments():
lines = []
lines.append("=" * 60)
lines.append(" QPU-1 QUANTUM PROCESSING UNIT — LIVE RESULTS")
lines.append(" Powered by Lap Quantum")
lines.append("=" * 60)
experiments = [
("[0] QPU-1 HEALTH", health_check),
("[1] BELL STATE (2 qubits)", run_bell_state),
("[2] GHZ STATE (5 qubits)", lambda: run_ghz(5)),
("[3] SUPERPOSITION (20 qubits)", lambda: run_superposition(20)),
("[4] BELL CORRELATION (50 trials)", lambda: run_bell_correlation(50)),
("[5] QUANTUM TELEPORTATION", run_teleportation),
("[6] DEUTSCH-JOZSA ALGORITHM", run_deutsch_jozsa),
("[7] BERNSTEIN-VAZIRANI (secret=101)", run_bernstein_vazirani),
("[8] LONG-RANGE ENTANGLEMENT (1M qubits)", lambda: run_long_range(1000000)),
("[9] GATE SPEED BENCHMARK", run_benchmark),
]
for title, fn in experiments:
lines.append(f"\n{title}")
lines.append("-" * 40)
lines.append(fn())
lines.append("\n" + "=" * 60)
lines.append(" ALL EXPERIMENTS COMPLETE!")
lines.append("=" * 60)
return "\n".join(lines)
# ===== RUN ON STARTUP & SAVE RESULTS =====
print(">>> Running quantum experiments on QPU-1...")
STARTUP_RESULTS = run_all_experiments()
print(STARTUP_RESULTS)
# Save results to repo so they can be read
try:
with open("/tmp/results.txt", "w") as f:
f.write(STARTUP_RESULTS)
api = HfApi(token=HF_TOKEN)
api.upload_file(
path_or_fileobj="/tmp/results.txt",
path_in_repo="results.txt",
repo_id=REPO_ID,
repo_type="space",
)
print(">>> Results saved to results.txt in repo!")
except Exception as e:
print(f">>> Could not save results: {e}")
CSS = """
.main-title { text-align: center; background: linear-gradient(135deg, #8b5cf6, #6366f1, #3b82f6); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 2.5em; font-weight: 800; }
.subtitle { text-align: center; color: #888; font-size: 1.1em; }
"""
with gr.Blocks(title="QPU-1 Experiments", css=CSS, theme=gr.themes.Soft()) as app:
gr.HTML("<h1 class='main-title'>⚛️ QPU-1 Experiments</h1>")
gr.HTML("<p class='subtitle'>Real quantum circuits on Lap Quantum's QPU-1</p>")
with gr.Tab("🚀 Run All"):
gr.Markdown("### Startup Results (ran when Space loaded)")
startup_box = gr.Textbox(label="Results", lines=45, value=STARTUP_RESULTS, show_copy_button=True)
rerun_btn = gr.Button("🔄 Re-run All", variant="primary", size="lg")
fresh_box = gr.Textbox(label="Fresh Results", lines=45, show_copy_button=True)
rerun_btn.click(fn=run_all_experiments, outputs=fresh_box)
with gr.Tab("🔬 Individual"):
with gr.Row():
with gr.Column():
gr.Markdown("### Bell State"); bell_btn = gr.Button("Run"); bell_out = gr.Textbox(lines=2); bell_btn.click(fn=run_bell_state, outputs=bell_out)
gr.Markdown("### GHZ State"); ghz_n = gr.Slider(2, 20, value=5, step=1, label="Qubits"); ghz_btn = gr.Button("Run GHZ"); ghz_out = gr.Textbox(lines=2); ghz_btn.click(fn=run_ghz, inputs=ghz_n, outputs=ghz_out)
gr.Markdown("### Superposition"); sup_n = gr.Slider(1, 100, value=10, step=1, label="Qubits"); sup_btn = gr.Button("Run"); sup_out = gr.Textbox(lines=3); sup_btn.click(fn=run_superposition, inputs=sup_n, outputs=sup_out)
gr.Markdown("### Bell Correlation"); corr_n = gr.Slider(10, 500, value=100, step=10, label="Trials"); corr_btn = gr.Button("Test"); corr_out = gr.Textbox(lines=3); corr_btn.click(fn=run_bell_correlation, inputs=corr_n, outputs=corr_out)
with gr.Column():
gr.Markdown("### Teleportation"); tp_btn = gr.Button("Run"); tp_out = gr.Textbox(lines=3); tp_btn.click(fn=run_teleportation, outputs=tp_out)
gr.Markdown("### Deutsch-Jozsa"); dj_btn = gr.Button("Run"); dj_out = gr.Textbox(lines=2); dj_btn.click(fn=run_deutsch_jozsa, outputs=dj_out)
gr.Markdown("### Bernstein-Vazirani"); bv_btn = gr.Button("Run"); bv_out = gr.Textbox(lines=4); bv_btn.click(fn=run_bernstein_vazirani, outputs=bv_out)
gr.Markdown("### Long-Range (1M qubits)"); lr_n = gr.Slider(1000, 1000000, value=1000000, step=1000, label="Qubits"); lr_btn = gr.Button("Run"); lr_out = gr.Textbox(lines=5); lr_btn.click(fn=run_long_range, inputs=lr_n, outputs=lr_out)
gr.Markdown("### Benchmark"); bench_btn = gr.Button("Run"); bench_out = gr.Textbox(lines=3); bench_btn.click(fn=run_benchmark, outputs=bench_out)
with gr.Tab("💻 Custom Code"):
code_input = gr.Code(language="python", lines=15, value="q = Qreg(3)\nq.H(0)\nq.CNOT(0, 1)\nq.CNOT(1, 2)\nprint(q.measure())")
custom_btn = gr.Button("▶️ Execute on QPU-1", variant="primary")
custom_out = gr.Textbox(label="Output", lines=8, show_copy_button=True)
custom_btn.click(fn=run_custom_code, inputs=code_input, outputs=custom_out)
with gr.Tab("💚 Health"):
health_btn = gr.Button("Check QPU-1 Health", variant="primary")
health_out = gr.Textbox(lines=10)
health_btn.click(fn=health_check, outputs=health_out)
if __name__ == "__main__":
app.launch()
|