diff --git a/Cargo.toml b/Cargo.toml index f7a52f64..4e19f896 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,7 +73,7 @@ members = ["pyrs", "compile-matcher", "taso-optimiser"] [workspace.dependencies] -quantinuum-hugr = { git = "https://github.com/CQCL-DEV/hugr", rev = "19ed0fc" } +quantinuum-hugr = { git = "https://github.com/CQCL-DEV/hugr", rev = "af664e3" } portgraph = { version = "0.9", features = ["serde"] } pyo3 = { version = "0.19" } itertools = { version = "0.11.0" } diff --git a/pyrs/src/circuit.rs b/pyrs/src/circuit.rs index 850278ff..dbb6db97 100644 --- a/pyrs/src/circuit.rs +++ b/pyrs/src/circuit.rs @@ -6,6 +6,7 @@ use pyo3::prelude::*; use hugr::{Hugr, HugrView}; use tket2::extension::REGISTRY; use tket2::json::TKETDecode; +use tket2::passes::CircuitChunks; use tket_json_rs::circuit_json::SerialCircuit; /// Apply a fallible function expecting a hugr on a pytket circuit. @@ -52,3 +53,38 @@ pub fn to_hugr_dot(c: Py) -> PyResult { pub fn to_hugr(c: Py) -> PyResult { with_hugr(c, |hugr| hugr) } + +#[pyfunction] +pub fn chunks(c: Py, max_chunk_size: usize) -> PyResult { + with_hugr(c, |hugr| CircuitChunks::split(&hugr, max_chunk_size)) +} + +/// circuit module +pub fn add_circuit_module(py: Python, parent: &PyModule) -> PyResult<()> { + let m = PyModule::new(py, "circuit")?; + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + + m.add_function(wrap_pyfunction!(validate_hugr, m)?)?; + m.add_function(wrap_pyfunction!(to_hugr_dot, m)?)?; + m.add_function(wrap_pyfunction!(to_hugr, m)?)?; + m.add_function(wrap_pyfunction!(chunks, m)?)?; + + m.add("HugrError", py.get_type::())?; + m.add("BuildError", py.get_type::())?; + m.add( + "ValidationError", + py.get_type::(), + )?; + m.add( + "HUGRSerializationError", + py.get_type::(), + )?; + m.add( + "OpConvertError", + py.get_type::(), + )?; + + parent.add_submodule(m) +} diff --git a/pyrs/src/lib.rs b/pyrs/src/lib.rs index 146c36f7..062b4ba4 100644 --- a/pyrs/src/lib.rs +++ b/pyrs/src/lib.rs @@ -1,6 +1,6 @@ //! Python bindings for TKET2. #![warn(missing_docs)] -use circuit::try_with_hugr; +use circuit::{add_circuit_module, try_with_hugr}; use pyo3::prelude::*; use tket2::{json::TKETDecode, passes::apply_greedy_commutation}; use tket_json_rs::circuit_json::SerialCircuit; @@ -25,30 +25,6 @@ fn pyrs(py: Python, m: &PyModule) -> PyResult<()> { Ok(()) } -/// circuit module -fn add_circuit_module(py: Python, parent: &PyModule) -> PyResult<()> { - let m = PyModule::new(py, "circuit")?; - m.add_class::()?; - m.add_class::()?; - - m.add("HugrError", py.get_type::())?; - m.add("BuildError", py.get_type::())?; - m.add( - "ValidationError", - py.get_type::(), - )?; - m.add( - "HUGRSerializationError", - py.get_type::(), - )?; - m.add( - "OpConvertError", - py.get_type::(), - )?; - - parent.add_submodule(m) -} - /// portmatching module fn add_pattern_module(py: Python, parent: &PyModule) -> PyResult<()> { let m = PyModule::new(py, "pattern")?; diff --git a/pyrs/test/test_bindings.py b/pyrs/test/test_bindings.py index 211b0e51..a43263e5 100644 --- a/pyrs/test/test_bindings.py +++ b/pyrs/test/test_bindings.py @@ -1,5 +1,5 @@ from dataclasses import dataclass -from pyrs.pyrs import passes +from pyrs.pyrs import passes, circuit from pytket.circuit import Circuit @@ -19,6 +19,17 @@ def test_depth_optimise(): assert c.depth() == 2 +def test_chunks(): + c = Circuit(4).CX(0, 2).CX(1, 3).CX(1, 2).CX(0, 3).CX(1, 3) + + assert c.depth() == 3 + + chunks = circuit.chunks(c, 2) + circuits = chunks.circuits() + chunks.update_circuit(0, circuits[0]) + c2 = chunks.reassemble() + + assert c2.depth() == 3 # from dataclasses import dataclass # from typing import Callable, Iterable diff --git a/src/lib.rs b/src/lib.rs index 3e89fda1..af4ec438 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,9 +14,11 @@ pub(crate) mod ops; pub mod optimiser; pub mod passes; pub mod rewrite; -pub use ops::{symbolic_constant_op, Pauli, T2Op}; #[cfg(feature = "portmatching")] pub mod portmatching; mod utils; + +pub use circuit::Circuit; +pub use ops::{symbolic_constant_op, Pauli, T2Op}; diff --git a/src/passes.rs b/src/passes.rs index 68ac2a44..efacfec5 100644 --- a/src/passes.rs +++ b/src/passes.rs @@ -1,6 +1,9 @@ -//! Optimisation passes for circuits. +//! Optimisation passes and related utilities for circuits. mod commutation; pub use commutation::apply_greedy_commutation; #[cfg(feature = "pyo3")] pub use commutation::PyPullForwardError; + +pub mod chunks; +pub use chunks::CircuitChunks; diff --git a/src/passes/chunks.rs b/src/passes/chunks.rs new file mode 100644 index 00000000..ff10d3b7 --- /dev/null +++ b/src/passes/chunks.rs @@ -0,0 +1,339 @@ +//! Utility + +use std::collections::HashMap; + +use hugr::builder::{Dataflow, DataflowHugr, FunctionBuilder}; +use hugr::extension::ExtensionSet; +use hugr::hugr::hugrmut::HugrMut; +use hugr::hugr::views::sibling_subgraph::ConvexChecker; +use hugr::hugr::views::{HierarchyView, SiblingGraph, SiblingSubgraph}; +use hugr::hugr::{HugrError, NodeMetadata}; +use hugr::ops::handle::DataflowParentID; +use hugr::types::{FunctionType, Signature}; +use hugr::{Hugr, HugrView, Node, Port, Wire}; +use itertools::Itertools; + +use crate::extension::REGISTRY; +use crate::Circuit; + +#[cfg(feature = "pyo3")] +use crate::json::TKETDecode; +#[cfg(feature = "pyo3")] +use pyo3::{exceptions::PyAttributeError, pyclass, pymethods, Py, PyAny, PyResult}; +#[cfg(feature = "pyo3")] +use tket_json_rs::circuit_json::SerialCircuit; + +/// An identifier for the connection between chunks. +/// +/// This is based on the wires of the original circuit. +/// +/// When reassembling the circuit, the input/output wires of each chunk are +/// re-linked by matching these identifiers. +pub type ChunkConnection = Wire; + +/// A chunk of a circuit. +#[derive(Debug, Clone)] +#[cfg_attr(feature = "pyo3", pyclass)] +pub struct Chunk { + /// The extracted circuit. + pub circ: Hugr, + /// The original wires connected to the input. + pub inputs: Vec, + /// The original wires connected to the output. + pub outputs: Vec, +} + +impl Chunk { + /// Extract a chunk from a circuit. + /// + /// The chunk is extracted from the input wires to the output wires. + pub(self) fn extract<'h, H: HugrView>( + circ: &'h H, + nodes: impl IntoIterator, + checker: &mut ConvexChecker<'h, H>, + ) -> Self { + let subgraph = SiblingSubgraph::try_from_nodes_with_checker( + nodes.into_iter().collect_vec(), + circ, + checker, + ) + .expect("Failed to define the chunk subgraph"); + let extracted = subgraph + .extract_subgraph(circ, "Chunk", ExtensionSet::new()) + .expect("Failed to extract chunk"); + // Transform the subgraph's input/output sets into wires that can be + // matched between different chunks. + // + // This requires finding the `Outgoing` port corresponding to each + // subgraph input. + let inputs = subgraph + .incoming_ports() + .iter() + .map(|wires| { + let (inp_node, inp_port) = wires[0]; + let (out_node, out_port) = circ + .linked_ports(inp_node, inp_port) + .exactly_one() + .ok() + .unwrap(); + Wire::new(out_node, out_port) + }) + .collect(); + let outputs = subgraph + .outgoing_ports() + .iter() + .map(|&(node, port)| Wire::new(node, port)) + .collect(); + Self { + circ: extracted, + inputs, + outputs, + } + } + + /// Insert the chunk back into a circuit. + // + // TODO: The new chunk may have input ports directly connected to outputs. We have to take care of those. + #[allow(clippy::type_complexity)] + pub(self) fn insert(&self, circ: &mut impl HugrMut, root: Node) -> ChunkInsertResult { + let chunk_sg: SiblingGraph<'_, DataflowParentID> = + SiblingGraph::try_new(&self.circ, self.circ.root()).unwrap(); + let subgraph = SiblingSubgraph::try_new_dataflow_subgraph(&chunk_sg) + .expect("The chunk circuit is no longer a dataflow"); + let node_map = circ + .insert_subgraph(root, &self.circ, &subgraph) + .expect("Failed to insert the chunk subgraph") + .node_map; + + let [inp, out] = circ.get_io(root).unwrap(); + let mut input_map = HashMap::with_capacity(self.inputs.len()); + let mut output_map = HashMap::with_capacity(self.outputs.len()); + + for (&connection, incoming) in self.inputs.iter().zip(subgraph.incoming_ports().iter()) { + let incoming = incoming.iter().map(|&(node, port)| { + if node == out { + // TODO: Add a map for directly connected Input connection -> Output Wire. + panic!("Chunk input directly connected to the output. This is not currently supported."); + } + (*node_map.get(&node).unwrap(),port) + }).collect_vec(); + input_map.insert(connection, incoming); + } + + for (&wire, &(node, port)) in self.outputs.iter().zip(subgraph.outgoing_ports().iter()) { + if node == inp { + // TODO: Add a map for directly connected Input Wire -> Output Wire. + panic!("Chunk input directly connected to the output. This is not currently supported."); + } + output_map.insert(wire, (*node_map.get(&node).unwrap(), port)); + } + + ChunkInsertResult { + incoming_connections: input_map, + outgoing_connections: output_map, + } + } +} + +/// A map from the original input/output [`ChunkConnection`]s to an inserted chunk's inputs and outputs. +struct ChunkInsertResult { + /// A map from incoming connections to a chunk, to the new node and incoming port targets. + /// + /// A chunk may specify multiple targets to be connected to a single incoming `ChunkConnection`. + pub incoming_connections: HashMap>, + /// A map from outgoing connections from a chunk, to the new node and outgoing port target. + pub outgoing_connections: HashMap, +} + +/// An utility for splitting a circuit into chunks, and reassembling them afterwards. +#[derive(Debug, Clone)] +#[cfg_attr(feature = "pyo3", pyclass)] +pub struct CircuitChunks { + /// The original circuit's signature. + signature: FunctionType, + + /// The original circuit's root metadata. + root_meta: NodeMetadata, + + /// The original circuit's inputs. + input_connections: Vec, + + /// The original circuit's outputs. + output_connections: Vec, + + /// The split circuits. + pub chunks: Vec, +} + +impl CircuitChunks { + /// Split a circuit into chunks. + /// + /// The circuit is split into chunks of at most `max_size` gates. + pub fn split(circ: &impl Circuit, max_size: usize) -> Self { + let root_meta = circ.get_metadata(circ.root()).clone(); + let signature = circ.circuit_signature().clone(); + + let [circ_input, circ_output] = circ.get_io(circ.root()).unwrap(); + let input_connections = circ + .node_outputs(circ_input) + .map(|port| Wire::new(circ_input, port)) + .collect(); + let output_connections = circ + .node_inputs(circ_output) + .flat_map(|p| circ.linked_ports(circ_output, p)) + .map(|(n, p)| Wire::new(n, p)) + .collect(); + + let mut chunks = Vec::new(); + let mut convex_checker = ConvexChecker::new(circ); + for commands in &circ.commands().map(|cmd| cmd.node()).chunks(max_size) { + chunks.push(Chunk::extract(circ, commands, &mut convex_checker)); + } + Self { + signature, + root_meta, + input_connections, + output_connections, + chunks, + } + } + + /// Reassemble the chunks into a circuit. + pub fn reassemble(self) -> Result { + let name = self + .root_meta + .get("name") + .and_then(|v| v.as_str()) + .unwrap_or(""); + let signature = Signature { + signature: self.signature, + // TODO: Is this correct? Can a circuit root have a fixed set of input extensions? + input_extensions: ExtensionSet::new(), + }; + + let builder = FunctionBuilder::new(name, signature).unwrap(); + let inputs = builder.input_wires(); + // TODO: Use the correct REGISTRY if the method accepts custom input resources. + let mut reassembled = builder.finish_hugr_with_outputs(inputs, ®ISTRY).unwrap(); + let root = reassembled.root(); + let [reassembled_input, reassembled_output] = reassembled.get_io(root).unwrap(); + + // The chunks input and outputs are each identified with a + // [`ChunkConnection`]. We collect both sides first, and rewire them + // after the chunks have been inserted. + let mut sources: HashMap = HashMap::new(); + let mut targets: HashMap> = HashMap::new(); + + for (&connection, port) in self + .input_connections + .iter() + .zip(reassembled.node_outputs(reassembled_input)) + { + reassembled.disconnect(reassembled_input, port)?; + sources.insert(connection, (reassembled_input, port)); + } + for (&connection, port) in self + .output_connections + .iter() + .zip(reassembled.node_inputs(reassembled_output)) + { + targets.insert(connection, vec![(reassembled_output, port)]); + } + + for chunk in self.chunks { + // Insert the chunk circuit without its input/output nodes. + let ChunkInsertResult { + incoming_connections, + outgoing_connections, + } = chunk.insert(&mut reassembled, root); + // Reconnect the chunk's inputs and outputs in the reassembled circuit. + sources.extend(outgoing_connections); + incoming_connections.into_iter().for_each(|(wire, tgts)| { + targets.entry(wire).or_default().extend(tgts); + }); + } + + // Reconnect the different chunks. + for (connection, (source, source_port)) in sources { + let Some(tgts) = targets.remove(&connection) else { + continue; + }; + for (target, target_port) in tgts { + reassembled.connect(source, source_port, target, target_port)?; + } + } + + Ok(reassembled) + } + + /// Returns a list of references to the split circuits. + pub fn circuits(&self) -> impl Iterator { + self.chunks.iter().map(|chunk| &chunk.circ) + } +} + +#[cfg(feature = "pyo3")] +#[pymethods] +impl CircuitChunks { + /// Reassemble the chunks into a circuit. + #[pyo3(name = "reassemble")] + fn py_reassemble(&self) -> PyResult> { + let hugr = self.clone().reassemble()?; + SerialCircuit::encode(&hugr)?.to_tket1() + } + + /// Returns clones of the split circuits. + #[pyo3(name = "circuits")] + fn py_circuits(&self) -> PyResult>> { + self.circuits() + .map(|hugr| SerialCircuit::encode(hugr)?.to_tket1()) + .collect() + } + + /// Replaces a chunk's circuit with an updated version. + #[pyo3(name = "update_circuit")] + fn py_update_circuit(&mut self, index: usize, new_circ: Py) -> PyResult<()> { + let hugr = SerialCircuit::_from_tket1(new_circ).decode()?; + if hugr.circuit_signature() != self.chunks[index].circ.circuit_signature() { + return Err(PyAttributeError::new_err( + "The new circuit has a different signature.", + )); + } + self.chunks[index].circ = hugr; + Ok(()) + } +} + +#[cfg(test)] +mod test { + use crate::circuit::CircuitHash; + use crate::utils::build_simple_circuit; + use crate::T2Op; + + use super::*; + + #[test] + fn split_reassemble() { + let circ = build_simple_circuit(2, |circ| { + circ.append(T2Op::H, [0])?; + circ.append(T2Op::CX, [0, 1])?; + circ.append(T2Op::T, [1])?; + circ.append(T2Op::H, [0])?; + circ.append(T2Op::CX, [0, 1])?; + circ.append(T2Op::H, [0])?; + circ.append(T2Op::CX, [0, 1])?; + Ok(()) + }) + .unwrap(); + + let mut chunks = CircuitChunks::split(&circ, 3); + + // Rearrange the chunks so nodes are inserted in a new order. + chunks.chunks.reverse(); + + let mut reassembled = chunks.reassemble().unwrap(); + + reassembled.infer_and_validate(®ISTRY).unwrap(); + assert_eq!(circ.circuit_hash(), reassembled.circuit_hash()); + } +}