Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
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
4 changes: 3 additions & 1 deletion qiskit/passmanager/base_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from collections.abc import Iterable, Callable, Generator
from typing import Any

from .compilation_status import RunState, PassManagerState
from .compilation_status import RunState, PassManagerState, PropertySet

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -62,6 +62,7 @@ class GenericPass(Task, ABC):
"""

def __init__(self):
self.property_set = PropertySet()
self.requires: Iterable[Task] = []

def name(self) -> str:
Expand All @@ -77,6 +78,7 @@ def execute(
# Overriding this method is not safe.
# Pass subclass must keep current implementation.
# Especially, task execution may break when method signature is modified.
self.property_set = state.property_set

if self.requires:
# pylint: disable=cyclic-import
Expand Down
2 changes: 2 additions & 0 deletions qiskit/passmanager/flow_controllers.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ def iter_tasks(self, state: PassManagerState) -> Generator[Task, PassManagerStat
state = yield task
if not self.do_while(state.property_set):
return
# Remove stored tasks from the completed task collection for next loop
state.workflow_status.completed_passes.difference_update(self.tasks)
Comment on lines +136 to +137

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I kind of get why we're doing this, but the need also potentially points to a data-model problem in the idea of "completed passes" to me; the pass still completely after a loop iteration, and it's not immediately clear to me that starting a new loop should throw that information away.

What part of the logic is causing a pass to get skipped if it was completed? Passes aren't required to be idempotent, so a pass having been run shouldn't be sufficient to cause it to be skipped on a second attempt.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line. Change to this logic causes many test failures in test.python.transpiler.test_pass_scheduler

if self not in state.workflow_status.completed_passes:
ret = self.run(passmanager_ir)
run_state = RunState.SUCCESS
else:
run_state = RunState.SKIP

I guess this protection is added because of GenericPass.required. i.e.

pm = PassManager([PassB, PassA[required=PassB]])

runs PassB twice.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, but I think that's potentially indicative of buggy handling: pass_ = MyPass(); PassManager([pass_, pass_]) should run pass_ twice unless the pass specifically marks itself as being idempotent somehow. It's a different story if the pass is inserted into the pipeline by requires, because that's an implicit add and it's fine to re-use a previous run if we know that the output from it is still valid.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I just tried it on 0.25.3, and I realise now that what I'm complaining about is pre-existing behaviour. I think that's bad behaviour, but it being pre-existing puts it out of scope of this PR. The fix you've got in this comment is fine.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really like the required mechanism. Since dependencies are needed to be instantiated within the target pass, the target pass may require extra constructor args if passes have different interface. If we remove this mechanism, I think we can drop completed_passes and awkward pass equality check.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We definitely do use the required handling in some places in the existing pipelines, so it won't be as easy as completely stripping it out. I think the intent of it is good, it's just that it uses referential pass equality to implicitly mean "idempotent", which isn't generally true, and that's the knock-on problem here.

@nkanazawa1989 nkanazawa1989 Nov 2, 2023

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually circuit transform pass is not idempotent (so pass_ = MyPass(); PassManager([pass_, pass_]) should work as you expect), but it also removes all passes because .preserves is usually empty at least in Qiskit passes.

def update_status(
self,
state: PassManagerState,
run_state: RunState,
) -> PassManagerState:
state = super().update_status(state, run_state)
if run_state == RunState.SUCCESS:
state.workflow_status.completed_passes.intersection_update(set(self.preserves))
return state

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that's what I mean - I think PassManager([pass_, pass_]) should run pass_ twice in the general case, because there's nothing marking _pass as idempotent, but the "has this pass run?" handling that existed in 0.25.3 would mean it only runs once. Since it was in 0.25.3 and the 0.45.0 passmanager just maintains the same behaviour, there's no need to rush in a fix now.

raise PassManagerError("Maximum iteration reached. max_iteration=%i" % max_iteration)


Expand Down
2 changes: 1 addition & 1 deletion qiskit/passmanager/passmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ def callback_func(**kwargs):
return in_programs

is_list = True
if not isinstance(in_programs, Sequence):
if not (isinstance(in_programs, Sequence) and not isinstance(in_programs, str)):
Comment thread
nkanazawa1989 marked this conversation as resolved.
Outdated
in_programs = [in_programs]
is_list = False

Expand Down
16 changes: 0 additions & 16 deletions qiskit/transpiler/basepasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ class BasePass(GenericPass, metaclass=MetaPass):
def __init__(self):
super().__init__()
self.preserves: Iterable[GenericPass] = []
self.property_set = PropertySet()
self._hash = hash(None)

def __hash__(self):
Expand Down Expand Up @@ -118,21 +117,6 @@ def is_analysis_pass(self):
"""
return isinstance(self, AnalysisPass)

def execute(
self,
passmanager_ir: PassManagerIR,
state: PassManagerState,
callback: Callable = None,
) -> tuple[PassManagerIR, PassManagerState]:
# For backward compatibility.
# Circuit passes access self.property_set.
self.property_set = state.property_set
return super().execute(
passmanager_ir=passmanager_ir,
state=state,
callback=callback,
)

def __call__(
self,
circuit: QuantumCircuit,
Expand Down
77 changes: 77 additions & 0 deletions test/python/passmanager/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

"""Pass manager test cases."""

import io
import re
from itertools import zip_longest
from logging import StreamHandler, getLogger

from qiskit.passmanager import PassManagerState, WorkflowStatus, PropertySet
from qiskit.test import QiskitTestCase


class PassManagerTestCase(QiskitTestCase):
"""Test case for the pass manager module."""

def setUp(self):
super().setUp()

self.output = io.StringIO()
self.state = PassManagerState(
workflow_status=WorkflowStatus(),
property_set=PropertySet(),
)

logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)

logger.setLevel("DEBUG")
logger.addHandler(StreamHandler(self.output))

def assertLogEqual(self, func, expected_lines, *args, exception_type=None):
"""Execute provided function and verify logger.

Args:
func (Callable): Function to test.
expected_lines (List[str]): Expected log output.
args (Any): Arguments to the function.
exception_type (Type): Optional. Expected exception for error handling.

Returns:
Any: Output values from the function.
"""
if exception_type:
self.assertRaises(exception_type, func, *args)
out = None
else:
out = func(*args)

self.output.seek(0)
recorded_lines = [line.rstrip() for line in self.output.readlines()]
for i, (expected, recorded) in enumerate(zip_longest(expected_lines, recorded_lines)):
expected = expected or ""
recorded = recorded or ""
if not re.fullmatch(expected, recorded):
raise AssertionError(
f"Log didn't match. Mismatch found at line #{i}.\n\n"
f"Expected:\n{self._format_log(expected_lines)}\n"
f"Recorded:\n{self._format_log(recorded_lines)}"
)
return out

@jakelishman jakelishman Nov 2, 2023

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this code copied from somewhere? The exception handling within this function shouldn't be necessary; wrapping a "standard" call to this function in the self.assertRaises context manager in the regular test should all work correctly.

It'd also likely be better if this function was a context-manager wrapper around unittest.TestCase.assertLogs - it's much easier to read tests written in context-manager form than "exploded function call" (assertRaises(f, arg0, arg1, ...)).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I needed this to check

finally:
ret = ret or passmanager_ir
if run_state != RunState.SKIP:
running_time = time.time() - start_time
logger.info("Pass: %s - %.5f (ms)", self.name(), running_time * 1000)
if callback is not None:
callback(
task=self,
passmanager_ir=ret,
property_set=state.property_set,
running_time=running_time,
count=state.workflow_status.count,
)

The assertRaises context manager will catch the error as you say, but the assertLogEqual function returns before checking the log.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, but if they're both used as context managers, the clean-up code from both (the bit that contains the assertions) will still run in both correctly; we can use the context-manager stack to manage things arbitrarily, rather than needing hard-coded functions.

@jakelishman jakelishman Nov 2, 2023

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In very very very rough form, what I'm meaning is something like:

import contextlib]
import unittest

class MyTestCas(unittest.TestCase):
    @contextlib.contextmanager
    def assertLogContains(self, expected_lines):        
        with self.assertLogs() as cm:
            yield cm
        recorded_lines = cm.output
        for i, (expected, recorded) in enumerate(zip(expected_lines, recorded_lines)):
            # ... your existing handling

then I think it should work in test cases as:

def test_logs_while_raising(self):
    with self.assertLogContains(["blah blah"]):
        getLogger().log("blah blah")
        with self.assertRaises(Exception):
            raise Exception

and that test would pass.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(possibly the log-checking code should be in a finally block, so there's no spurious passes if a test author accidentally puts the assertLogContains and assertRaises calls the wrong way round)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, that's neat. I'll try

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 846e416. I needed some ugly hack because of this logic.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmmm it didn't work. The default formatter is bit ugly but maybe okey.

Expected:
#00: Pass: TaskC - (\d*\.)?\d+ \(ms\)
#01: Pass: TaskB - (\d*\.)?\d+ \(ms\)

Recorded:
#00: INFO:qiskit.passmanager.base_tasks:Pass: TaskA - 0.00596 (ms)
#01: INFO:qiskit.passmanager.base_tasks:Pass: TaskB - 0.00691 (ms)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, that's unfortunately gross of the standard library. Unfortunately, I think we're going to have problems with the private method: the unittest/_log.py was only split out from unittest/case.py in Python 3.9, so if we're going to go the way of accessing private internals, we'll need to have an import catch for Python 3.8 to pull it from unittest.case instead. The actual private code didn't meaningfully change, though, so it'll just about hold up.

Is there any way we can write the test enforcing the default logging format, so we can avoid needing the private access?

def _format_log(self, lines):
out = ""
for i, line in enumerate(lines):
out += f"#{i:02d}: {line}\n"
return out
126 changes: 126 additions & 0 deletions test/python/passmanager/test_generic_pass.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-class-docstring

"""Pass manager test cases."""

from test.python.passmanager import PassManagerTestCase

from logging import getLogger

from qiskit.passmanager import GenericPass
from qiskit.passmanager.compilation_status import RunState


class TestGenericPass(PassManagerTestCase):
"""Tests for the GenericPass subclass."""

def test_run_task(self):
"""Test case: Simple successful task execution."""

class Task(GenericPass):
def run(self, passmanager_ir):
return passmanager_ir

task = Task()
data = "test_data"
expected = [r"Pass: Task - (\d*\.)?\d+ \(ms\)"]
self.assertLogEqual(task.execute, expected, data, self.state)
self.assertEqual(self.state.workflow_status.count, 1)
self.assertIn(task, self.state.workflow_status.completed_passes)
self.assertEqual(self.state.workflow_status.previous_run, RunState.SUCCESS)

def test_failure_task(self):
"""Test case: Log is created regardless of success."""

class TestError(Exception):
pass

class RaiseError(GenericPass):
def run(self, passmanager_ir):
raise TestError()

task = RaiseError()
data = "test_data"
expected = [r"Pass: RaiseError - (\d*\.)?\d+ \(ms\)"]
self.assertLogEqual(task.execute, expected, data, self.state, exception_type=TestError)
self.assertEqual(self.state.workflow_status.count, 0)
self.assertNotIn(task, self.state.workflow_status.completed_passes)
self.assertEqual(self.state.workflow_status.previous_run, RunState.FAIL)

def test_requires(self):
"""Test cate: Dependency tasks are run in advance to user provided task."""

class TaskA(GenericPass):
def run(self, passmanager_ir):
return passmanager_ir

class TaskB(GenericPass):
def __init__(self):
super().__init__()
self.requires = [TaskA()]

def run(self, passmanager_ir):
return passmanager_ir

task = TaskB()
data = "test_data"
expected = [
r"Pass: TaskA - (\d*\.)?\d+ \(ms\)",
r"Pass: TaskB - (\d*\.)?\d+ \(ms\)",
]
self.assertLogEqual(task.execute, expected, data, self.state)
self.assertEqual(self.state.workflow_status.count, 2)

def test_requires_in_list(self):
"""Test cate: Dependency tasks are not executed multiple times."""

class TaskA(GenericPass):
def run(self, passmanager_ir):
return passmanager_ir

class TaskB(GenericPass):
def __init__(self):
super().__init__()
self.requires = [TaskA()]

def run(self, passmanager_ir):
return passmanager_ir

task = TaskB()
data = "test_data"
expected = [
r"Pass: TaskB - (\d*\.)?\d+ \(ms\)",
]
self.state.workflow_status.completed_passes.add(task.requires[0]) # already done
self.assertLogEqual(task.execute, expected, data, self.state)
self.assertEqual(self.state.workflow_status.count, 1)

def test_run_with_callable(self):
"""Test case: Callable is called after generic pass is run."""

# pylint: disable=unused-argument
def test_callable(task, passmanager_ir, property_set, running_time, count):
logger = getLogger()
logger.info("%s is running on %s", task.name(), passmanager_ir)

class Task(GenericPass):
def run(self, passmanager_ir):
return passmanager_ir

task = Task()
data = "test_data"
expected = [
r"Pass: Task - (\d*\.)?\d+ \(ms\)",
r"Task is running on test_data",
]
self.assertLogEqual(task.execute, expected, data, self.state, test_callable)
Loading