The logical programming stack
Follow one Bell pair, written as an ordinary CUDA-Q kernel, from the kernel to
a physical schedule on Steane-encoded qubits, and then run it. First, compile,
place, and estimate the kernel with explicit cudaq.logical calls. Then
estimate it with a single cudaq.estimate call through a CUDA-Q target built
from the same device. Finally, run the kernel and its physical build with
cudaq.run.
Install CUDA-Q Logical following the quick start. See Core concepts for the definitions used throughout this guide.
The excerpts below come from the runnable Steane Bell-pair example. From the repository root, run:
python3 preview/logical/examples/steane_bell_e2e_workflow.py
The compilation stages are P0, P1, P2, and P3:
P0: logical program → P1: placement → P2: QEC realization → P3: physical schedule
A logical program describes the computation on logical qubits, independent of the QEC code and device. Each stage adds the information needed for more detailed resource estimates.
1. Write the kernel
Write the Bell pair as a CUDA-Q kernel that returns its two measurements. The kernel specifies the computation independently of its QEC code and device:
import cudaq
import cudaq.logical as cql
@cudaq.kernel
def bell_pair() -> tuple[bool, bool]:
qubits = cudaq.qvector(2)
h(qubits[0])
x.ctrl(qubits[0], qubits[1])
return mz(qubits[0]), mz(qubits[1])
2. Choose the code and its implementations
Define the Steane [[7,1,3]]
CSS code explicitly. It
protects one logical qubit with seven data qubits; CSSBlock also reserves
three X-check and three Z-check ancillas. The hx and hz rows list the
data-qubit indices for each X and Z stabilizer check, while lx and lz define
the logical X and Z operators.
@cql.code validates the code’s algebraic structure.
cql.materialize creates its compiler
representation, which can be inspected independently of the Bell kernel:
@cql.code
class Steane:
block = cql.codes.CSSBlock(data=7, sx=3, sz=3)
d = 3
hx = ((0, 1, 2, 3), (0, 1, 4, 5), (0, 2, 4, 6))
hz = hx
lx = (tuple(range(7)),)
lz = lx
code = cql.materialize(Steane)
assert (Steane.n, Steane.k, Steane.d.value) == (7, 1, 3)
assert Steane.block.size == 13
The same code is also available as the built-in cql.codes.Steane. To use it,
replace the class definition with Steane = cql.codes.Steane.
Supply gadgets for the
kernel’s Hadamard and controlled-X operations. Each implements= clause
names the ideal logical
action; the body
describes its implementation on encoded patches. For Steane, these operations
can be applied across the data qubits:
@cql.gadget(implements=cql.standard.h)
def steane_h(block: cql.patch[Steane]) -> cql.patch[Steane]:
return cql.h(block.data)
@cql.gadget(implements=cql.standard.cx)
def steane_cx(
control: cql.patch[Steane],
target: cql.patch[Steane],
) -> tuple[cql.patch[Steane], cql.patch[Steane]]:
return cql.cx(control.data, target.data)
Each logical qubit also needs a preparation. Resetting the seven data qubits
gives |0000000⟩, which does not satisfy the X stabilizers, so supply an
encoder that prepares logical |0⟩.
cql.gadgets.verify_gadget checks
it. The contract binds the prepared block’s syndrome to zero, which requires
every stabilizer to be +1, and the prepare_zero claim requires logical Z to
be +1:
@cql.gadget(implements=cql.standard.prepare_zero)
def steane_prepare_zero(block: cql.patch[Steane]) -> cql.patch[Steane]:
block = cql.reset(block.data)
for index in (3, 5, 6):
block = cql.h(block.data[index])
for control, targets in ((3, (0, 1, 2)), (5, (0, 1, 4)), (6, (0, 2, 4))):
for target in targets:
block = cql.cx(block.data[control], block.data[target])
return block
# Check that the encoder prepares logical |0>. The contract binds the block's
# syndrome to zero, which requires every stabilizer to be +1, and the
# `prepare_zero` claim requires logical Z to be +1.
encoder_contract = cql.gadgets.GadgetContract(
steane_prepare_zero,
boundary={steane_prepare_zero.outputs.only().syndrome: False},
)
assert cql.gadgets.verify_gadget(encoder_contract).verified
Combine these gadgets with the library’s logical-Z measurement in a QEC architecture. Together they cover every operation in the kernel:
steane_architecture = cql.devices.QECArchitecture(
"SteaneBellArchitecture",
Steane.default_encoding,
link_roots=(
steane_prepare_zero,
steane_h,
steane_cx,
cql.gadgets.measure_z(Steane),
),
)
See Defining a code and Gadgets and verification for custom definitions.
3. Describe the device
A device connects the logical machine, QEC realization, and physical resources. First, give its logical machine a compute region with two slots, then bind that region to the Steane architecture:
builder = cql.devices.DeviceBuilder("SteaneBellDevice")
compute = builder.logical.add_compute(capacity=2)
encoded_region = builder.qec.bind(compute, architecture=steane_architecture)
Each logical qubit needs one Steane block. Here,
CSSBlock(data=7, sx=3, sz=3) reserves seven data qubits and six check ancillas
per block. The device therefore reserves 2 * (7 + 3 + 3) = 26 physical qubits:
14 data qubits and 12 ancillas. The ancillas are part of this example’s block
layout. Declare the operations, measurements, and timing available on the
physical machine:
carriers = builder.physical.add_qubits(
2 * Steane.block.size,
native_actions=cql.architecture.physical_actions.clifford_set(),
native_instruments=(
cql.architecture.physical_instruments.MZ,
cql.architecture.physical_instruments.MPP,
),
)
builder.physical.bind(encoded_region, to=carriers)
builder.physical.set_operating_point(timing={"cycle_ns": 1.0})
device = builder.build()
This is a teaching device with an illustrative one-nanosecond cycle and native Clifford operations and Pauli-product measurements. Its resource and timing results describe these assumptions. See Devices and placement for other device configurations.
A compilation target packages the device so
that CUDA-Q can compile and estimate kernels for it. Expose device through
Target.from_device, with the estimate options that the target and the
explicit estimates below share:
estimate_options = {
"p_phys": 1.0e-3,
"failure_budget": 0.1,
"cycle_time": 1.0e-9,
}
target = cql.targets.Target.from_device(
"steane_bell",
device,
estimate_options=estimate_options,
)
4. Compile the kernel for CUDA-Q Logical
cql.compiler.import_cudaq compiles the kernel to a logical program, a P0
build. The P0 program returns
one result per measurement, in the kernel’s return order:
logical = cql.compiler.import_cudaq(bell_pair)
Pass the build to cql.estimate to count its logical resources:
logical_resources = cql.estimate(logical, tier=cql.estimate.Tier.LOGICAL)
print(f"Peak logical qubits: {logical_resources.logical_qubits_peak}")
print(f"Hadamard actions: {logical_resources.actions['qlx_standard_h']}")
print(f"Controlled-X actions: {logical_resources.actions['qlx_standard_cx']}")
Peak logical qubits: 2
Hadamard actions: 1
Controlled-X actions: 1
These counts describe the workload. Encoded blocks, physical qubits, and timing depend on the realization chosen above. See Capabilities for the results a kernel can return.
5. Place and realize the program
Use cql.compiler.place to assign the P0
program’s logical qubits to the device’s logical machine:
placed = cql.compiler.place(logical, device=device)
print([(binding.space, binding.slot) for binding in placed.placement.bindings])
[('compute', 0), ('compute', 1)]
This P1 build records placement. It has not yet selected the QEC implementations. Continue compilation with the QEC pipeline to produce P2, then estimate the encoded resources directly:
encoded = cql.compile(
placed,
pipeline=cql.compiler.pipelines.qec(),
device=device,
)
static_resources = cql.estimate(encoded, tier=cql.estimate.Tier.STATIC)
print(f"Peak encoded patches: {static_resources.patches_peak}")
print(f"Hadamard gadget calls: {static_resources.gadget_calls['steane_h']}")
print(
f"Controlled-X gadget calls: {static_resources.gadget_calls['steane_cx']}")
Peak encoded patches: 2
Hadamard gadget calls: 1
Controlled-X gadget calls: 1
The Bell pair now uses two Steane patches. Its selected implementations also include two encoder preparations and two logical-Z measurements.
6. Schedule and estimate the physical resources
Continue with the physical pipeline and schedule the resulting P3 events:
physical = cql.compile(
encoded,
pipeline=cql.compiler.pipelines.physical(),
device=device,
)
schedule = cql.compiler.schedule(physical)
cql.estimate can now report physical resources and timing under the estimate
options defined with the target:
schedule_resources = cql.estimate(
schedule,
tier=cql.estimate.Tier.SCHEDULE,
**estimate_options,
)
print(f"Physical qubits: {schedule_resources.physical_qubits}")
print(f"Scheduled events: {schedule_resources.event_count}")
print(f"Makespan: {schedule_resources.makespan_ns:.1f} ns")
Physical qubits: 26
Scheduled events: 25
Makespan: 10.0 ns
The estimation tier determines which resources to report and which compilation stage is required:
Tier |
Available from |
What it reports |
|---|---|---|
LOGICAL |
P0 |
logical qubits, actions, and instruments |
STATIC |
P2 |
encoded patches, gadget calls, and authored actions |
ANALYTICAL |
P2 |
modeled physical cost, error, acceptance, and timing |
SCHEDULE |
P3 |
physical resources, timed events, and utilization |
See Resource estimation for the analytical tier and the complete result fields. The outputs above are estimates for preparing and measuring the Bell pair under this device model.
7. Estimate the kernel through the target
The explicit calls above are useful when developing a device or inspecting
compilation stages. An application can instead select the target and call
cudaq.estimate on the kernel. The target then handles logical compilation,
placement, QEC realization, and physical scheduling. Recover the logical and
static counts with typed views; the schedule results are available in the
SCHEDULE annotation:
cudaq.set_target(target)
estimate = cudaq.estimate(bell_pair)
kernel_logical = cql.estimate.LogicalEstimate.from_annotations(
estimate.annotations)
kernel_static = cql.estimate.FabricCounts.from_annotations(estimate.annotations)
kernel_schedule = estimate.annotations["SCHEDULE"]
assert kernel_logical.logical_qubits_peak == logical_resources.logical_qubits_peak
assert kernel_logical.actions == logical_resources.actions
assert kernel_static.patches_peak == static_resources.patches_peak
assert kernel_static.gadget_calls == static_resources.gadget_calls
assert kernel_schedule["physical_qubits"] == schedule_resources.physical_qubits
assert kernel_schedule["event_count"] == schedule_resources.event_count
assert kernel_schedule["makespan_ns"] == schedule_resources.makespan_ns
Both entry points estimate the same Bell pair on the same device. An application can reuse the target for compatible kernels without repeating the individual compiler calls.
8. Run the kernel and its physical build
cudaq.run executes the kernel directly. It also executes the P3 build, which
it first translates to Quake with Build.to_quake(). Both circuits are
Clifford, so the stim target runs them:
import collections
cudaq.set_target("stim")
for name, runnable in {
"CUDA-Q kernel": bell_pair,
"P3 Build": physical
}.items():
results = cudaq.run(runnable, shots_count=100)
counts = collections.Counter(tuple(shot) for shot in results)
assert set(counts) == {(False, False), (True, True)}
print(f"{name}:\toutcomes\t{dict(counts)}")
CUDA-Q kernel: outcomes {(True, True): 52, (False, False): 48}
P3 Build: outcomes {(False, False): 46, (True, True): 54}
Both runs give only the two Bell outcomes, and the counts vary from run to run.
The kernel returns each shot as the tuple it declares. The P3 build returns
its two results as a list[bool], in the kernel’s return order, so the cell
converts each shot with tuple(shot) before counting.
9. Optional: inspect the executed Quake
The Quake that the P3 build runs is an ordinary CUDA-Q module. This cell counts its operations next to the kernel’s:
kernel_resources = cudaq.estimate_resources(bell_pair)
print(f"CUDA-Q kernel: {kernel_resources.num_qubits} qubits, "
f"{kernel_resources.count('h')} h, "
f"{kernel_resources.count_controls('x', 1)} cx, "
f"{kernel_resources.count('mz')} mz")
quake = physical.to_quake()
entry = next(op for op in quake.body.operations
if "cudaq-entrypoint" in op.operation.attributes)
ops = collections.Counter((op.operation.name, len(op.operation.operands))
for op in entry.regions[0].blocks[0].operations)
print(f"P3 Build: {ops['quake.null_wire', 0]} qubits, "
f"{ops['quake.h', 1]} h, {ops['quake.x', 2]} cx, "
f"{ops['quake.reset', 1]} reset, {ops['quake.mz', 1]} mz")
CUDA-Q kernel: 2 qubits, 1 h, 1 cx, 2 mz
P3 Build: 28 qubits, 13 h, 39 cx, 14 reset, 2 mz
The Quake allocates all 13 carriers of each block, including the six check ancillas this program never uses, plus one ancilla for each logical-Z measurement. The schedule counts that measurement as one native Pauli-product event, so it reports only the 26 carriers. These counts follow from how this release translates P3 to Quake. Use the schedule estimate for physical resources.
Where to go next
Execute an encoded program with
cudaq.runin the Steane Bernstein–Vazirani example. It supplies an encoding circuit and returns measurement bits per shot. The T-state distillation example runs on distance-1BareQubitpatches and adds non-Clifford gates, measurement feedback, and noise.Read Core concepts for definitions of programs, machines, codes, gadgets, devices, and targets.
Work through the guides for defining a code, placing a program, and estimating resources.
Browse the examples. The Carbon target builds a custom code and integrates paired operations with CUDA-Q kernels.