Defining Networks¶
Every DQC workflow needs a network topology: the QPUs, their qubits, and the links between them.
The recommended way to build one is the Network Builder, a local web app that lets you draw a topology in the browser — placing processors, wiring up local and remote connections, and generating common patterns (line, ring, hub, grid) — then export it as a topology file the compiler loads directly. Reach for it first:
uv sync --extra builder
uv run network-builder
Writing the JSON by hand or generating it with a Python script (covered later in this notebook) is a nice-to-have for scripted/programmatic workflows, not the primary path — most users should never need to hand-author a topology file. This notebook covers the topology file format, how to inspect a loaded network, how to build one programmatically as a fallback, and how the network determines the e-bit cost of a distributed gate.
Running this notebook. From the repository root:
uv sync uv run jupyter lab demo/networks.ipynbPaths are relative to this
demo/directory.
1. The topology file format¶
A network is a JSON file with two sections that matter:
processors— one entry per QPU, listing which qubit IDs it owns, split intocomputation(data) andcommunication(networking) qubits.qubits— one entry per physical qubit, giving itstype, its owningprocessorId, and its connections.
Let's look at the two-QPU network used by the basic demo.
The full field-by-field reference for this format lives in Network Topology Format.
import json
with open("inputs/demo_network.json") as f:
config = json.load(f)
print("top-level sections:", list(config))
print("QPUs:", list(config["processors"]))
print()
print("one computation qubit entry:")
print(json.dumps(config["qubits"]["q_0_0"], indent=2))
print()
print("one communication qubit entry:")
print(json.dumps(config["qubits"]["c_0_0"], indent=2))
top-level sections: ['processors', 'qubits', 'connections']
QPUs: ['0', '1']
one computation qubit entry:
{
"id": "q_0_0",
"kind": "computation",
"type": "computation",
"processorId": 0,
"localIndex": 0,
"label": "q(0,0)",
"coherenceTime": 100,
"coherenceTimeUnit": "us",
"localConnections": [
"c_0_0",
"q_0_1"
],
"remoteConnections": []
}
one communication qubit entry:
{
"id": "c_0_0",
"kind": "communication",
"type": "communication",
"processorId": 0,
"localIndex": 0,
"label": "c(0,0)",
"coherenceTime": 100,
"coherenceTimeUnit": "us",
"localConnections": [
"q_0_0"
],
"remoteConnections": [
"c_1_0"
]
}
The one rule worth knowing¶
Graph edges come only from each qubit's localConnections and
remoteConnections lists:
localConnections— edges inside a QPU (data qubit to data qubit, or a data qubit to one of its communication qubits).remoteConnections— entanglement links between QPUs. These always join a communication qubit on one QPU to a communication qubit on another.
Some topology files also carry a top-level connections array. It is
convenient for other tools, but NetworkGraph ignores it — if a link
appears there and not in a qubit's own connection lists, the loaded graph will
not have that edge. Keep the per-qubit lists authoritative.
Fields like label, coherenceTime, and localIndex are optional;
type and processorId are required.
coherenceTime (per qubit) and fidelity (per remote link, inside the
top-level connections array) are recorded but not yet consumed: no
current partitioner or scheduler reads them. They are reserved for
future coherence- and fidelity-aware algorithms.
2. Inspecting a loaded network¶
NetworkGraph takes a path to a topology file and exposes the QPU and qubit
structure. Note the accessor style is mixed: the num_* counts and
is_homogeneous are properties, while qpu_ids(),
computation_qubits(), comp_qubits_per_qpu() and the routing helpers are
methods — call them.
from memq_dqc.network import NetworkGraph
network = NetworkGraph("inputs/demo_network.json")
print("QPUs: ", network.num_qpus)
print("QPU IDs: ", network.qpu_ids())
print("total qubits: ", network.num_total_qubits)
print("computation qubits: ", network.num_comp_qubits)
print("communication qubits:", network.num_comm_qubits)
print("computation per QPU: ", network.comp_qubits_per_qpu())
print("communication /QPU: ", network.comm_qubits_per_qpu())
print("homogeneous: ", network.is_homogeneous)
print()
print("computation qubits: ", network.computation_qubits()[:3], "...")
print("communication qubits:", network.communication_qubits()[:3], "...")
QPUs: 2 QPU IDs: [0, 1] total qubits: 8 computation qubits: 4 communication qubits: 4 computation per QPU: [2, 2] communication /QPU: [2, 2] homogeneous: True computation qubits: [PhysicalQubit(qpu_id=0, qubit_id=0, qubit_type='computation'), PhysicalQubit(qpu_id=0, qubit_id=1, qubit_type='computation'), PhysicalQubit(qpu_id=1, qubit_id=0, qubit_type='computation')] ... communication qubits: [PhysicalQubit(qpu_id=0, qubit_id=0, qubit_type='communication'), PhysicalQubit(qpu_id=0, qubit_id=1, qubit_type='communication'), PhysicalQubit(qpu_id=1, qubit_id=0, qubit_type='communication')] ...
3. Building a topology programmatically (fallback)¶
The Network Builder GUI is the recommended way to build a topology — reach for the helper below only when you need to generate networks parametrically (e.g. sweeping over network size in an experiment). Writing this JSON by hand does not scale past a few QPUs. The helper below builds a chain of QPUs — QPU 0 links to 1, 1 links to 2, and so on.
The important design decision is pairs_per_link. A single remote gate
between adjacent QPUs consumes one entangled pair, but a state
teleportation (rswap) consumes two, and routing a gate through an
intermediate QPU requires those teleportation hops. So a link needs 2
remote pairs to be routable through, which means each QPU needs
pairs_per_link communication qubits per neighbour.
def build_chain_network(num_qpus, comp_per_qpu=2, pairs_per_link=2):
"""Build a chain topology: QPU 0 - QPU 1 - ... - QPU n-1.
Args:
num_qpus: Number of QPUs in the chain.
comp_per_qpu: Computation qubits on each QPU.
pairs_per_link: Remote entanglement pairs per adjacency. Two or more
makes a link usable for state teleportation and for routing.
Returns:
A topology dict ready to serialize as JSON.
"""
links = [(p, p + 1) for p in range(num_qpus - 1)]
comm_needed = dict.fromkeys(range(num_qpus), 0)
for a, b in links:
comm_needed[a] += pairs_per_link
comm_needed[b] += pairs_per_link
qubits, processors = {}, {}
for p in range(num_qpus):
comp = [f"q_{p}_{i}" for i in range(comp_per_qpu)]
comm = [f"c_{p}_{j}" for j in range(comm_needed[p])]
processors[str(p)] = {
"id": p,
"qubits": {"computation": comp, "communication": comm},
}
for i, qid in enumerate(comp):
neighbours = []
if i:
neighbours.append(comp[i - 1])
if i + 1 < comp_per_qpu:
neighbours.append(comp[i + 1])
qubits[qid] = {
"id": qid,
"type": "computation",
"processorId": p,
"localIndex": i,
"localConnections": neighbours,
"remoteConnections": [],
}
for j, cid in enumerate(comm):
host = comp[j % comp_per_qpu]
qubits[cid] = {
"id": cid,
"type": "communication",
"processorId": p,
"localIndex": j,
"localConnections": [host],
"remoteConnections": [],
}
qubits[host]["localConnections"].append(cid)
next_comm = dict.fromkeys(range(num_qpus), 0)
for a, b in links:
for _ in range(pairs_per_link):
ca = f"c_{a}_{next_comm[a]}"
cb = f"c_{b}_{next_comm[b]}"
next_comm[a] += 1
next_comm[b] += 1
qubits[ca]["remoteConnections"].append(cb)
qubits[cb]["remoteConnections"].append(ca)
return {"processors": processors, "qubits": qubits}
NetworkGraph reads from a file, so write the config to disk and load it back.
from pathlib import Path
Path("outputs").mkdir(exist_ok=True)
chain_path = Path("outputs/chain_3qpu.json")
chain_path.write_text(json.dumps(build_chain_network(3), indent=2))
chain = NetworkGraph(str(chain_path))
print("QPUs: ", chain.num_qpus)
print("computation per QPU:", chain.comp_qubits_per_qpu())
print("communication /QPU: ", chain.comm_qubits_per_qpu())
print("homogeneous: ", chain.is_homogeneous)
QPUs: 3 computation per QPU: [2, 2, 2] communication /QPU: [2, 4, 2] homogeneous: False
The middle QPU has twice the communication qubits of the two ends, because it terminates two links instead of one. That makes the network heterogeneous — a normal and useful situation, not a problem.
4. Routing and e-bit cost¶
This is where topology turns into cost. A two-qubit gate whose operands sit on different QPUs is either:
- direct — the two QPUs share a link, costing 1 e-bit; or
- routed — no shared link, so the moving operand teleports through intermediate QPUs first. Each teleportation hop costs 2 e-bits, plus 1 for the final remote gate.
get_qpu_route reports the path and remote_gate_ebit_cost the price.
for source, target in [(0, 1), (1, 2), (0, 2)]:
route = chain.get_qpu_route(source, target)
cost = chain.remote_gate_ebit_cost(source, target)
kind = "direct" if len(route) == 2 else "routed"
print(
f"QPU {source} -> QPU {target}: route={route} "
f"cost={cost} e-bits ({kind})"
)
print()
print("remote swap 0 <-> 1 supported:", chain.supports_remote_swap(0, 1))
print("remote swap cost:", chain.remote_swap_ebit_cost(0, 1), "e-bits")
QPU 0 -> QPU 1: route=[0, 1] cost=1 e-bits (direct) QPU 1 -> QPU 2: route=[1, 2] cost=1 e-bits (direct) QPU 0 -> QPU 2: route=[0, 1, 2] cost=3 e-bits (routed) remote swap 0 <-> 1 supported: True remote swap cost: 2 e-bits
Routing QPU 0 to QPU 2 costs 3 e-bits versus 1 for an adjacent pair. This
single fact drives most partitioning results: a partitioner that keeps
interacting qubits on directly-linked QPUs spends far less entanglement than
one that does not. comparing_partitioners.ipynb measures exactly that.
Here is what a link shortage looks like — build the same chain with only one pair per link and routing becomes impossible, because no hop can teleport.
thin_path = Path("outputs/chain_3qpu_thin.json")
thin_path.write_text(
json.dumps(build_chain_network(3, pairs_per_link=1), indent=2)
)
thin = NetworkGraph(str(thin_path))
print("communication per QPU:", thin.comm_qubits_per_qpu())
print("adjacent gate 0 -> 1:", thin.remote_gate_ebit_cost(0, 1), "e-bits")
try:
thin.get_qpu_route(0, 2)
except ValueError as err:
print("routed gate 0 -> 2 failed:", err)
communication per QPU: [1, 2, 1] adjacent gate 0 -> 1: 1 e-bits routed gate 0 -> 2 failed: No routed remote-gate path found for directional movement: 0 -> 2.
5. Compiling onto a network you built¶
A generated topology is a first-class input — hand the file path straight to
Compiler.
from memq_dqc import Compiler
compiler = Compiler("inputs/qft_n4.qasm", str(chain_path), algo="interaction")
compiler.compile()
print("compiled onto", compiler.network.num_qpus, "QPUs")
print("total e-bit cost:", compiler.cost)
print("verified:", compiler.verify(shots=20000))
compiled onto 3 QPUs total e-bit cost: 4.0
verified: True
6. The canonical configuration format¶
Alongside the topology format above, DQC ships a canonical network configuration: a broader, translation-oriented JSON representation that also captures noise models, protocols, observables, and simulation settings, with every cross-reference made explicit by string ID. It is aimed at exchanging network definitions with other tools.
CanonicalNetworkConfigBuilder assembles one and validates it.
from memq_dqc.network import (
CanonicalNetworkConfigBuilder,
CanonicalNetworkConfigError,
validate_canonical_network_config,
)
builder = CanonicalNetworkConfigBuilder()
builder.add_node(id="node_0", type="qpu", label="QPU 0")
builder.add_node(id="node_1", type="qpu", label="QPU 1")
builder.add_link(
id="link_0", type="entanglement", node_ids=["node_0", "node_1"]
)
canonical = builder.build()
validate_canonical_network_config(canonical)
print("sections:", sorted(canonical))
print("units:", canonical["units"])
print("nodes:", [n["id"] for n in canonical["nodes"]])
print("links:", [dict(link) for link in canonical["links"]])
sections: ['channels', 'constraints', 'initial_state', 'links', 'mapping_hints', 'memories', 'metadata', 'nodes', 'noise_models', 'observables', 'processors', 'protocols', 'simulation', 'units', 'version']
units: {'time': 'ns', 'frequency': 'Hz', 'distance': 'm', 'probability': 'unitless'}
nodes: ['node_0', 'node_1']
links: [{'id': 'link_0', 'type': 'entanglement', 'node_ids': ['node_0', 'node_1'], 'parameters': {}}]
Validation is strict about dangling references, which is the main thing it buys you — a link pointing at a node that does not exist is caught immediately.
broken = CanonicalNetworkConfigBuilder()
broken.add_node(id="node_0", type="qpu")
broken.add_link(
id="link_0", type="entanglement", node_ids=["node_0", "node_missing"]
)
try:
validate_canonical_network_config(broken.build())
except CanonicalNetworkConfigError as err:
print("validation rejected the config:")
print(" ", err)
validation rejected the config: Field 'node_ids' on 'link_0' references unknown ID 'node_missing'.
Write it out with builder.write(path), or get the JSON string from
builder.dumps().
What you produced¶
| File | What it is |
|---|---|
outputs/chain_3qpu.json |
A routable 3-QPU chain topology |
outputs/chain_3qpu_thin.json |
The same chain, under-provisioned on links |
Next¶
comparing_partitioners.ipynb— measure how partitioning strategy changes the e-bit cost on a given network.scheduling_and_hardware.ipynb— turn a compiled circuit into a timeline under a hardware model.