Using Nexus Console to encode programs with the Iceberg architecture¶
Download this notebook - iceberg_encoding.ipynb
Note
This feature will become available to Nexus Console users in the 26.2 release of the Quantinuum Nexus developer platform.
The release notes for the platform releases can be found here.
We have seen in the Steane code example that Guppy FT provides automatic encoding for Guppy programs. In this demonstration, we will show automatic encoding for the \([[k+2, k, 2]]\) Iceberg architecture. The Iceberg code is distance \(2\) so it can detect (but not correct) an arbitrary single qubit error. Once an error is detected, it is possible to exit the program early, skipping any remaining gates.
Unlike Steane, encoding a program with the Iceberg architecture requires the use of Nexus Console - Quantinuum’s cloud platform. As Nexus Console is required, we will need the qnexus client package. The workflow is comprised of three steps.
Write a computational program in Guppy. A computational program can be written independently of QEC or fault-tolerance. We then compile this program.
Secondly, define some Iceberg encoding parameters via the
IcebergBuilderclass. These parameters will include the number of logical qubits in a block, the number of blocks and a policy for inserting quantum error detection (QED) cycles.Finally, upload the annotated program to Nexus Console. Compilation to the physical gates will happen server-side. The program will then be executed on a quantum device or simulator.
Note
As discussed in our Getting Started page, the encoded program will be larger and more expensive to run, but we cannot guarantee that the error rate will be reduced.
Setup¶
The qnexus Python package can be installed as follows
pip install qnexus
In addition, we will also need a Nexus Console account. If you don’t already have access to Nexus Console, it is possible to apply for access at https://nexus.quantinuum.com/signup.
Once we have the qnexus package installed, we can log in to Nexus Console and create a project to keep track of all of the jobs we run.
import qnexus as qnx
qnx.login()
project = qnx.projects.get_or_create(name="iceberg_project")
qnx.context.set_active_project(project)
Already logged in. Tokens are valid.
Write a computational program¶
We can now define our computational program using Guppy. For demonstration purposes, we will show a \(k\) qubit Quantum Fourier Transform (\(QFT\)) followed by an \(X\)-basis measurement of all of the logical qubits. The expected result in the absence of errors would be the all-zero bitstring. This is true since \(QFT |0\rangle^{\otimes k} = |+\rangle^{\otimes k}\) and an \(X\)-basis measurement on \(|+\rangle\) deterministically returns outcome \(0\). The \(k\) qubit \(QFT\) can be implemented with \(k\) Hadamard gates and \(\frac{k(k-1)}{2}\) controlled rotations. Given the quadratic number of two qubit gates, the program is deep enough for errors to occur if we run it with a noise model. This will serve to demonstrate a QED policy (see next section). It’s also very easy to see which shots give the expected result of an all-zero bitstring and which shots are discarded after an error is detected.
from guppylang import guppy
from guppylang.std.builtins import array, nat
from guppylang.std.quantum import h, crz, qubit, rz
from guppylang.std.angles import pi, angle
from guppylang.std.mem import mem_swap
@guppy
def cphase(control: qubit, target: qubit, theta: angle) -> None:
rz(control, theta / 2)
crz(control, target, theta)
@guppy
def qft[k: nat](qs: array[qubit, k]) -> None:
for i in range(k):
h(qs[i])
for j in range(i + 1, k):
cphase(qs[j], qs[i], pi / 2 ** (j - i))
# Reverse qubit order with swaps
for m in range(k // 2):
mem_swap(qs[m], qs[k - m - 1])
Now that we have our \(QFT\) implementation, lets define a helper to measure an array of \(k\) qubits in the \(X\)-basis.
from guppylang.std.builtins import owned
from guppylang.std.quantum import Measurement, measure_array
@guppy
def measure_x_array[k: nat](qs: array[qubit, k] @ owned) -> array[Measurement, k]:
for i in range(k):
h(qs[i])
return measure_array(qs)
We also need a main function which defines the entrypoint to our quantum program. Inside this main function we first allocate some qubits, then apply the \(QFT\) and follow it with the \(X\)-basis measurements.
from guppylang.std.platform import output
from guppylang.std.quantum import collect_measurements
from guppylang.defs import GuppyFunctionDefinition
def build_qft_main(num_logical_qubits: int) -> GuppyFunctionDefinition:
@guppy
def main() -> None:
qs = array(qubit() for _ in range(num_logical_qubits))
qft(qs)
measurements = measure_x_array(qs)
output("m_x", collect_measurements(measurements))
return main
We can now create a \(k=6\) qubit instance of our \(QFT\) program and compile it to the HUGR intermediate representation.
n_qft_qubits = 6
qft_main = build_qft_main(n_qft_qubits)
pkg = qft_main.compile()
Define Iceberg encoding parameters¶
Now that we have our computational program, we can use the IcebergBuilder to configure the parameters of the Iceberg architecture.
The IcebergBuilder should be configured with an IcebergQEDPolicy—a policy describing when quantum error detection (QED) cycles should be applied. Guppy FT allows users to assign different costs to logical operations. These costs are accumulated as the program runs, and a QED cycle is inserted whenever the user defined threshold is reached.
For our policy, we will choose to assign a the same cost of 1.0 to Rx, Rz and ZZPhase gates. In the Iceberg code, each of these three logical gates are implemented with a single physical two-qubit gate, which is why we assign the same cost to all of them.
A QED cycle will be performed after a threshold value of 50 is met.
from guppyft.code.iceberg.encode import IcebergBuilder, IcebergQEDPolicy
qed_policy = IcebergQEDPolicy()
qed_policy.costs.rx = 1.0
qed_policy.costs.rz = 1.0
qed_policy.costs.zz_phase_intrablock = 1.0
# Insert a QED cycle after 50 of these gates are applied (combining Rx, Rz and ZZPhase gates).
qed_policy.threshold = 50
Once we have defined a policy, we can use the IcebergBuilder to annotate our compiled Guppy program with some metadata which stores all of the encoding parameters that we have specified. Computational to physical compilation can then be done server-side.
For this example we are going to encode our 6 qubit \(QFT\) program in a single \([[8, 6, 2]]\) Iceberg block.
# Specify the block size (number of logical qubits), number of blocks and QED policy
n_blocks = 1
iceberg_instance = (
IcebergBuilder.new(block_size=n_qft_qubits, n_blocks=n_blocks)
.with_qed_policy(qed_policy)
.build()
)
# Annotate block_size, n_blocks, qed_policy and other parameters onto the compiled program.
iceberg_instance.annotate(pkg)
Upload to Nexus Console for execution¶
We can now upload our \(QFT\) program to the cloud using the qnexus client for compilation and execution. This program is now annotated with all of the Iceberg parameters that we specified in the previous section.
import uuid
name = f"iceberg-nexus-{uuid.uuid4()}"
iceberg_hugr_ref = qnx.hugr.upload(hugr_package=pkg, name=name)
In this example, we submit for execution on the Helios-1E remote emulator. This emulator uses a physics informed noise model to mimic the noise present in the Quantinuum Helios-1 device.
config = qnx.HeliosConfig(
system_name="Helios-1E", emulator_config=qnx.models.HeliosEmulatorConfig()
)
Finally, we submit an execute job to run on the Helios-1E emulator by passing a reference to our Iceberg-annotated program to the qnx.start_execute_job method. Note how we have to specify the max_cost in HQCs and also specify a total number of physical qubits to be used in the simulation.
In general, it is not straightforward to predict the number of qubits needed by the physical program. We need at least 8 qubits for the \([[8, 6, 2]]\) block, but the Iceberg architecture requires additional ancilla qubits for state preparation and error detection. We choose to set an upper bound of 16 physical qubits to allow plenty of ancilla qubits during runtime. We will execute this encoded \(QFT\) program on the noisy emulator for 500 shots.
Note
Before running encoded programs it’s highly recommended to test the program with the coinflip or classical replay simulators. This can help determine the number of physical qubits used at runtime and potentially detect issues which could otherwise manifest as runtime errors.
See the Nexus console docs for information on how to use the coinflip and classical replay simulations.
ref_execute_job = qnx.start_execute_job(
programs=[iceberg_hugr_ref],
n_shots=[500],
backend_config=config,
max_cost=1000,
name=f"Iceberg QFT-(n_logical_qubits={n_qft_qubits}, n_blocks={n_blocks})",
n_qubits=16,
)
Analyze the results¶
Now that we have finished running our Iceberg experiment, we can download our results from Nexus Console and analyze them.
qnx.jobs.wait_for(ref_execute_job)
results = qnx.jobs.results(ref_execute_job)
result_ref = results[0]
shot_results = result_ref.download_result()
Firstly, we will plot the proportion of completed shots as a fraction of the total number of shots. This will allow us to clearly see how many shots exit when an error is detected. Some of the completed shots do not result in the expected all-zero bitstring; these shots correspond to undetected errors.
def process_results(data, plot: bool) -> tuple[int, int, int]:
collated = data.collated_counts()
total = sum(collated.values())
if total:
early = collated.get((), 0)
completed = total - early
counts = data.register_counts().get("m_x", {})
all_zero = sum(n for state, n in counts.items() if state and set(state) == {"0"})
errors = completed - all_zero
ax = make_outcomes_axes()
early_bar = ax.bar("Early exit", early / total, **early_exit_style)
all_zero_bar = ax.bar("Completed", all_zero / total, **all_zero_style)
error_bar = None
if completed:
error_bar = ax.bar(
"Completed", errors / total, bottom=all_zero / total, **error_style
)
format_outcomes(
ax,
early_bar,
all_zero_bar,
error_bar,
early=early,
all_zero=all_zero,
errors=errors,
total=total,
)
if plot:
plt.show()
else:
plt.close()
return all_zero, completed, total
_ = process_results(shot_results, plot=True)
Finally, we will plot the histogram of completed shots which have the expected all-zero measurement outcome bitstring. Successful shots are shown in green. Shots for which an undetected logical error occurs are shown in orange.
counts = shot_results.register_counts().get("m_x")
top = counts.most_common(5) if counts else []
if top:
states = [str(state) for state, _ in top]
shots = [count for _, count in top]
ax = make_completed_shots_axes(len(top))
bars = ax.bar(states, shots)
format_completed_shots(ax, bars, shots)
plt.show()
Adjusting the discard rate trade-off¶
The primary mechanisms to detect errors in the Iceberg architecture is the QED cycle.
We can reduce the number of undetected errors that slip through our checks by increasing the frequency of QED cycle insertion.
This is as simple as decreasing the threshold of our QED policy. Previously, we had set it to 50; let’s see what happens when we reduce the threshold down to 5.
This reduces the gap between QED cycles by a factor of ten.
# Change the threshold from 50 to 5
qed_policy.threshold = 5
# Configure a new Iceberg architecture instance with this QED policy.
new_iceberg_instance = (
IcebergBuilder.new(block_size=n_qft_qubits, n_blocks=n_blocks)
.with_qed_policy(qed_policy)
.build()
)
# Annotate block_size, n_blocks, qed_policy and other parameters onto the compiled program.
new_pkg = qft_main.compile()
new_iceberg_instance.annotate(new_pkg)
# Upload and submit to Nexus Console
name = f"iceberg-nexus-{uuid.uuid4()}"
iceberg_hugr_ref = qnx.hugr.upload(hugr_package=new_pkg, name=name)
ref_execute_job = qnx.start_execute_job(
programs=[iceberg_hugr_ref],
n_shots=[500],
backend_config=config,
max_cost=1000,
name=f"Iceberg QFT-(n_logical_qubits={n_qft_qubits}, n_blocks={n_blocks})",
n_qubits=16,
)
# Wait for results
qnx.jobs.wait_for(ref_execute_job)
new_shot_results = qnx.jobs.results(ref_execute_job)[0].download_result()
_ = process_results(new_shot_results, plot=True)
Using more QED cycles implies a larger proportion of the completed shots return the correct outcome. In exchange, the price to pay is a larger number of shots being discarded (early exit) due to an error being detected. Note that QED cycles introduce more gates into the circuit, which themselves can be faulty. Consequently, as we decrease the QED policy’s threshold, the proportion of discarded shots will generally increase faster than the fidelity of the completed shots.
print_summary()
QED threshold = 50
Completed/Total: 234/500 (46.80%)
Correct/Completed: 207/234 (88.46%)
QED threshold = 5
Completed/Total: 137/500 (27.40%)
Correct/Completed: 136/137 (99.27%)
Users are encouraged to explore this trade-off using emulation. When emulating the program, it is advisable to convert all of the angle rotations in the program to multiples of \(\pi/2\), so that it can be emulated using a stabilizer backend, which is scalable and fast. Then, the QED policy can be tuned to a target discard rate and, once a good QED policy is found, the same policy should provide roughly the same behaviour on the program with the original angles.