Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Frontend] Corrected output of PyTree when using qml.counts() #1219

Open
wants to merge 29 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
e45bcae
Added fix for incorrect pytree output with qml.counts() + tests
abhamra Oct 19, 2024
0130ca1
Merge branch 'PennyLaneAI:main' into pytree_qml_counts_issue_arjun_bh…
abhamra Oct 19, 2024
6556507
running black linter
abhamra Oct 19, 2024
da3d038
codefactor fixes
abhamra Oct 19, 2024
5b3af98
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 22, 2024
708b759
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 22, 2024
5d18e78
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 23, 2024
1f0d19b
minor code fixes, correct location of tests + add mcm test, add chang…
abhamra Oct 23, 2024
5c42520
Merge branch 'pytree_qml_counts_issue_arjun_bhamra' of github.com:abh…
abhamra Oct 23, 2024
9dba319
fix for linter
abhamra Oct 23, 2024
dd7dc15
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 23, 2024
ec5a8ec
linter line length fix
abhamra Oct 23, 2024
a192610
Merge branch 'pytree_qml_counts_issue_arjun_bhamra' of github.com:abh…
abhamra Oct 23, 2024
c55b8e3
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 23, 2024
add7e2b
updated tests to use actual PyTreeDefs, not str rep
abhamra Oct 23, 2024
2969713
linter fixes
abhamra Oct 23, 2024
1cf0aa7
Update doc/releases/changelog-dev.md
abhamra Oct 23, 2024
ecc152d
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 23, 2024
af405f5
changelog and comment fixes
abhamra Oct 24, 2024
df32646
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 24, 2024
2347d36
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 24, 2024
9528a98
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 25, 2024
0075948
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 25, 2024
a01e7fb
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 25, 2024
d6972d0
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 26, 2024
5bb216f
add explanation for num_counts
abhamra Oct 28, 2024
0fbaf13
Merge branch 'pytree_qml_counts_issue_arjun_bhamra' of github.com:abh…
abhamra Oct 28, 2024
440aa84
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 28, 2024
3064287
Merge branch 'main' into pytree_qml_counts_issue_arjun_bhamra
abhamra Oct 30, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,8 @@
- Registers the func dialect as a requirement for running the scatter lowering pass.
- Emits error if `%input`, `%update` and `%result` are not of length 1 instead of segfaulting.

* Resolves a bug where calling `qml.counts()` within complex and/or nested return expressions did not return the correct `PyTreeDef`. [(#1219)](https://github.com/PennyLaneAI/catalyst/pull/1219)
abhamra marked this conversation as resolved.
Show resolved Hide resolved

<h3>Internal changes</h3>

* Remove deprecated pennylane code across the frontend.
Expand Down Expand Up @@ -382,6 +384,7 @@
This release contains contributions from (in alphabetical order):

Amintor Dusko,
Arjun Bhamra,
Joey Carter,
Spencer Comin,
Lillian M.A. Frederiksen,
Expand Down
44 changes: 34 additions & 10 deletions frontend/catalyst/jax_tracer.py
Original file line number Diff line number Diff line change
Expand Up @@ -844,6 +844,8 @@
"""
shots = get_device_shots(device)
out_classical_tracers = []
# NOTE: Number of qml.counts() we hit
num_counts = 0

for i, o in enumerate(outputs):
if isinstance(o, MeasurementProcess):
Expand Down Expand Up @@ -914,16 +916,8 @@
results = (jnp.asarray(results[0], jnp.int64), results[1])
out_classical_tracers.extend(results)
counts_tree = tree_structure(("keys", "counts"))
meas_return_trees_children = out_tree.children()
if len(meas_return_trees_children):
meas_return_trees_children[i] = counts_tree
out_tree = out_tree.make_from_node_data_and_children(
PyTreeRegistry(),
out_tree.node_data(),
meas_return_trees_children,
)
else:
out_tree = counts_tree
num_counts += 1
abhamra marked this conversation as resolved.
Show resolved Hide resolved
out_tree = replace_child_tree(out_tree, i + num_counts, counts_tree)
elif isinstance(o, StateMP) and not isinstance(o, DensityMatrixMP):
assert using_compbasis
shape = (2**nqubits,)
Expand All @@ -941,6 +935,36 @@
return out_classical_tracers, out_tree


def replace_child_tree(tree: PyTreeDef, index: int, subtree: PyTreeDef) -> PyTreeDef:
"""
Replace the index-th leaf node in a left-to-right depth-first tree traversal of a PyTreeDef with a given subtree.

Check notice on line 940 in frontend/catalyst/jax_tracer.py

View check run for this annotation

codefactor.io / CodeFactor

frontend/catalyst/jax_tracer.py#L940

Line too long (117/100) (line-too-long)
abhamra marked this conversation as resolved.
Show resolved Hide resolved

Args:
tree (PyTreeDef): The original PyTree.
index (int): The index of the leaf node to replace.
subtree (PyTreeDef): The new subtree to replace the original leaf node with.

Returns:
PyTreeDef: The modified PyTree with the replaced leaf node.
"""

def replace_node(node, idx):
if not node.children():
# Leaf node => update leaf node counter
idx[0] += 1
if idx[0] == index:
return subtree
return node

return node.make_from_node_data_and_children(
PyTreeRegistry(),
node.node_data(),
[replace_node(child, idx) for child in node.children()],
)

return replace_node(tree, [0])


@debug_logger
def is_transform_valid_for_batch_transforms(tape, flat_results):
"""Not all transforms are valid for batch transforms.
Expand Down
164 changes: 164 additions & 0 deletions frontend/test/pytest/test_pytree_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,5 +593,169 @@ def classical(x):
assert result.a == 4


class TestPyTreesQmlCounts:
"""Test QJIT workflows when using qml.counts in a return expression."""

def test_pytree_qml_counts_simple(self):
"""Test if a single qml.counts() can be used and output correctly."""
dev = qml.device("lightning.qubit", wires=1, shots=20)

@qjit
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
return {"1": qml.counts()}

observed = circuit(0.5)
expected = {"1": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))}

_, expected_shape = tree_flatten(expected)
_, observed_shape = tree_flatten(observed)
assert expected_shape == observed_shape

def test_pytree_qml_counts_nested(self):
"""Test if nested qml.counts() can be used and output correctly."""
dev = qml.device("lightning.qubit", wires=1, shots=20)

@qjit
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
return {"1": qml.counts()}, {"2": qml.expval(qml.Z(0))}

observed = circuit(0.5)
expected = (
{"1": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))},
{"2": jnp.array(-1, dtype=jnp.float64)},
)

_, expected_shape = tree_flatten(expected)
_, observed_shape = tree_flatten(observed)
assert expected_shape == observed_shape

@qjit
@qml.qnode(dev)
def circuit2(x):
qml.RX(x, wires=0)
return [{"1": qml.expval(qml.Z(0))}, {"2": qml.counts()}], {"3": qml.expval(qml.Z(0))}

observed = circuit2(0.5)
expected = (
[
{"1": jnp.array(-1, dtype=jnp.float64)},
{"2": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))},
],
{"3": jnp.array(-1, dtype=jnp.float64)},
)
_, expected_shape = tree_flatten(expected)
_, observed_shape = tree_flatten(observed)
assert expected_shape == observed_shape

def test_pytree_qml_counts_2_nested(self):
"""Test if multiple nested qml.counts() can be used and output correctly."""
dev = qml.device("lightning.qubit", wires=1, shots=20)

@qjit
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
return [{"1": qml.expval(qml.Z(0))}, {"2": qml.counts()}], [
{"3": qml.expval(qml.Z(0))},
{"4": qml.counts()},
]

observed = circuit(0.5)
expected = (
[
{"1": jnp.array(-1, dtype=jnp.float64)},
{"2": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))},
],
[
{"3": jnp.array(-1, dtype=jnp.float64)},
{"4": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))},
],
)
_, expected_shape = tree_flatten(expected)
_, observed_shape = tree_flatten(observed)
assert expected_shape == observed_shape

@qjit
@qml.qnode(dev)
def circuit2(x):
qml.RX(x, wires=0)
return [{"1": qml.expval(qml.Z(0))}, {"2": qml.counts()}], [
{"3": qml.counts()},
{"4": qml.expval(qml.Z(0))},
]

observed = circuit2(0.5)
expected = (
[
{"1": jnp.array(-1, dtype=jnp.float64)},
{"2": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))},
],
[
{"3": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))},
{"4": jnp.array(-1, dtype=jnp.float64)},
],
)
_, expected_shape = tree_flatten(expected)
_, observed_shape = tree_flatten(observed)
assert expected_shape == observed_shape

def test_pytree_qml_counts_longer(self):
"""Test if 3 differently nested qml.counts() can be used and output correctly."""
dev = qml.device("lightning.qubit", wires=1, shots=20)

@qjit
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
return [
[{"1": qml.expval(qml.Z(0))}, {"2": qml.counts()}],
[{"3": qml.expval(qml.Z(0))}, {"4": qml.counts()}],
{"5": qml.expval(qml.Z(0))},
{"6": qml.counts()},
]

observed = circuit(0.5)
expected = [
[
{"1": jnp.array(-1, dtype=jnp.float64)},
{"2": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))},
],
[
{"3": jnp.array(-1, dtype=jnp.float64)},
{"4": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))},
],
{"5": jnp.array(-1, dtype=jnp.float64)},
{"6": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))},
]
_, expected_shape = tree_flatten(expected)
_, observed_shape = tree_flatten(observed)
assert expected_shape == observed_shape

def test_pytree_qml_counts_mcm(self):
"""Test qml.counts() with mid circuit measurement."""
abhamra marked this conversation as resolved.
Show resolved Hide resolved
dev = qml.device("lightning.qubit", wires=1, shots=20)

@qml.qjit
@qml.qnode(dev, mcm_method="one-shot", postselect_mode=None)
def circuit(x):
qml.RX(x, wires=0)
measure(0, postselect=1)
return {"hi": qml.counts()}, {"bye": qml.expval(qml.Z(0))}, {"hi": qml.counts()}

observed = circuit(0.5)
expected = (
{"hi": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))},
{"bye": jnp.array(-1, dtype=jnp.float64)},
{"hi": (jnp.array((0, 1), dtype=jnp.int64), jnp.array((0, 3), dtype=jnp.int64))},
)
_, expected_shape = tree_flatten(expected)
_, observed_shape = tree_flatten(observed)
assert expected_shape == observed_shape


if __name__ == "__main__":
pytest.main(["-x", __file__])
Loading