The question
Solve two three-switch puzzles, then compare local readout with teleporting the final bit.
Circuit & method
Two Grover iterations amplify answers 010 and 101. Compare direct and teleported C readout on a calibration-selected top chain and a typical chain; each case uses 256 shots.
Results
Pooling both puzzles, the top chain returned 402/512 exact direct answers and 357/512 teleported answers. The typical chain returned 429/512 and 361/512.

What this supports
Percentages are rounded for reading. The original integer counts, physical layouts, settings and available uncertainty calculations remain in the records below. Sampling intervals do not account for drift or every systematic error.
Full experiment record
Every top-level field from the primary hardware JSON is reproduced below, including the complete saved measurement distributions where present. Field names and outcome strings retain their original order and spelling.
- Switch-puzzles-hardware.jsonQuantum Field Report.pdf / Experiment-results.zip · 8,278 bytes
backend
ibm_kingston
map_job
dc0fg8inj2vs73ddulv0
selected
{
"best": {
"path": [
68,
67,
57,
47,
48
],
"score": 0.22510567572728113,
"rank": 1,
"map_correct": [
249,
251,
250,
246,
249
],
"edge_errors": [
0.0012055274867526777,
0.0016377401830433569,
0.0016177717764823407,
0.0025028908255529947
]
},
"typical": {
"path": [
124,
123,
136,
143,
142
],
"score": 0.40480304839873016,
"rank": 396,
"map_correct": [
242,
246,
242,
233,
239
],
"edge_errors": [
0.0016624278069253817,
0.0013988161687761291,
0.0016179233040090335,
0.0011756589091689307
]
}
}ranking
{
"candidate_count": 790,
"median_score": 0.4046149189394884,
"cz_weights": [
24.0,
28.0,
0.5,
0.5
],
"method": "sum negative log smoothed graph pass rates plus native CZ workload weighted negative log CZ success"
}settings
[
{
"chain": "best",
"puzzle": "odd",
"mode": "teleport",
"native_cz_per_link": [
24,
28,
1,
1
]
},
{
"chain": "best",
"puzzle": "odd",
"mode": "direct",
"native_cz_per_link": [
24,
28,
0,
0
]
},
{
"chain": "typical",
"puzzle": "odd",
"mode": "teleport",
"native_cz_per_link": [
24,
28,
1,
1
]
},
{
"chain": "best",
"puzzle": "even",
"mode": "direct",
"native_cz_per_link": [
24,
28,
0,
0
]
},
{
"chain": "best",
"puzzle": "even",
"mode": "teleport",
"native_cz_per_link": [
24,
28,
1,
1
]
},
{
"chain": "typical",
"puzzle": "even",
"mode": "direct",
"native_cz_per_link": [
24,
28,
0,
0
]
},
{
"chain": "typical",
"puzzle": "odd",
"mode": "direct",
"native_cz_per_link": [
24,
28,
0,
0
]
},
{
"chain": "typical",
"puzzle": "even",
"mode": "teleport",
"native_cz_per_link": [
24,
28,
1,
1
]
}
]mid_readout
measure_2
solutions_ABC
{
"odd": "010",
"even": "101"
}stage
done
tag
switch-puzzles-20261120-v1-test
shots_per_circuit
256
job_id
dc0fgc2nj2vs73ddum40
counts
[
{
"00010": 51,
"11011": 6,
"01011": 9,
"01010": 42,
"11010": 39,
"10010": 44,
"00011": 9,
"00111": 2,
"11100": 3,
"01101": 2,
"00001": 2,
"11101": 3,
"10011": 8,
"00000": 2,
"11001": 2,
"00110": 1,
"01110": 5,
"10101": 3,
"11000": 5,
"10110": 3,
"10001": 3,
"11111": 1,
"10111": 1,
"01100": 1,
"10000": 2,
"10100": 1,
"00100": 1,
"00101": 4,
"01000": 1
},
{
"00010": 209,
"00100": 9,
"00001": 12,
"00110": 11,
"00111": 5,
"00000": 5,
"00011": 2,
"00101": 3
},
{
"01010": 55,
"00010": 57,
"11010": 34,
"10110": 3,
"00011": 5,
"10010": 34,
"10000": 5,
"10011": 5,
"11111": 4,
"10101": 3,
"01001": 3,
"10100": 2,
"01000": 5,
"11100": 1,
"11110": 1,
"11000": 5,
"00000": 7,
"01111": 2,
"11001": 1,
"11011": 4,
"11101": 1,
"00101": 1,
"01110": 1,
"10001": 4,
"10111": 1,
"00110": 3,
"00100": 4,
"01101": 1,
"01100": 1,
"00111": 3
},
{
"00101": 193,
"00110": 13,
"00001": 13,
"00100": 8,
"00010": 8,
"00000": 9,
"00111": 7,
"00011": 5
},
{
"00001": 3,
"01110": 2,
"11110": 4,
"00100": 5,
"11101": 49,
"11100": 10,
"10101": 56,
"01000": 2,
"01101": 32,
"01011": 2,
"11001": 3,
"00101": 44,
"10100": 9,
"00000": 2,
"00011": 2,
"11011": 1,
"10001": 3,
"00110": 2,
"11111": 4,
"11010": 2,
"10000": 4,
"10011": 1,
"01100": 1,
"01001": 2,
"01010": 2,
"10110": 3,
"10010": 5,
"00010": 1
},
{
"00101": 219,
"00011": 7,
"00111": 8,
"00010": 6,
"00001": 8,
"00100": 3,
"00110": 2,
"00000": 3
},
{
"00100": 7,
"00010": 210,
"00000": 5,
"00011": 9,
"00111": 8,
"00110": 9,
"00101": 3,
"00001": 5
},
{
"01010": 4,
"11100": 7,
"00101": 49,
"10101": 42,
"11101": 45,
"01101": 45,
"00011": 2,
"01001": 6,
"01100": 4,
"00100": 9,
"10010": 3,
"10100": 6,
"00001": 1,
"10000": 4,
"00000": 1,
"11110": 2,
"11111": 4,
"10011": 2,
"10111": 3,
"10001": 4,
"11001": 2,
"00110": 2,
"01000": 2,
"01111": 1,
"01110": 2,
"10110": 2,
"11000": 1,
"01011": 1
}
]metrics
{
"caller": "qiskit",
"qiskit_version": "qiskit_ibm_runtime-0.52.1,qiskit-2.6.2*,qiskit_aer-0.17.2",
"timestamps": {
"created": "2026-11-21T01:47:28.202795Z",
"finished": "2026-11-21T01:47:33.872868Z",
"running": "2026-11-21T01:47:29.441738Z"
},
"usage": {
"qpu_charge_time_seconds": 3,
"value": 0.037729,
"unit": "resource_units",
"status": "complete",
"details": [
{
"value": 0.037729,
"unit": "resource_units",
"metric": {
"id": "caffe3ca-729c-5750-8777-df63bbf8bfd9",
"value": 3
}
}
]
},
"circuits_execution_time_ns": 547644672
}rows
[
{
"chain": "best",
"puzzle": "odd",
"mode": "teleport",
"native_cz_per_link": [
24,
28,
1,
1
],
"correct": 176
},
{
"chain": "best",
"puzzle": "odd",
"mode": "direct",
"native_cz_per_link": [
24,
28,
0,
0
],
"correct": 209
},
{
"chain": "typical",
"puzzle": "odd",
"mode": "teleport",
"native_cz_per_link": [
24,
28,
1,
1
],
"correct": 180
},
{
"chain": "best",
"puzzle": "even",
"mode": "direct",
"native_cz_per_link": [
24,
28,
0,
0
],
"correct": 193
},
{
"chain": "best",
"puzzle": "even",
"mode": "teleport",
"native_cz_per_link": [
24,
28,
1,
1
],
"correct": 181
},
{
"chain": "typical",
"puzzle": "even",
"mode": "direct",
"native_cz_per_link": [
24,
28,
0,
0
],
"correct": 219
},
{
"chain": "typical",
"puzzle": "odd",
"mode": "direct",
"native_cz_per_link": [
24,
28,
0,
0
],
"correct": 210
},
{
"chain": "typical",
"puzzle": "even",
"mode": "teleport",
"native_cz_per_link": [
24,
28,
1,
1
],
"correct": 181
}
]Supporting records & original figures
- Switch-puzzles-chain-map.pngQuantum Field Report.pdf / Experiment-results.zip · 326,842 bytes
Simulation & checks
These are the supplied simulator records and their preserved variants. Their model, seed, settings and results appear exactly as saved. Shared simulator references on fresh-map pages describe the ideal graph protocol, rather than a new hardware-matched calibration.
- Switch-puzzles-simulator.jsonQuantum Field Report.pdf / Experiment-results.zip · 1,438 bytes
field-report/outputs/Switch-puzzles-simulator.json · full record
{
"solutions_ABC": {
"odd": "010",
"even": "101"
},
"shots_each": 256,
"ideal_full_answer_probability": 0.9453125,
"results": {
"odd_direct": {
"counts": {
"00010": 244,
"00100": 6,
"00111": 4,
"00110": 1,
"00000": 1
},
"correct": 244
},
"odd_teleport": {
"counts": {
"01010": 61,
"01100": 2,
"10010": 62,
"10001": 1,
"11010": 55,
"11100": 1,
"00010": 63,
"00101": 1,
"01101": 1,
"01110": 2,
"10100": 2,
"00111": 1,
"10011": 1,
"01000": 1,
"11110": 1,
"11101": 1
},
"correct": 241
},
"even_direct": {
"counts": {
"00101": 240,
"00001": 3,
"00010": 5,
"00000": 2,
"00100": 3,
"00011": 2,
"00110": 1
},
"correct": 240
},
"even_teleport": {
"counts": {
"11101": 54,
"00101": 62,
"11110": 3,
"01101": 62,
"10101": 62,
"10010": 1,
"01100": 2,
"00111": 2,
"00110": 1,
"10100": 1,
"01111": 1,
"00001": 1,
"10011": 1,
"11010": 1,
"10001": 1,
"01000": 1
},
"correct": 240
}
},
"seed": 20261120
}Source code
Original experiment and verification programs are preserved byte for byte. These are historical listings; dependencies, authentication prompts and machine-specific input paths may need adjustment before a rerun.
- run_switch_puzzles.pyQuantum Field Report.pdf / Experiment-source.zip · 9,663 bytes
- switch_puzzles.pyQuantum Field Report.pdf / Experiment-source.zip · 3,881 bytes
- check_switch_puzzles.pyQuantum Field Report.pdf / Experiment-source.zip · 1,845 bytes
- run_switch_puzzles.pyThrough the Noise Wall.pdf / Kingston measurements and source.zip · 9,663 bytes
- switch_puzzles.pyThrough the Noise Wall.pdf / Kingston measurements and source.zip · 3,881 bytes
field-report/outputs/run_switch_puzzles.py · complete source
"""Fresh graph map, then controlled Grover/teleport comparison on the same QPU."""
import getpass
import json
import logging
import math
import random
import sys
import time
import traceback
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
from qiskit import transpile
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2
import graph156
from switch_puzzles import ROOT, SHOTS, SEED, PARITIES, classical, circuit, score
MAP=ROOT/"Switch-puzzles-fresh-map.json"
TEST=ROOT/"Switch-puzzles-hardware.json"
BASE_TAG="switch-puzzles-20261120-v1"
def load(path):
return json.loads(path.read_text()) if path.exists() else {}
def execute(service,backend,path,tag,rec,make):
if rec.get("stage")=="done":
return rec
if rec.get("stage")=="failed":
raise RuntimeError("Previously submitted job failed")
if rec.get("job_id"):
job=service.job(rec["job_id"])
elif rec.get("stage")=="submitting":
matches=service.jobs(job_tags=[tag],limit=2)
if len(matches)!=1:
raise RuntimeError("Prior submission must be reconciled")
job=matches[0]
else:
circuits=make()
sampler=SamplerV2(mode=backend,options={"max_execution_time":30,"environment":{"job_tags":[tag]},
"twirling":{"enable_measure":False,"enable_gates":False},
"dynamical_decoupling":{"enable":False}})
rec.update(stage="submitting",tag=tag,shots_per_circuit=SHOTS)
with path.open("x",encoding="utf8") as f:
json.dump(rec,f,indent=2)
job=sampler.run(circuits,shots=SHOTS)
rec.update(stage="submitted",job_id=job.job_id())
graph156.save(path,rec)
pubs=job.result()
rec["counts"]=[pub.data.c.get_counts() for pub in pubs]
assert all(sum(c.values())==SHOTS for c in rec["counts"])
for _ in range(24):
metrics=job.metrics()
if metrics.get("usage",{}).get("status")=="complete":
break
time.sleep(5)
rec.update(stage="done",metrics=metrics)
graph156.save(path,rec)
return rec
def compile_map(b):
p=b.properties(refresh=True)
if p.faulty_qubits():
raise ValueError("Processor has flagged faulty qubits")
bad={tuple(sorted(g.qubits)) for g in p.faulty_gates() if len(g.qubits)==2}
geo=graph156.geometry(e for e in b.coupling_map.get_edges() if tuple(sorted(e)) not in bad)
isa=transpile(graph156.circuits(geo),b,initial_layout=list(range(156)),optimization_level=1,
seed_transpiler=SEED,num_processes=1,routing_method="none")
for qc in isa:
b.check_faulty(qc)
edges=[sorted(qc.find_bit(q).index for q in op.qubits) for op in qc.data if len(op.qubits)==2]
measured={qc.find_bit(op.clbits[0]).index:qc.find_bit(op.qubits[0]).index
for op in qc.data if op.operation.name=="measure"}
assert sorted(edges)==geo["edges"] and measured==dict(enumerate(range(156)))
return geo,isa
def compile_one(b,path,puzzle,mode,fast):
q=circuit(puzzle,mode,fast)
isa=transpile(q,b,initial_layout=list(path),optimization_level=1,routing_method="none",seed_transpiler=SEED)
b.check_faulty(isa)
measured={}
flags=[]
links=Counter()
for op in isa.data:
gate=op.operation
physical=[isa.find_bit(q).index for q in op.qubits]
if gate.name!="barrier":
assert set(physical)<=set(path)
if gate.name=="cz":
a,c=sorted(path.index(x) for x in physical)
assert c==a+1
links[a]+=1
if gate.name in ("measure","measure_2"):
measured[isa.find_bit(op.clbits[0]).index]=physical[0]
if gate.name=="if_else":
bit,value=gate.condition
flag=isa.find_bit(bit).index
assert physical==[path[4]] and value==1 and flag in measured
flags.append(flag)
expected={2:path[0],1:path[1],0:path[2]}
if mode=="teleport":
expected.update({0:path[4],3:path[2],4:path[3]})
assert flags==[4,3]
assert measured==expected
return isa,[links[i] for i in range(4)]
def paths_and_scores(b,geo,analysis):
neighbors=[[] for _ in range(156)]
err={}
for a,c in geo["edges"]:
prop=b.target["cz"].get((a,c)) or b.target["cz"].get((c,a))
if prop is None or prop.error is None or not 0<=prop.error<1:
continue
neighbors[a].append(c)
neighbors[c].append(a)
err[a,c]=err[c,a]=prop.error
def extend(path):
if len(path)==5:
yield tuple(path)
return
for q in neighbors[path[-1]]:
if q not in path:
yield from extend(path+[q])
paths=[p for i in range(156) for p in extend([i])]
# Common pulse basis and routing-free layout: edge counts are verified again on both paths.
# Rank by a heuristic, not an estimated circuit fidelity.
gate_weights=[0.]*4
for puzzle in PARITIES:
for mode in ("direct","teleport"):
_,counts=compile_one(b,paths[0],puzzle,mode,False)
gate_weights=[x+n/4 for x,n in zip(gate_weights,counts)]
vertex=[-math.log((v+0.5)/(SHOTS+1)) for v in analysis["correct_by_qubit"]]
ranked=sorted((sum(vertex[q] for q in path)+sum(w*-math.log1p(-err[e]) for w,e in zip(gate_weights,zip(path,path[1:]))),path) for path in paths)
median=(ranked[(len(ranked)-1)//2][0]+ranked[len(ranked)//2][0])/2
best=ranked[0]
typical=min((entry for entry in ranked if set(entry[1]).isdisjoint(best[1])),
key=lambda entry:(abs(entry[0]-median),entry))
selected={}
for label,entry in (("best",best),("typical",typical)):
s,path=entry
selected[label]={"path":list(path),"score":s,"rank":ranked.index(entry)+1,
"map_correct":[analysis["correct_by_qubit"][q] for q in path],
"edge_errors":[err[e] for e in zip(path,path[1:])]}
return selected,{"candidate_count":len(ranked),"median_score":median,"cz_weights":gate_weights,
"method":"sum negative log smoothed graph pass rates plus native CZ workload weighted negative log CZ success"}
def run():
if not (ROOT/"Switch-puzzles-simulator.json").exists() or not sys.stdin.isatty():
raise RuntimeError("Simulate first and use a private console")
if load(TEST).get("rows"):
return
token=getpass.getpass("IBM Cloud API key (hidden): ").strip()
if not token:
return
service=QiskitRuntimeService(channel="ibm_quantum_platform",token=token,plans_preference=["open"],region="us-east")
m=load(MAP)
if m:
b=service.backend(m["backend"])
isa=None
else:
devices={b.name:b for b in service.backends(simulator=False,min_num_qubits=156) if not b.is_mock and b.num_qubits==156}
prepared={}
excluded={}
while True:
queues={n:b.status().to_dict() for n,b in devices.items()}
active=[n for n,s in queues.items() if s["operational"] and s["status_msg"].lower()=="active" and n not in excluded]
name=min(active,key=lambda n:(queues[n]["pending_jobs"],n))
b=devices[name]
if name in prepared:
break
try:
prepared[name]=compile_map(b)
except ValueError as e:
excluded[name]=str(e)
geo,isa=prepared[name]
m={"backend":name,"queues":queues,"excluded":excluded,"geometry":geo,
"queue_snapshot_utc":datetime.now(timezone.utc).isoformat()}
m=execute(service,b,MAP,BASE_TAG+"-map",m,lambda:isa)
analysis=graph156.analyze(m["geometry"],m["counts"])
m["analysis"]=analysis
graph156.save(MAP,m)
rec=load(TEST)
isa=[]
if not rec:
selected,ranking=paths_and_scores(b,m["geometry"],analysis)
cells=[(l,p,mode) for l in selected for p in PARITIES for mode in ("direct","teleport")]
random.Random(SEED).shuffle(cells)
fast=all(b.target.instruction_supported("measure_2",(q,)) for s in selected.values() for q in s["path"][2:4])
settings=[]
weights={}
for label,puzzle,mode in cells:
q,links=compile_one(b,selected[label]["path"],puzzle,mode,fast)
isa.append(q)
settings.append({"chain":label,"puzzle":puzzle,"mode":mode,"native_cz_per_link":links})
key=(puzzle,mode)
if key in weights:
assert weights[key]==links
weights[key]=links
assert ranking["cz_weights"]==[sum(v[i] for v in weights.values())/4 for i in range(4)]
rec={"backend":b.name,"map_job":m["job_id"],"selected":selected,"ranking":ranking,
"settings":settings,"mid_readout":"measure_2" if fast else "measure",
"solutions_ABC":classical()}
rec=execute(service,b,TEST,BASE_TAG+"-test",rec,lambda:isa)
assert len(rec["counts"])==len(rec["settings"])==8
rec["rows"]=[dict(s,correct=score(c,rec["solutions_ABC"][s["puzzle"]]))
for s,c in zip(rec["settings"],rec["counts"])]
graph156.save(TEST,rec)
print([(r["chain"],r["puzzle"],r["mode"],r["correct"]) for r in rec["rows"]])
if __name__=="__main__":
logging.disable(logging.CRITICAL)
try:
run()
except Exception as e:
frames=[[Path(f.filename).name,f.lineno,f.name] for f in traceback.extract_tb(e.__traceback__)]
graph156.save(ROOT.parent/"work"/"switch-puzzles-error.json",{"type":type(e).__name__,"frames":frames})
print(type(e).__name__)
input("Press Enter to close.")
field-report/outputs/switch_puzzles.py · complete source
"""Two three-switch Grover searches with direct or teleported C readout."""
import itertools
import json
from pathlib import Path
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Operator, Statevector
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime.circuit import MidCircuitMeasure
ROOT = Path(__file__).resolve().parent
SHOTS, SEED = 256, 20261120
PARITIES = {"odd":1,"even":0}
CHECK_GATES = [(1,0),(1,2),(0,1),(1,2),(2,1)]
def classical():
cases = list(itertools.product((0,1),repeat=3))
solutions = {}
for puzzle, parity in PARITIES.items():
hits = ["".join(map(str,(a,b,c))) for a,b,c in cases
if a!=b and b!=c and (a^b^c)==parity]
assert len(hits)==1
solutions[puzzle]=hits[0]
return solutions
def ccz(q):
# 4abc = a+b+c -(a XOR b) -(a XOR c) -(b XOR c) +(a XOR b XOR c).
# Eight nearest-neighbor CNOTs expose the parities and restore all inputs.
for i in range(3):
q.t(i)
labels=[1,2,4]
pending={3:-1,5:-1,6:-1,7:1}
for src,dst in [(0,1),(1,2)]*4:
q.cx(src,dst)
labels[dst]^=labels[src]
phase=pending.pop(labels[dst],0)
if phase==1:
q.t(dst)
elif phase==-1:
q.tdg(dst)
assert labels==[1,2,4] and not pending
def oracle(q,puzzle):
# Reversible checks replace A,B,C by A XOR B, B XOR C, A XOR B XOR C.
for src,dst in CHECK_GATES:
q.cx(src,dst)
if PARITIES[puzzle]==0:
q.x(2)
ccz(q)
if PARITIES[puzzle]==0:
q.x(2)
for src,dst in reversed(CHECK_GATES):
q.cx(src,dst)
def search(puzzle):
q=QuantumCircuit(3)
q.h(range(3))
for _ in range(2):
oracle(q,puzzle)
q.h(range(3))
q.x(range(3))
ccz(q)
q.x(range(3))
q.h(range(3))
return q
def circuit(puzzle,mode,fast=False):
q=QuantumCircuit(5,5,name=puzzle+"_"+mode)
q.compose(search(puzzle),[0,1,2],inplace=True)
q.barrier()
output=2
if mode=="teleport":
q.h(3)
q.cx(3,4)
q.cx(2,3)
q.h(2)
for wire,flag in ((2,3),(3,4)):
if fast:
q.append(MidCircuitMeasure(),[wire],[flag])
else:
q.measure(wire,flag)
with q.if_test((q.clbits[4],1)):
q.x(4)
with q.if_test((q.clbits[3],1)):
q.z(4)
output=4
q.measure([0,1,output],[2,1,0])
return q
def score(counts,key):
assert sum(counts.values())==SHOTS and all(len(w)==5 for w in counts)
return sum(n for bits,n in counts.items() if bits[-3:]==key)
def simulate():
solutions=classical()
sim=AerSimulator(method="statevector")
data={}
for puzzle,key in solutions.items():
check=QuantumCircuit(3)
oracle(check,puzzle)
diagonal=[-1 if format(i,"03b")[::-1]==key else 1 for i in range(8)]
assert np.allclose(Operator(check).data,np.diag(diagonal))
probs=Statevector.from_instruction(search(puzzle)).probabilities()
assert np.isclose(probs[int(key[::-1],2)],121/128)
for j,mode in enumerate(("direct","teleport")):
q=circuit(puzzle,mode)
qc=transpile(q,sim,optimization_level=0)
counts=sim.run(qc,shots=SHOTS,seed_simulator=SEED+2*PARITIES[puzzle]+j).result().get_counts()
if mode=="teleport":
assert len({s[:2] for s in counts})==4
data[puzzle+"_"+mode]={"counts":counts,"correct":score(counts,key)}
record={"solutions_ABC":solutions,"shots_each":SHOTS,"ideal_full_answer_probability":121/128,
"results":data,"seed":SEED}
(ROOT/"Switch-puzzles-simulator.json").write_text(json.dumps(record,indent=2))
print(solutions,{k:v["correct"] for k,v in data.items()})
if __name__=="__main__":
simulate()
field-report/work/check_switch_puzzles.py · complete source
import json
import math
from pathlib import Path
root=Path(__file__).resolve().parents[1]/"outputs"
h=json.loads((root/"Switch-puzzles-hardware.json").read_text())
m=json.loads((root/"Switch-puzzles-fresh-map.json").read_text())
print("backend",h["backend"],"queues",{k:v["pending_jobs"] for k,v in m["queues"].items()})
print("map",m["job_id"],m["metrics"]["usage"],m["analysis"]["mean_accuracy"])
print("puzzles",h["job_id"],h["metrics"]["usage"])
print(h["selected"],h["ranking"])
cells={}
for row,counts in zip(h["rows"],h["counts"]):
key=h["solutions_ABC"][row["puzzle"]]
hits=0
for sample,count in counts.items():
v=int(sample,2)
decoded="".join(str((v>>i)&1) for i in (2,1,0))
if decoded==key:
hits+=count
assert hits==row["correct"] and sum(counts.values())==256
cells[(row["chain"],row["puzzle"],row["mode"])]=hits
print(sorted(cells.items()))
def contrast(groups1,groups2):
terms=[]
vs=[]
for group in (groups1,groups2):
values=[cells[k]/256 for k in group]
terms.append(sum(values)/len(values))
vs.append(sum(p*(1-p)/255 for p in values)/len(values)**2)
d=terms[0]-terms[1]
half=1.96*math.sqrt(sum(vs))
return [round(100*x,2) for x in (terms[0],terms[1],d,d-half,d+half)]
print("pooled tele-direct",contrast([k for k in cells if k[2]=="teleport"],[k for k in cells if k[2]=="direct"]))
for mode in ("direct","teleport"):
print(mode,"best-typical",contrast([k for k in cells if k[0]=="best" and k[2]==mode],
[k for k in cells if k[0]=="typical" and k[2]==mode]))
for chain in ("best","typical"):
print(chain,"tele-direct",contrast([k for k in cells if k[0]==chain and k[2]=="teleport"],
[k for k in cells if k[0]==chain and k[2]=="direct"]))
noise-wall/source/run_switch_puzzles.py · complete source
"""Fresh graph map, then controlled Grover/teleport comparison on the same QPU."""
import getpass
import json
import logging
import math
import random
import sys
import time
import traceback
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
from qiskit import transpile
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2
import graph156
from switch_puzzles import ROOT, SHOTS, SEED, PARITIES, classical, circuit, score
MAP=ROOT/"Switch-puzzles-fresh-map.json"
TEST=ROOT/"Switch-puzzles-hardware.json"
BASE_TAG="switch-puzzles-20261120-v1"
def load(path):
return json.loads(path.read_text()) if path.exists() else {}
def execute(service,backend,path,tag,rec,make):
if rec.get("stage")=="done":
return rec
if rec.get("stage")=="failed":
raise RuntimeError("Previously submitted job failed")
if rec.get("job_id"):
job=service.job(rec["job_id"])
elif rec.get("stage")=="submitting":
matches=service.jobs(job_tags=[tag],limit=2)
if len(matches)!=1:
raise RuntimeError("Prior submission must be reconciled")
job=matches[0]
else:
circuits=make()
sampler=SamplerV2(mode=backend,options={"max_execution_time":30,"environment":{"job_tags":[tag]},
"twirling":{"enable_measure":False,"enable_gates":False},
"dynamical_decoupling":{"enable":False}})
rec.update(stage="submitting",tag=tag,shots_per_circuit=SHOTS)
with path.open("x",encoding="utf8") as f:
json.dump(rec,f,indent=2)
job=sampler.run(circuits,shots=SHOTS)
rec.update(stage="submitted",job_id=job.job_id())
graph156.save(path,rec)
pubs=job.result()
rec["counts"]=[pub.data.c.get_counts() for pub in pubs]
assert all(sum(c.values())==SHOTS for c in rec["counts"])
for _ in range(24):
metrics=job.metrics()
if metrics.get("usage",{}).get("status")=="complete":
break
time.sleep(5)
rec.update(stage="done",metrics=metrics)
graph156.save(path,rec)
return rec
def compile_map(b):
p=b.properties(refresh=True)
if p.faulty_qubits():
raise ValueError("Processor has flagged faulty qubits")
bad={tuple(sorted(g.qubits)) for g in p.faulty_gates() if len(g.qubits)==2}
geo=graph156.geometry(e for e in b.coupling_map.get_edges() if tuple(sorted(e)) not in bad)
isa=transpile(graph156.circuits(geo),b,initial_layout=list(range(156)),optimization_level=1,
seed_transpiler=SEED,num_processes=1,routing_method="none")
for qc in isa:
b.check_faulty(qc)
edges=[sorted(qc.find_bit(q).index for q in op.qubits) for op in qc.data if len(op.qubits)==2]
measured={qc.find_bit(op.clbits[0]).index:qc.find_bit(op.qubits[0]).index
for op in qc.data if op.operation.name=="measure"}
assert sorted(edges)==geo["edges"] and measured==dict(enumerate(range(156)))
return geo,isa
def compile_one(b,path,puzzle,mode,fast):
q=circuit(puzzle,mode,fast)
isa=transpile(q,b,initial_layout=list(path),optimization_level=1,routing_method="none",seed_transpiler=SEED)
b.check_faulty(isa)
measured={}
flags=[]
links=Counter()
for op in isa.data:
gate=op.operation
physical=[isa.find_bit(q).index for q in op.qubits]
if gate.name!="barrier":
assert set(physical)<=set(path)
if gate.name=="cz":
a,c=sorted(path.index(x) for x in physical)
assert c==a+1
links[a]+=1
if gate.name in ("measure","measure_2"):
measured[isa.find_bit(op.clbits[0]).index]=physical[0]
if gate.name=="if_else":
bit,value=gate.condition
flag=isa.find_bit(bit).index
assert physical==[path[4]] and value==1 and flag in measured
flags.append(flag)
expected={2:path[0],1:path[1],0:path[2]}
if mode=="teleport":
expected.update({0:path[4],3:path[2],4:path[3]})
assert flags==[4,3]
assert measured==expected
return isa,[links[i] for i in range(4)]
def paths_and_scores(b,geo,analysis):
neighbors=[[] for _ in range(156)]
err={}
for a,c in geo["edges"]:
prop=b.target["cz"].get((a,c)) or b.target["cz"].get((c,a))
if prop is None or prop.error is None or not 0<=prop.error<1:
continue
neighbors[a].append(c)
neighbors[c].append(a)
err[a,c]=err[c,a]=prop.error
def extend(path):
if len(path)==5:
yield tuple(path)
return
for q in neighbors[path[-1]]:
if q not in path:
yield from extend(path+[q])
paths=[p for i in range(156) for p in extend([i])]
# Common pulse basis and routing-free layout: edge counts are verified again on both paths.
# Rank by a heuristic, not an estimated circuit fidelity.
gate_weights=[0.]*4
for puzzle in PARITIES:
for mode in ("direct","teleport"):
_,counts=compile_one(b,paths[0],puzzle,mode,False)
gate_weights=[x+n/4 for x,n in zip(gate_weights,counts)]
vertex=[-math.log((v+0.5)/(SHOTS+1)) for v in analysis["correct_by_qubit"]]
ranked=sorted((sum(vertex[q] for q in path)+sum(w*-math.log1p(-err[e]) for w,e in zip(gate_weights,zip(path,path[1:]))),path) for path in paths)
median=(ranked[(len(ranked)-1)//2][0]+ranked[len(ranked)//2][0])/2
best=ranked[0]
typical=min((entry for entry in ranked if set(entry[1]).isdisjoint(best[1])),
key=lambda entry:(abs(entry[0]-median),entry))
selected={}
for label,entry in (("best",best),("typical",typical)):
s,path=entry
selected[label]={"path":list(path),"score":s,"rank":ranked.index(entry)+1,
"map_correct":[analysis["correct_by_qubit"][q] for q in path],
"edge_errors":[err[e] for e in zip(path,path[1:])]}
return selected,{"candidate_count":len(ranked),"median_score":median,"cz_weights":gate_weights,
"method":"sum negative log smoothed graph pass rates plus native CZ workload weighted negative log CZ success"}
def run():
if not (ROOT/"Switch-puzzles-simulator.json").exists() or not sys.stdin.isatty():
raise RuntimeError("Simulate first and use a private console")
if load(TEST).get("rows"):
return
token=getpass.getpass("IBM Cloud API key (hidden): ").strip()
if not token:
return
service=QiskitRuntimeService(channel="ibm_quantum_platform",token=token,plans_preference=["open"],region="us-east")
m=load(MAP)
if m:
b=service.backend(m["backend"])
isa=None
else:
devices={b.name:b for b in service.backends(simulator=False,min_num_qubits=156) if not b.is_mock and b.num_qubits==156}
prepared={}
excluded={}
while True:
queues={n:b.status().to_dict() for n,b in devices.items()}
active=[n for n,s in queues.items() if s["operational"] and s["status_msg"].lower()=="active" and n not in excluded]
name=min(active,key=lambda n:(queues[n]["pending_jobs"],n))
b=devices[name]
if name in prepared:
break
try:
prepared[name]=compile_map(b)
except ValueError as e:
excluded[name]=str(e)
geo,isa=prepared[name]
m={"backend":name,"queues":queues,"excluded":excluded,"geometry":geo,
"queue_snapshot_utc":datetime.now(timezone.utc).isoformat()}
m=execute(service,b,MAP,BASE_TAG+"-map",m,lambda:isa)
analysis=graph156.analyze(m["geometry"],m["counts"])
m["analysis"]=analysis
graph156.save(MAP,m)
rec=load(TEST)
isa=[]
if not rec:
selected,ranking=paths_and_scores(b,m["geometry"],analysis)
cells=[(l,p,mode) for l in selected for p in PARITIES for mode in ("direct","teleport")]
random.Random(SEED).shuffle(cells)
fast=all(b.target.instruction_supported("measure_2",(q,)) for s in selected.values() for q in s["path"][2:4])
settings=[]
weights={}
for label,puzzle,mode in cells:
q,links=compile_one(b,selected[label]["path"],puzzle,mode,fast)
isa.append(q)
settings.append({"chain":label,"puzzle":puzzle,"mode":mode,"native_cz_per_link":links})
key=(puzzle,mode)
if key in weights:
assert weights[key]==links
weights[key]=links
assert ranking["cz_weights"]==[sum(v[i] for v in weights.values())/4 for i in range(4)]
rec={"backend":b.name,"map_job":m["job_id"],"selected":selected,"ranking":ranking,
"settings":settings,"mid_readout":"measure_2" if fast else "measure",
"solutions_ABC":classical()}
rec=execute(service,b,TEST,BASE_TAG+"-test",rec,lambda:isa)
assert len(rec["counts"])==len(rec["settings"])==8
rec["rows"]=[dict(s,correct=score(c,rec["solutions_ABC"][s["puzzle"]]))
for s,c in zip(rec["settings"],rec["counts"])]
graph156.save(TEST,rec)
print([(r["chain"],r["puzzle"],r["mode"],r["correct"]) for r in rec["rows"]])
if __name__=="__main__":
logging.disable(logging.CRITICAL)
try:
run()
except Exception as e:
frames=[[Path(f.filename).name,f.lineno,f.name] for f in traceback.extract_tb(e.__traceback__)]
graph156.save(ROOT.parent/"work"/"switch-puzzles-error.json",{"type":type(e).__name__,"frames":frames})
print(type(e).__name__)
input("Press Enter to close.")
noise-wall/source/switch_puzzles.py · complete source
"""Two three-switch Grover searches with direct or teleported C readout."""
import itertools
import json
from pathlib import Path
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.quantum_info import Operator, Statevector
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime.circuit import MidCircuitMeasure
ROOT = Path(__file__).resolve().parent
SHOTS, SEED = 256, 20261120
PARITIES = {"odd":1,"even":0}
CHECK_GATES = [(1,0),(1,2),(0,1),(1,2),(2,1)]
def classical():
cases = list(itertools.product((0,1),repeat=3))
solutions = {}
for puzzle, parity in PARITIES.items():
hits = ["".join(map(str,(a,b,c))) for a,b,c in cases
if a!=b and b!=c and (a^b^c)==parity]
assert len(hits)==1
solutions[puzzle]=hits[0]
return solutions
def ccz(q):
# 4abc = a+b+c -(a XOR b) -(a XOR c) -(b XOR c) +(a XOR b XOR c).
# Eight nearest-neighbor CNOTs expose the parities and restore all inputs.
for i in range(3):
q.t(i)
labels=[1,2,4]
pending={3:-1,5:-1,6:-1,7:1}
for src,dst in [(0,1),(1,2)]*4:
q.cx(src,dst)
labels[dst]^=labels[src]
phase=pending.pop(labels[dst],0)
if phase==1:
q.t(dst)
elif phase==-1:
q.tdg(dst)
assert labels==[1,2,4] and not pending
def oracle(q,puzzle):
# Reversible checks replace A,B,C by A XOR B, B XOR C, A XOR B XOR C.
for src,dst in CHECK_GATES:
q.cx(src,dst)
if PARITIES[puzzle]==0:
q.x(2)
ccz(q)
if PARITIES[puzzle]==0:
q.x(2)
for src,dst in reversed(CHECK_GATES):
q.cx(src,dst)
def search(puzzle):
q=QuantumCircuit(3)
q.h(range(3))
for _ in range(2):
oracle(q,puzzle)
q.h(range(3))
q.x(range(3))
ccz(q)
q.x(range(3))
q.h(range(3))
return q
def circuit(puzzle,mode,fast=False):
q=QuantumCircuit(5,5,name=puzzle+"_"+mode)
q.compose(search(puzzle),[0,1,2],inplace=True)
q.barrier()
output=2
if mode=="teleport":
q.h(3)
q.cx(3,4)
q.cx(2,3)
q.h(2)
for wire,flag in ((2,3),(3,4)):
if fast:
q.append(MidCircuitMeasure(),[wire],[flag])
else:
q.measure(wire,flag)
with q.if_test((q.clbits[4],1)):
q.x(4)
with q.if_test((q.clbits[3],1)):
q.z(4)
output=4
q.measure([0,1,output],[2,1,0])
return q
def score(counts,key):
assert sum(counts.values())==SHOTS and all(len(w)==5 for w in counts)
return sum(n for bits,n in counts.items() if bits[-3:]==key)
def simulate():
solutions=classical()
sim=AerSimulator(method="statevector")
data={}
for puzzle,key in solutions.items():
check=QuantumCircuit(3)
oracle(check,puzzle)
diagonal=[-1 if format(i,"03b")[::-1]==key else 1 for i in range(8)]
assert np.allclose(Operator(check).data,np.diag(diagonal))
probs=Statevector.from_instruction(search(puzzle)).probabilities()
assert np.isclose(probs[int(key[::-1],2)],121/128)
for j,mode in enumerate(("direct","teleport")):
q=circuit(puzzle,mode)
qc=transpile(q,sim,optimization_level=0)
counts=sim.run(qc,shots=SHOTS,seed_simulator=SEED+2*PARITIES[puzzle]+j).result().get_counts()
if mode=="teleport":
assert len({s[:2] for s in counts})==4
data[puzzle+"_"+mode]={"counts":counts,"correct":score(counts,key)}
record={"solutions_ABC":solutions,"shots_each":SHOTS,"ideal_full_answer_probability":121/128,
"results":data,"seed":SEED}
(ROOT/"Switch-puzzles-simulator.json").write_text(json.dumps(record,indent=2))
print(solutions,{k:v["correct"] for k,v in data.items()})
if __name__=="__main__":
simulate()
Personal comments
Personal comments will be added here.