"""Builder and encoding implementation for the ToyK2 architecture."""
from collections.abc import Callable
from copy import deepcopy
from dataclasses import dataclass, field, replace
from typing import Any, Self, no_type_check
from guppylang import guppy
from guppylang.decorator import custom_guppy_decorator
from guppylang.defs import GuppyFunctionDefinition
from guppylang.library import GuppyLibrary, link_name
from guppylang.std.array import empty_array
from guppylang.std.builtins import array, comptime, exit, owned
from guppylang.std.collections import Stack, empty_stack
from guppylang.std.option import some
from hugr.ext import ExtensionRegistry, OpDef
from hugr.package import Package
from hugr.std import _std_extensions
from guppyft.code.toy_k2 import primitives as k2_primitives
from guppyft.encode import (
EncodeSpec,
EncodingArchitectureInstance,
ImplementOps,
ImplementOpsSpec,
OpReplacements,
ReplacementCompiler,
TyReplacements,
encode,
)
from guppyft.extensions import std_ops, std_types, toy_k2_ops, toy_k2_types
from guppyft.globals import map_global, with_global
from guppyft.std import LogicalBlock
N = guppy.nat_var("N")
[docs]
@dataclass
class QEDPolicy:
"""Policy to determine when QED cycles are injected.
Each logical block accumulates a cost based on `costs`. Once a
block's accumulated cost reaches `threshold` a QED cycle
is performed on that block and its counter is reset.
Attributes:
threshold: Threshold at which a QED cycle is triggered.
costs: See `OperationCosts`.
"""
[docs]
class OperationCosts:
"""Configuration for operation costs. Used e.g. for applying QED cycles."""
prep_zero_ft: float = 0.0
prep_zero_plus_ft: float = 0.0
prep_y_states_non_ft: float = 0.0
prep_t_states_non_ft: float = 0.0
x: float = 0.0
z: float = 0.0
h_all: float = 0.0
cx_intra: float = 0.0
cx_transversal: float = 0.0
swap_intra: float = 0.0
measure_z_all: float = 0.0
project_z: float = 0.0
def __setattr__(self, key: str, value: Any) -> None:
"""Set a non-negative cost for a known logical operation."""
if not hasattr(self, key):
raise KeyError(f"Unknown cost key: {key}")
if value < 0:
raise ValueError(f"Op cost cannot be negative: received {value}")
super().__setattr__(key, value)
threshold: int = 1
costs: OperationCosts = field(default_factory=OperationCosts)
@dataclass(frozen=True, kw_only=True)
class _ToyK2Options:
qed_policy: QEDPolicy
[docs]
@dataclass(frozen=True)
class ToyK2Instance(EncodingArchitectureInstance):
"""A ToyK2 architecture instance built by `ToyK2Builder.build`."""
_spec: EncodeSpec
_options: _ToyK2Options
def _encode(self, pkg: Package, *, as_bytes: bool) -> Package | bytes:
self.check_may_encode(pkg)
pkg_bytes: Package | bytes = encode(pkg, self._spec, as_bytes=as_bytes)
return pkg_bytes
[docs]
def compile(self, pkg: Package) -> Package:
"""Compile a computational package to logical with the ToyK2 instance."""
self.check_may_encode(pkg)
assert self._spec.compile is not None
return self._spec.compile(pkg)
def _implement_ops(self, pkg: Package, *, as_bytes: bool) -> Package | bytes:
assert self._spec.implement_ops is not None
pkg_bytes: Package | bytes = self._spec.implement_ops(pkg, as_bytes=as_bytes)
return pkg_bytes
[docs]
def check_may_encode(self, hugr: Package) -> None:
"""Check whether any issues can be detected that would arise when trying to
encode the given package, e.g. the package containing unsupported gates.
Note that this function returning without error is not a guarantee that a
subsequent call to `encode` will succeed."""
assert self._spec.compile is not None
if (error := self._spec.compile.check_may_compile(hugr)) is not None:
raise error
[docs]
@dataclass(frozen=True, kw_only=True)
class ToyK2Builder:
"""ToyK2 architecture builder class for creating `ToyK2Instance` objects."""
_options: _ToyK2Options = field(
default_factory=lambda: _ToyK2Options(
qed_policy=QEDPolicy(),
)
)
def _gen_implement_spec(self, n_blocks: int) -> ImplementOpsSpec:
"""Generate the `ImplementOpsSpec` providing ToyK2 implementations of
logical ops for a program using `n_blocks` logical blocks."""
qed_policy = self._options.qed_policy
lib = GuppyLibrary(members=[])
ops = OpReplacements()
def _register_op_replacement(
op_def: OpDef,
) -> Callable[[Callable[..., Any]], GuppyFunctionDefinition[Any, Any]]:
@custom_guppy_decorator
def decorator(
func: Callable[..., Any],
) -> GuppyFunctionDefinition[Any, Any]:
# Generate guppy function
name = f"link.{op_def.qualified_name()}"
guppy_func = guppy(link_name(name)(func))
# Register in library and for op replacement
lib.register_member(guppy_func)
ops.with_generated_decl(op_def, name)
return guppy_func
return decorator
@guppy.struct
class RuntimeBlock:
"""Represents a logical block at runtime for the ToyK2 architecture.
Attributes:
logical_block: The logical block contained in this runtime block.
borrowed_addr: Indicates which addresses have been borrowed.
qed_counter: The QED counter associated with this runtime block.
"""
logical_block: LogicalBlock[4] # type: ignore[valid-type, type-arg]
borrowed_addr: array[bool, 2] # type: ignore[valid-type]
qed_counter: float
@guppy
@no_type_check
def borrow_addr(self, qb_id: int) -> None:
"""Mark the address as borrowed."""
if self.borrowed_addr[qb_id]:
exit("borrow_addr: Address is already borrowed")
self.borrowed_addr[qb_id] = True
@guppy
@no_type_check
def restore_addr(self, qb_id: int) -> None:
"""Restore the borrowed address."""
if not self.borrowed_addr[qb_id]:
exit("restore_addr: Cannot restore non-borrowed address")
self.borrowed_addr[qb_id] = False
@guppy
@no_type_check
def is_borrowed(self) -> bool:
"""Check if any address in the block is borrowed."""
return self.borrowed_addr[0] or self.borrowed_addr[1]
@guppy
@no_type_check
def discard(self: Self @ owned) -> None:
"""Discard the runtime block, releasing any resources."""
self.logical_block.discard()
@guppy.struct
class STATE:
"""Tracks the global context for the ToyK2 architecture at runtime.
Attributes:
blocks: Stores the runtime blocks.
free_block_ids: Stack of block IDs that have not yet been
allocated.
available_dyn_addrs: Stack of available addresses on existing
dynamic blocks.
"""
blocks: array[RuntimeBlock, n_blocks] # type: ignore[valid-type]
free_block_ids: Stack[int, n_blocks] # type: ignore[valid-type]
available_dyn_addrs: Stack[tuple[int, int], n_blocks] # type: ignore[valid-type]
@guppy
@no_type_check
def release_block(self, blk_id: int) -> LogicalBlock[4]:
"""Consumes the RuntimeBlock and returns its logical block."""
runtime_block = self.blocks.take(blk_id)
self.free_block_ids.push(blk_id)
return runtime_block.logical_block
@guppy
@no_type_check
def allocate_block_id(self, logical_block: LogicalBlock[4] @ owned) -> int:
"""Reserve a new RuntimeBlock containing the given LogicalBlock."""
if len(self.free_block_ids) == 0:
exit("allocate_blk_id: No more logical blocks to allocate")
blk_id = self.free_block_ids.pop()
runtime_block = RuntimeBlock(logical_block, array(False, False), 0.0)
self.blocks.put(runtime_block, blk_id)
return blk_id
@guppy
@no_type_check
def release_dyn_addr(self, addr: tuple[int, int]) -> None:
"""Restore the dynamic logical qubit back to its block and
free the block if it is fully restored."""
blk_id, qb_id = addr
self.blocks[blk_id].restore_addr(qb_id)
if not self.blocks[blk_id].is_borrowed():
# It is fully restored, so release it and discard the block
logical_block = self.release_block(blk_id)
logical_block.discard()
# Remove the remaining addresses of this block from the stack
# NOTE: Ideally, `available_dyn_addrs` would be a data
# structure with fast deletion (e.g. a set).
# Generally, this stack will be small, though, so it
# shouldn't be a performance bottleneck.
aux_stack: Stack[tuple[int, int], n_blocks] = empty_stack()
for _ in range(len(self.available_dyn_addrs)):
addr = self.available_dyn_addrs.pop()
if addr[0] != blk_id:
aux_stack.push(addr)
for addr in aux_stack:
self.available_dyn_addrs.push(addr)
@guppy
@no_type_check
def allocate_dyn_addr(self: "STATE") -> tuple[int, int]:
"""Find or create a dynamic block and return an address from
it to be used as a dynamic logical qubit."""
if len(self.available_dyn_addrs) > 0:
blk_id, qb_id = self.available_dyn_addrs.pop()
else:
# Otherwise, prepare a new block
logical_block = k2_primitives.prep_zero_ft_rus()
blk_id = self.allocate_block_id(logical_block)
# The first address will be returned
qb_id = 0
# And the other address is added to the stack
self.available_dyn_addrs.push((blk_id, 1))
# Borrow the selected address from the dynamic block
self.blocks[blk_id].borrow_addr(qb_id)
return blk_id, qb_id
@guppy
@no_type_check
def qed_policy(
self,
blk_ids: array[int, N] @ owned,
op_cost: float,
) -> None:
def helper(blk: RuntimeBlock, op_cost: float) -> None:
blk.qed_counter += op_cost
if blk.qed_counter >= comptime(qed_policy.threshold):
k2_primitives.qed_cycle(blk.logical_block)
blk.qed_counter = 0.0
for i in blk_ids:
helper(self.blocks[i], op_cost)
@_register_op_replacement(toy_k2_ops.borrow_def)
@no_type_check
def _borrow(blk_id: int, qb_id: int) -> tuple[tuple[int, int], int]:
@guppy
@no_type_check
def _impl(
state: STATE @ owned, blk_id: int, qb_id: int
) -> tuple[STATE, tuple[int, int], int]:
state.blocks[blk_id].borrow_addr(qb_id)
return state, (blk_id, qb_id), blk_id
map_global(_impl, blk_id, qb_id)
return (blk_id, qb_id), blk_id
@_register_op_replacement(toy_k2_ops.borrow_more_def)
@no_type_check
def _borrow_more(blk_id: int, qb_id: int) -> tuple[tuple[int, int], int]:
@guppy
@no_type_check
def _impl(
state: STATE @ owned, blk_id: int, qb_id: int
) -> tuple[STATE, tuple[int, int]]:
state.blocks[blk_id].borrow_addr(qb_id)
return state, (blk_id, qb_id)
map_global(_impl, blk_id, qb_id)
return (blk_id, qb_id), blk_id
@_register_op_replacement(toy_k2_ops.restore_some_def)
@no_type_check
def _restore_some(blk_id: int, addr: tuple[int, int]) -> int:
@guppy
@no_type_check
def _impl(
state: STATE @ owned, blk_id: int, qb_id: int
) -> tuple[STATE, int]:
state.blocks[blk_id].restore_addr(qb_id)
return state, blk_id
return map_global(_impl, blk_id, addr[1])
@_register_op_replacement(toy_k2_ops.restore_def)
@no_type_check
def _restore(blk_id: int, addr: tuple[int, int]) -> int:
@guppy
@no_type_check
def _impl(
state: STATE @ owned, blk_id: int, qb_id: int
) -> tuple[STATE, int]:
state.blocks[blk_id].restore_addr(qb_id)
return state, blk_id
return map_global(_impl, blk_id, addr[1])
@_register_op_replacement(toy_k2_ops.alloc_dynq_def)
@no_type_check
def _alloc_dynq() -> tuple[tuple[int, int]]:
@guppy
@no_type_check
def _impl(state: STATE @ owned) -> tuple[STATE, tuple[int, int]]:
blk_id, qb_id = state.allocate_dyn_addr()
return state, (blk_id, qb_id)
return map_global(_impl)
@_register_op_replacement(toy_k2_ops.free_dynq_def)
@no_type_check
def _free_dynq(addr: tuple[int, int]) -> None:
@guppy
@no_type_check
def _impl(state: STATE @ owned, addr: tuple[int, int]) -> STATE:
state.release_dyn_addr(addr)
return state
return map_global(_impl, addr)
@_register_op_replacement(toy_k2_ops.qed_cycle_def)
@no_type_check
def _qed_cycle(blk_id: int) -> int:
@guppy
@no_type_check
def _impl(state: STATE @ owned, blk_id: int) -> tuple[STATE, int]:
def helper(blk: RuntimeBlock) -> None:
k2_primitives.qed_cycle(blk.logical_block)
blk.qed_counter = 0.0
helper(state.blocks[blk_id])
return state, blk_id
return map_global(_impl, blk_id)
@_register_op_replacement(toy_k2_ops.prep_zero_ft_def)
@no_type_check
def _prep_zero_ft() -> int:
@guppy
def _impl(state: STATE @ owned) -> tuple[STATE, int]:
logical_block = k2_primitives.prep_zero_ft_rus()
blk_id = state.allocate_block_id(logical_block)
state.qed_policy(array(blk_id), comptime(qed_policy.costs.prep_zero_ft))
return state, blk_id
return map_global(_impl)
@_register_op_replacement(toy_k2_ops.prep_zero_plus_ft_def)
@no_type_check
def _prep_zero_plus_ft() -> int:
@guppy
def _impl(state: STATE @ owned) -> tuple[STATE, int]:
logical_block = k2_primitives.prep_zero_plus_ft()
blk_id = state.allocate_block_id(logical_block)
state.qed_policy(
array(blk_id), comptime(qed_policy.costs.prep_zero_plus_ft)
)
return state, blk_id
return map_global(_impl)
@_register_op_replacement(toy_k2_ops.prep_y_states_non_ft_def)
@no_type_check
def _prep_y_states_non_ft() -> int:
@guppy
def _impl(state: STATE @ owned) -> tuple[STATE, int]:
logical_block = k2_primitives.prep_y_states_non_ft()
blk_id = state.allocate_block_id(logical_block)
state.qed_policy(
array(blk_id), comptime(qed_policy.costs.prep_y_states_non_ft)
)
return state, blk_id
return map_global(_impl)
@_register_op_replacement(toy_k2_ops.prep_t_states_non_ft_def)
@no_type_check
def _prep_t_states_non_ft() -> int:
@guppy
def _impl(state: STATE @ owned) -> tuple[STATE, int]:
logical_block = k2_primitives.prep_t_states_non_ft()
blk_id = state.allocate_block_id(logical_block)
state.qed_policy(
array(blk_id), comptime(qed_policy.costs.prep_t_states_non_ft)
)
return state, blk_id
return map_global(_impl)
@_register_op_replacement(toy_k2_ops.project_z_def)
@no_type_check
def _project_z(blk_id: int, qb_id: int) -> tuple[bool, int]:
@guppy
def _impl(
state: STATE @ owned, blk_id: int, qb_id: int
) -> tuple[STATE, bool, int]:
res = k2_primitives.project_z(state.blocks[blk_id].logical_block, qb_id)
state.qed_policy(array(blk_id), comptime(qed_policy.costs.project_z))
return state, res, blk_id
return map_global(_impl, blk_id, qb_id)
@_register_op_replacement(toy_k2_ops.measure_z_all_def)
@no_type_check
def _measure_z_all(blk_id: int) -> tuple[tuple[bool, bool]]:
@guppy
def _impl(
state: STATE @ owned, blk_id: int
) -> tuple[STATE, tuple[bool, bool]]:
blk = state.release_block(blk_id)
res = k2_primitives.measure_z_all(blk)
return state, res
return map_global(_impl, blk_id)
@_register_op_replacement(toy_k2_ops.free_def)
@no_type_check
def _free(blk_id: int) -> None:
@guppy
def _impl(state: STATE @ owned, blk_id: int) -> STATE:
state.release_block(blk_id).discard()
return state
return map_global(_impl, blk_id)
@_register_op_replacement(toy_k2_ops.x_def)
@no_type_check
def _x(blk_id: int, target: int) -> int:
@guppy
def _impl(
state: STATE @ owned, blk_id: int, target: int
) -> tuple[STATE, int]:
k2_primitives.x(state.blocks[blk_id].logical_block, target)
state.qed_policy(array(blk_id), comptime(qed_policy.costs.x))
return state, blk_id
return map_global(_impl, blk_id, target)
@_register_op_replacement(toy_k2_ops.z_def)
@no_type_check
def _z(blk_id: int, target: int) -> int:
@guppy
def _impl(
state: STATE @ owned, blk_id: int, target: int
) -> tuple[STATE, int]:
k2_primitives.z(state.blocks[blk_id].logical_block, target)
state.qed_policy(array(blk_id), comptime(qed_policy.costs.z))
return state, blk_id
return map_global(_impl, blk_id, target)
@_register_op_replacement(toy_k2_ops.h_all_def)
@no_type_check
def _h_all(blk_id: int) -> int:
@guppy
def _impl(state: STATE @ owned, blk_id: int) -> tuple[STATE, int]:
k2_primitives.h_all(state.blocks[blk_id].logical_block)
state.qed_policy(array(blk_id), comptime(qed_policy.costs.h_all))
return state, blk_id
return map_global(_impl, blk_id)
@_register_op_replacement(toy_k2_ops.cx_intra_def)
@no_type_check
def _cx_intra(blk_id: int, target: int) -> int:
@guppy
def _impl(
state: STATE @ owned, blk_id: int, target: int
) -> tuple[STATE, int]:
k2_primitives.cx_intra(state.blocks[blk_id].logical_block, target)
state.qed_policy(array(blk_id), comptime(qed_policy.costs.cx_intra))
return state, blk_id
return map_global(_impl, blk_id, target)
@_register_op_replacement(toy_k2_ops.cx_transversal_def)
@no_type_check
def _cx_transversal(ctl_blk_id: int, tgt_blk_id: int) -> tuple[int, int]:
@guppy
def _impl(
state: STATE @ owned, ctl_blk_id: int, tgt_blk_id: int
) -> tuple[STATE, int, int]:
k2_primitives.cx_transversal(
state.blocks[ctl_blk_id].logical_block,
state.blocks[tgt_blk_id].logical_block,
)
state.qed_policy(
array(ctl_blk_id, tgt_blk_id),
comptime(qed_policy.costs.cx_transversal),
)
return state, ctl_blk_id, tgt_blk_id
return map_global(_impl, ctl_blk_id, tgt_blk_id)
@_register_op_replacement(toy_k2_ops.swap_intra_def)
@no_type_check
def _swap_intra(blk_id: int) -> int:
@guppy
def _impl(state: STATE @ owned, blk_id: int) -> tuple[STATE, int]:
k2_primitives.swap_intra(state.blocks[blk_id].logical_block)
state.qed_policy(array(blk_id), comptime(qed_policy.costs.swap_intra))
return state, blk_id
return map_global(_impl, blk_id)
# NOTE: The following are re-implementations of what we have in
# `guppyft.code.toy_k2.logical` for the addressable gates.
# An alternative would be to first run a pass that replaces the
# dynamic qubit operations with the non-primitive addressable logical
# gates defined in that module.
# Another alternative is to define the addressable gates in
# `guppyft.code.toy_k2.logical` acting on the dynamic_qubit type and
# adding HUGR extension ops to inspect these types, checking if two are
# in the same block (which is implemented by comparing ints during
# implement_ops), etc. In that case, we would just replace a
# computational CX with this logical CX via the compose_op replacement,
# and *not* have the dyn ops in the extension.
# NOTE: The return type below needs to be `tuple[tuple[int,int]]`
# to stop Guppy from unpacking the `tuple[int,int]` that is used
# to represent a dynamic qubit.
@_register_op_replacement(toy_k2_ops.x_dynq_def)
@no_type_check
def _x_dynq(addr: tuple[int, int]) -> tuple[tuple[int, int]]:
blk_id, qb_id = addr
_x(blk_id, qb_id)
return (addr,)
@_register_op_replacement(toy_k2_ops.z_dynq_def)
@no_type_check
def _z_dynq(addr: tuple[int, int]) -> tuple[tuple[int, int]]:
blk_id, qb_id = addr
_z(blk_id, qb_id)
return (addr,)
@_register_op_replacement(toy_k2_ops.h_dynq_def)
@no_type_check
def _h_dynq(addr: tuple[int, int]) -> tuple[tuple[int, int]]:
blk_id, qb_id = addr
# Prepare an ancilla `|0+>` state, with the `|+>` on the index where
# we want to apply the Hadamard.
ancilla_blk_id = _prep_zero_plus_ft() # |0+>
if qb_id == 0:
# Swap the qubits so that |+> is on the correct index.
_swap_intra(ancilla_blk_id)
# Use the ancilla state to introduce a Hadamard on the chosen index.
# This approach follows Fig 8A from https://arxiv.org/abs/2403.16054
# In the case where ancilla is |0>, the CX gates are cancelled and there is
# no effect on the logical qubit at that index.
# In the case where the ancilla is |+>, a H is applied on the block,
# up to a Z correction if the measurement outcome is 0 and X if it is 1.
_cx_transversal(ancilla_blk_id, blk_id)
_h_all(ancilla_blk_id)
_cx_transversal(blk_id, ancilla_blk_id)
((m0, m1),) = _measure_z_all(ancilla_blk_id)
m = m0 if qb_id == 0 else m1
if m:
_x(blk_id, qb_id)
else:
_z(blk_id, qb_id)
return (addr,)
@_register_op_replacement(toy_k2_ops.cx_dynq_def)
@no_type_check
def _cx_dynq(
ctl_addr: tuple[int, int], tgt_addr: tuple[int, int]
) -> tuple[tuple[int, int], tuple[int, int]]:
ctl_blk, ctl_qb = ctl_addr
tgt_blk, tgt_qb = tgt_addr
# If they are the same block, we apply an intra CX
if ctl_blk == tgt_blk:
_cx_intra(tgt_blk, tgt_qb)
# Otherwise, we need to decompose it
else:
if ctl_qb == tgt_qb:
_swap_intra(ctl_blk)
_cx_transversal(ctl_blk, tgt_blk)
_cx_intra(tgt_blk, tgt_qb)
_cx_transversal(ctl_blk, tgt_blk)
_cx_intra(tgt_blk, tgt_qb)
if ctl_qb == tgt_qb:
_swap_intra(ctl_blk)
return ctl_addr, tgt_addr
@_register_op_replacement(toy_k2_ops.s_dynq_def)
@no_type_check
def _s_dynq(addr: tuple[int, int]) -> tuple[tuple[int, int]]:
# Prepare two |Y> states
y_blk_id = _prep_y_states_non_ft()
# Inject only one of them
_cx_dynq(addr, (y_blk_id, 0))
# Measure the whole block because that's more efficient
((m0, _),) = _measure_z_all(y_blk_id)
# Correct if necessary
if m0:
_z_dynq(addr)
return (addr,)
@_register_op_replacement(toy_k2_ops.sdg_dynq_def)
@no_type_check
def _sdg_dynq(addr: tuple[int, int]) -> tuple[tuple[int, int]]:
_x_dynq(addr)
_s_dynq(addr)
_x_dynq(addr)
return (addr,)
@_register_op_replacement(toy_k2_ops.t_dynq_def)
@no_type_check
def _t_dynq(addr: tuple[int, int]) -> tuple[tuple[int, int]]:
# Prepare two T|+> states
t_blk_id = _prep_t_states_non_ft()
# Inject only one of them
_cx_dynq(addr, (t_blk_id, 0))
# Measure the whole block because that's more efficient
((m0, _),) = _measure_z_all(t_blk_id)
# Correct if necessary
if m0:
_s_dynq(addr)
return (addr,)
@_register_op_replacement(toy_k2_ops.tdg_dynq_def)
@no_type_check
def _tdg_dynq(addr: tuple[int, int]) -> tuple[tuple[int, int]]:
_x_dynq(addr)
_t_dynq(addr)
_x_dynq(addr)
return (addr,)
@_register_op_replacement(toy_k2_ops.project_z_dynq_def)
@no_type_check
def _project_z_dynq(addr: tuple[int, int]) -> tuple[bool, tuple[int, int]]:
blk_id, qb_id = addr
res, _ = _project_z(blk_id, qb_id)
return res, addr
@_register_op_replacement(toy_k2_ops.measure_z_dynq_def)
@no_type_check
def _measure_z_dynq(addr: tuple[int, int]) -> bool:
m, _ = _project_z_dynq(addr)
_free_dynq(addr)
return m
@_register_op_replacement(toy_k2_ops.decode_qubit_measurement_def)
@no_type_check
def _no_op_decode1(outcome: bool) -> bool:
# In the current version of ToyK2, decoding actually happens within
# the implementation of the measure primitive, which returns bool.
# Hence, this operation is just a no-op to replace the computational
# `read()` with.
return outcome
@_register_op_replacement(toy_k2_ops.decode_block_measurement_def)
@no_type_check
def _no_op_decode2(outcome: tuple[bool, bool]) -> tuple[bool, bool]:
# Same as _no_op_decode1, but for the outcome of `measure_z_all`.
return outcome
@guppy.declare
@no_type_check
@link_name("guppyft.toy_k2.gen_state")
def state_gen_decl() -> STATE: ...
@lib.register_member
@guppy
@no_type_check
@link_name("guppyft.toy_k2.gen_state")
def state_gen() -> STATE:
return STATE(
empty_array(),
Stack(
array(some(blk_id) for blk_id in range(n_blocks)),
n_blocks,
),
empty_stack(),
)
@guppy.declare
@no_type_check
@link_name("guppyft.toy_k2.discard_state")
def state_discard_decl(state: "STATE" @ owned) -> None: ...
@lib.register_member
@guppy
@no_type_check
@link_name("guppyft.toy_k2.discard_state")
def state_discard(state: "STATE" @ owned) -> None:
for i in range(len(state.blocks)):
if not state.blocks.is_borrowed(i):
state.blocks.take(i).discard()
state.blocks.discard_all_taken()
def build_wrapper(
func: GuppyFunctionDefinition[[], None],
) -> GuppyFunctionDefinition[[], None]:
@guppy
@no_type_check
def wrapper() -> None:
state = state_gen_decl()
state = with_global(state, func)
state_discard_decl(state)
return wrapper # type: ignore[no-any-return]
ops.register_for_elimination_check(toy_k2_ops().name)
tys = TyReplacements().with_types(
[
("guppyft.toy_k2.types", "block"),
("guppyft.toy_k2.types", "borrowed_block"),
("guppyft.toy_k2.types", "dynamic_qubit"),
("guppyft.toy_k2.types", "block_measurement"),
("guppyft.toy_k2.types", "qubit_measurement"),
]
)
return ImplementOpsSpec(
ops=ops, tys=tys, build_wrapper=build_wrapper, libs=[lib.compile()]
)
def _gen_encoder_spec(self, n_blocks: int) -> EncodeSpec:
"""Generate the full `EncoderSpec` (logical encoding + op implementations)
for a program using `n_blocks` logical blocks."""
impl_spec = self._gen_implement_spec(n_blocks)
ext = ExtensionRegistry.from_extensions(
[toy_k2_ops(), toy_k2_types(), std_ops(), std_types()]
)
# `_std_extensions` should not be necessary but seems to be
# required for `borrow_array` when (de)serializing.
ext.extend(_std_extensions())
logical_compiler = ReplacementCompiler(
op_replacements={
("tket.quantum", "QAlloc"): ("guppyft.toy_k2.ops", "alloc_dynq", []),
("tket.quantum", "Measure"): (
"guppyft.toy_k2.ops",
"project_z_dynq",
[],
),
("tket.quantum", "MeasureFree"): (
"guppyft.toy_k2.ops",
"measure_z_dynq",
[],
),
("tket.quantum", "QFree"): ("guppyft.toy_k2.ops", "free_dynq", []),
("tket.measurement", "Read"): (
"guppyft.toy_k2.ops",
"decode_qubit_measurement",
[],
),
("tket.quantum", "X"): ("guppyft.toy_k2.ops", "x_dynq", []),
("tket.quantum", "Z"): ("guppyft.toy_k2.ops", "z_dynq", []),
("tket.quantum", "H"): ("guppyft.toy_k2.ops", "h_dynq", []),
("tket.quantum", "S"): ("guppyft.toy_k2.ops", "s_dynq", []),
("tket.quantum", "Sdg"): ("guppyft.toy_k2.ops", "sdg_dynq", []),
("tket.quantum", "T"): ("guppyft.toy_k2.ops", "t_dynq", []),
("tket.quantum", "Tdg"): ("guppyft.toy_k2.ops", "tdg_dynq", []),
("tket.quantum", "CX"): ("guppyft.toy_k2.ops", "cx_dynq", []),
},
compound_op_replacements={},
ty_replacements={
("prelude", "qubit"): ("guppyft.toy_k2.types", "dynamic_qubit"),
("tket.measurement", "Measurement"): (
"guppyft.toy_k2.types",
"qubit_measurement",
),
},
extensions=ext,
)
return EncodeSpec(
compile=logical_compiler, implement_ops=ImplementOps.for_spec(impl_spec)
)
[docs]
def with_qed_policy(self, qed_policy: QEDPolicy) -> Self:
"""Set the QED policy."""
return replace(self, _options=replace(self._options, qed_policy=qed_policy))
[docs]
def build(self, n_blocks: int) -> ToyK2Instance:
"""Build a `ToyK2Instance` configured for `n_blocks` logical blocks."""
encoder_spec = self._gen_encoder_spec(n_blocks)
return ToyK2Instance(_spec=encoder_spec, _options=deepcopy(self._options))