Skip to content

Commit

Permalink
Merge branch 'main' into sharding-handling
Browse files Browse the repository at this point in the history
  • Loading branch information
nealerickson-qtm committed Oct 5, 2023
2 parents 7336634 + 80fc126 commit 0fcbb0b
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 32 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ repos:
- id: debug-statements

- repo: https://github.com/crate-ci/typos
rev: v1.16.14
rev: v1.16.17
hooks:
- id: typos

Expand All @@ -23,7 +23,7 @@ repos:
- id: black

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.291
rev: v0.0.292
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
Expand Down
Empty file removed docs/__init__.py
Empty file.
4 changes: 1 addition & 3 deletions pytket/phir/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
NOTE: Just a placeholder to allow convenient testing of the flows
"""
"""NOTE: Just a placeholder to allow convenient testing of the flows."""

from pytket.circuit import Circuit
from pytket.qasm.qasm import circuit_from_qasm
Expand Down
6 changes: 4 additions & 2 deletions pytket/phir/sharding/shard.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@

@dataclass
class Shard:
"""
"""The Shard class.
A shard is a logical grouping of operations that represents the unit by which
we actually do placement of qubits
we actually do placement of qubits.
"""

# The unique identifier of the shard
Expand All @@ -36,6 +37,7 @@ class Shard:
depends_upon: set[int]

def pretty_print(self) -> str:
"""Returns the shard in a human-friendly format."""
output = io.StringIO()
output.write(f"Shard {self.ID}:")
output.write(f"\n Command: {self.primary_command}")
Expand Down
58 changes: 39 additions & 19 deletions pytket/phir/sharding/sharder.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,31 @@


class Sharder:
"""
The sharder class is responsible for taking in a circuit in TKET representation
"""The Sharder class.
Responsible for taking in a circuit in TKET representation
and converting it into shards that can be subsequently handled in the
compilation pipeline.
"""

def __init__(self, circuit: Circuit) -> None:
"""Create Sharder object.
Args:
----
circuit: tket Circuit
"""
self._circuit = circuit
self._pending_commands: dict[UnitID, list[Command]] = {}
self._shards: list[Shard] = []
print(f"Sharder created for circuit {self._circuit}")

def shard(self) -> list[Shard]:
"""
Performs the sharding algorithm on the circuit the Sharder was initialized
with, returning the list of Shards needed to schedule
"""Performs sharding algorithm on the circuit the Sharder was initialized with.
Returns:
-------
list of Shards needed to schedule
"""
print("Sharding begins....")
# https://cqcl.github.io/tket/pytket/api/circuit.html#pytket.circuit.Command
Expand All @@ -48,9 +57,10 @@ def shard(self) -> list[Shard]:
return self._shards

def _process_command(self, command: Command) -> None:
"""
Handles a given TKET command (operation, bits, etc) according to the type
and the extant context within the Sharder
"""Handles a command per the type and the extant context within the Sharder.
Args:
command: tket command (operation, bits, etc)
"""
print("Processing command: ", command.op, command.op.type, command.args)
if command.op.type in NOT_IMPLEMENTED_OP_TYPES:
Expand All @@ -66,9 +76,13 @@ def _process_command(self, command: Command) -> None:
self._add_pending_sub_command(command)

def _build_shard(self, command: Command) -> None:
"""
Creates a Shard object given the extant sharding context and the primary
Command object passed in, and appends it to the Shard list
"""Builds a shard.
Creates a Shard object given the extant sharding context and the schedulable
Command object passed in, and appends it to the Shard list.
Args:
command: tket command (operation, bits, etc)
"""
# Rollup any sub commands (SQ gates) that interact with the same qubits
sub_commands: dict[UnitID, list[Command]] = {}
Expand All @@ -89,7 +103,7 @@ def _build_shard(self, command: Command) -> None:
for sub_command in all_commands:
bits_written.update(sub_command.bits)
bits_read.update(
set(filter(lambda x: isinstance(x, Bit), sub_command.args)), # type: ignore [misc, arg-type] # noqa: E501
set(filter(lambda x: isinstance(x, Bit), sub_command.args)), # type: ignore [misc, arg-type]
)

# Handle dependency calculations
Expand Down Expand Up @@ -135,10 +149,6 @@ def _build_shard(self, command: Command) -> None:
print("Appended shard:", shard)

def _cleanup_remaining_commands(self) -> None:
"""
Checks for any remaining "unsharded" commands, and if found, adds them
to Barrier op shards for each qubit
"""
remaining_qubits = [k for k, v in self._pending_commands.items() if v]
for qubit in remaining_qubits:
self._circuit.add_barrier([qubit])
Expand All @@ -149,9 +159,13 @@ def _cleanup_remaining_commands(self) -> None:
self._build_shard(barrier_command)

def _add_pending_sub_command(self, command: Command) -> None:
"""
"""Adds a pending command.
Adds a pending sub command to the buffer to be flushed when a schedulable
operation creates a Shard.
Args:
command: tket command (operation, bits, etc)
"""
key = command.qubits[0]
if key not in self._pending_commands:
Expand All @@ -163,9 +177,15 @@ def _add_pending_sub_command(self, command: Command) -> None:

@staticmethod
def should_op_create_shard(op: Op) -> bool:
"""
Returns `True` if the operation is one that should result in shard creation.
"""Decide whether to create a shard.
This includes non-gate operations like measure/reset as well as 2-qubit gates.
Args:
op: operation
Returns:
`True` if the operation is one that should result in shard creation
"""
return (
op.type in (SHARD_TRIGGER_OP_TYPES)
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ build==1.0.3
mypy==1.5.1
pre-commit==3.4.0
pytest==7.4.2
ruff==0.0.291
ruff==0.0.292
pytket==1.20.1
wheel==0.41.2
20 changes: 15 additions & 5 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# See https://docs.astral.sh/ruff/rules/
target-version = "py310"

line-length = 88
Expand All @@ -11,6 +12,7 @@ select = [
"BLE", # flake8-blind-except
"C4", # flake8-comprehensions
"COM", # flake8-commas
"D", # pydocstyle
"EM", # flake8-errmsg
"EXE", # flake8-executable
"F", # pyFlakes
Expand Down Expand Up @@ -43,16 +45,24 @@ select = [
]

ignore = [
"T201", # no prints flake-8
"T201", # no prints flake-8
"FIX002", # Allow todos
"TD002", # Allow no author todos
"TD003", # allow todos with no issues
"TD002", # Allow no author todos
"TD003", # allow todos with no issues
"D100", # Missing docstring in public module
]

[per-file-ignores]
"__init__.py" = ["F401"] # module imported but unused
"__init__.py" = ["F401", "D104"] # module imported but unused
"docs/*" = [
"D100", # Missing docstring in public module
"INP001", # File * is part of an implicit namespace package. Add an `__init__.py`.
]
"tests/*" = [
"S101", # Use of `assert` detected
"INP001",
"D101", # Missing docstring in public class
"D102", # Missing docstring in public method
"S101", # Use of `assert` detected
"PLR2004" # Magic constants
]

Expand Down
8 changes: 8 additions & 0 deletions tests/sample_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,12 @@ class QasmFiles(Enum):


def get_qasm_as_circuit(qasm_file: QasmFiles) -> Circuit:
"""Utility function to convert a QASM file to Circuit.
Args:
qasm_file: enum for a QASM file
Returns:
Corresponding tket circuit
"""
return circuit_from_qasm(f"tests/data/qasm/{qasm_file.name}.qasm")

0 comments on commit 0fcbb0b

Please sign in to comment.