-
-
Notifications
You must be signed in to change notification settings - Fork 21
🐛 Fix RL Training and Improve Structure #573
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
Draft
flowerthrower
wants to merge
23
commits into
main
Choose a base branch
from
bugfix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+171
−72
Draft
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
8a86438
🐛 gracefully handle VF2Layout no-solution-found
flowerthrower f34a9ae
disable progress bar
flowerthrower 7a89375
🐛 only consider valid circuits for terminal action
flowerthrower af50584
🚧 debug predictor
flowerthrower 1e3d3d4
🐛handle layout fail more gracefully
flowerthrower 25c8a4a
🚧 restructure state machine
flowerthrower 7eb5138
🚧 update state machine
flowerthrower 37653fb
🎨 add strict policy
flowerthrower 8802fbd
🚧 add og paper strategy
flowerthrower 6db8ee7
🎨 fix og policy
flowerthrower dcc3810
⏪ remove thesis changes
flowerthrower 440d54c
Merge remote-tracking branch 'origin/main' into bugfix
flowerthrower 450d2dc
⏪ revert thesis updates
flowerthrower e69cf51
⏪ use og strategy
flowerthrower 934e46c
🐛 fix no-layout found bug
flowerthrower 825773f
Merge branch 'main' into bugfix
flowerthrower 8b27982
Update src/mqt/predictor/rl/predictorenv.py
flowerthrower 729ade7
🎨 docstring
flowerthrower 983a4f6
Merge branch 'main' into bugfix
flowerthrower de36b57
🐛 fix routing check
flowerthrower bc667bd
Merge commit '983a4f61b72d10af05bfe762bb72f27aa9304fac' into bugfix
flowerthrower 7c745fe
🐛 use find qubit
flowerthrower 0d46fa9
🐛 fix no valid action bug
flowerthrower File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -21,7 +21,7 @@ | |
|
|
||
| from bqskit import Circuit | ||
| from qiskit.passmanager.base_tasks import Task | ||
| from qiskit.transpiler import Target | ||
| from qiskit.transpiler import Layout, Target | ||
|
|
||
| from mqt.predictor.reward import figure_of_merit | ||
| from mqt.predictor.rl.actions import Action | ||
|
|
@@ -40,7 +40,6 @@ | |
| from qiskit import QuantumCircuit | ||
| from qiskit.passmanager.flow_controllers import DoWhileController | ||
| from qiskit.transpiler import CouplingMap, PassManager, TranspileLayout | ||
| from qiskit.transpiler.passes import CheckMap, GatesInBasis | ||
| from qiskit.transpiler.passes.layout.vf2_layout import VF2LayoutStopReason | ||
|
|
||
| from mqt.predictor.hellinger import get_hellinger_model_path | ||
|
|
@@ -189,23 +188,21 @@ def step(self, action: int) -> tuple[dict[str, Any], float, bool, bool, dict[Any | |
| self.state: QuantumCircuit = altered_qc | ||
| self.num_steps += 1 | ||
|
|
||
| self.state._layout = self.layout # noqa: SLF001 | ||
|
|
||
| self.valid_actions = self.determine_valid_actions_for_state() | ||
| if len(self.valid_actions) == 0: | ||
| msg = "No valid actions left." | ||
| raise RuntimeError(msg) | ||
|
|
||
| if action == self.action_terminate_index: | ||
| assert action in self.valid_actions, "Terminate action is not valid but was chosen." | ||
| reward_val = self.calculate_reward() | ||
| done = True | ||
| else: | ||
| reward_val = 0 | ||
| done = False | ||
|
|
||
| # in case the Qiskit.QuantumCircuit has unitary or u gates in it, decompose them (because otherwise qiskit will throw an error when applying the BasisTranslator | ||
| if self.state.count_ops().get("unitary"): # ty: ignore[invalid-argument-type] | ||
| self.state = self.state.decompose(gates_to_decompose="unitary") | ||
|
|
||
| self.state._layout = self.layout # noqa: SLF001 | ||
| obs = create_feature_dict(self.state) | ||
| return obs, reward_val, done, False, {} | ||
|
|
||
|
|
@@ -268,10 +265,14 @@ def action_masks(self) -> list[bool]: | |
| """Returns a list of valid actions for the current state.""" | ||
| action_mask = [action in self.valid_actions for action in self.action_set] | ||
|
|
||
| # it is not clear how tket will handle the layout, so we remove all actions that are from "origin"=="tket" if a layout is set | ||
| # TKET layout/optimization actions must not run after a Qiskit layout has been set | ||
| # (it is not clear how tket will handle the layout). TKET routing actions are | ||
| # designed to work after a Qiskit layout via PreProcessTKETRoutingAfterQiskitLayout. | ||
| if self.layout is not None: | ||
| action_mask = [ | ||
| action_mask[i] and self.action_set[i].origin != CompilationOrigin.TKET for i in range(len(action_mask)) | ||
| action_mask[i] | ||
| and (self.action_set[i].origin != CompilationOrigin.TKET or i in self.actions_routing_indices) | ||
| for i in range(len(action_mask)) | ||
| ] | ||
|
|
||
| if self.has_parameterized_gates or self.layout is not None: | ||
|
|
@@ -342,9 +343,16 @@ def _apply_qiskit_action(self, action: Action, action_index: int) -> QuantumCirc | |
| ): | ||
| altered_qc = self._handle_qiskit_layout_postprocessing(action, pm, altered_qc) | ||
|
|
||
| elif action_index in self.actions_routing_indices and self.layout: | ||
| elif ( | ||
| action_index in self.actions_routing_indices and self.layout and pm.property_set["final_layout"] is not None | ||
| ): | ||
| self.layout.final_layout = pm.property_set["final_layout"] | ||
|
|
||
| # BasisTranslator errors on unitary gates; decompose them immediately so | ||
| # the circuit is always in a consistent state after a Qiskit action. | ||
| if altered_qc.count_ops().get("unitary"): # ty: ignore[invalid-argument-type] | ||
| altered_qc = altered_qc.decompose(gates_to_decompose="unitary") | ||
|
|
||
| return altered_qc | ||
|
|
||
| def _handle_qiskit_layout_postprocessing( | ||
|
|
@@ -357,8 +365,13 @@ def _handle_qiskit_layout_postprocessing( | |
| assert self.layout is not None | ||
| altered_qc, _ = postprocess_vf2postlayout(altered_qc, post_layout, self.layout) | ||
| elif action.name == "VF2Layout": | ||
| assert pm.property_set["VF2Layout_stop_reason"] == VF2LayoutStopReason.SOLUTION_FOUND | ||
| assert pm.property_set["layout"] | ||
| if pm.property_set["VF2Layout_stop_reason"] != VF2LayoutStopReason.SOLUTION_FOUND: | ||
| logger.warning( | ||
| "VF2Layout pass did not find a solution. Reason: %s", | ||
| pm.property_set["VF2Layout_stop_reason"], | ||
| ) | ||
| else: | ||
| assert pm.property_set["layout"] | ||
| else: | ||
| assert pm.property_set["layout"] | ||
|
|
||
|
|
@@ -385,7 +398,7 @@ def _apply_tket_action(self, action: Action, action_index: int) -> QuantumCircui | |
|
|
||
| qbs = tket_qc.qubits | ||
| tket_qc.rename_units({qbs[i]: Qubit("q", i) for i in range(len(qbs))}) | ||
| altered_qc = tk_to_qiskit(tket_qc) | ||
| altered_qc = tk_to_qiskit(tket_qc, replace_implicit_swaps=True) | ||
|
|
||
| if action_index in self.actions_routing_indices: | ||
| assert self.layout is not None | ||
|
|
@@ -428,27 +441,134 @@ def _apply_bqskit_action(self, action: Action, action_index: int) -> QuantumCirc | |
|
|
||
| return bqskit_to_qiskit(bqskit_compiled_qc) | ||
|
|
||
| def determine_valid_actions_for_state(self) -> list[int]: | ||
| """Determines and returns the valid actions for the current state.""" | ||
| check_nat_gates = GatesInBasis(basis_gates=self.device.operation_names) | ||
| check_nat_gates(self.state) | ||
| only_nat_gates = check_nat_gates.property_set["all_gates_in_basis"] | ||
| def is_circuit_laid_out(self, circuit: QuantumCircuit, layout: TranspileLayout | Layout) -> bool: | ||
| """True if every logical qubit in the circuit has a physical assignment.""" | ||
| if isinstance(layout, TranspileLayout): | ||
| # Use final_layout if available; otherwise fallback to initial_layout | ||
| layout = layout.final_layout or layout.initial_layout | ||
|
|
||
| if not only_nat_gates: | ||
| actions = self.actions_synthesis_indices + self.actions_opt_indices | ||
| if self.layout is not None: | ||
| actions += self.actions_routing_indices | ||
| return actions | ||
| v2p = layout.get_virtual_bits() | ||
| for instr in circuit.data: | ||
| for q in instr.qubits: | ||
| if q not in v2p: | ||
| # Logical qubit not assigned | ||
| return False | ||
| return True | ||
|
Comment on lines
+444
to
+456
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Validate all logical qubits, not just those appearing in instructions. 🔧 Suggested fix- for instr in circuit.data:
- for q in instr.qubits:
- if q not in v2p:
- # Logical qubit not assigned
- return False
+ for q in circuit.qubits:
+ if q not in v2p:
+ # Logical qubit not assigned
+ return False🤖 Prompt for AI Agents |
||
|
|
||
| check_mapping = CheckMap(coupling_map=self.device.build_coupling_map()) | ||
| check_mapping(self.state) | ||
| mapped = check_mapping.property_set["is_swap_mapped"] | ||
| def is_circuit_synthesized(self, circuit: QuantumCircuit) -> bool: | ||
| """Check if the circuit uses only native gates of the device. | ||
|
|
||
| if mapped and self.layout is not None: # The circuit is correctly mapped. | ||
| return [self.action_terminate_index, *self.actions_opt_indices] | ||
| Verifies that every gate name in the circuit is present in | ||
| ``device.operation_names``, equivalent to the ``GatesInBasis`` pass. | ||
|
|
||
| if self.layout is not None: # The circuit is not yet mapped but a layout is set. | ||
| return self.actions_routing_indices | ||
| Args: | ||
| circuit: QuantumCircuit to check. | ||
|
|
||
| # No layout applied yet | ||
| return self.actions_mapping_indices + self.actions_layout_indices + self.actions_opt_indices | ||
| Returns: | ||
| True if all gates are native to the device. | ||
| """ | ||
| native_names = set(self.device.operation_names) | ||
| return all( | ||
| instr.operation.name in native_names or instr.operation.name in ("barrier", "measure") | ||
| for instr in circuit.data | ||
| ) | ||
|
|
||
| def is_circuit_routed(self, circuit: QuantumCircuit, coupling_map: CouplingMap) -> bool: | ||
| """Check if a circuit is fully routed to the device, including directionality. | ||
|
|
||
| A circuit is considered routed if all two-qubit gates are on qubit pairs | ||
| that exist as directed edges in the device coupling map. | ||
|
|
||
| After a layout pass the circuit's qubits are already physical qubits, so | ||
| ``circuit.find_bit(q).index`` gives the physical index directly — | ||
| consistent with how ``reward.py`` looks up gate calibrations. | ||
|
|
||
| Args: | ||
| circuit: QuantumCircuit to check. | ||
| coupling_map: CouplingMap of the target device. | ||
|
|
||
| Returns: | ||
| True if fully routed, False otherwise. | ||
| """ | ||
| directed_edges = set(coupling_map.get_edges()) | ||
| for instr in circuit.data: | ||
| if len(instr.qubits) == 2: | ||
| q0 = circuit.find_bit(instr.qubits[0]).index | ||
| q1 = circuit.find_bit(instr.qubits[1]).index | ||
| if (q0, q1) not in directed_edges: | ||
| return False | ||
| return True | ||
|
|
||
| def determine_valid_actions_for_state(self) -> list[int]: | ||
| """Determine valid actions based on circuit state: synthesized, mapped, routed.""" | ||
| synthesized = self.is_circuit_synthesized(self.state) | ||
| laid_out = self.is_circuit_laid_out(self.state, self.layout) if self.layout else False | ||
| # Routing is only allowed after layout | ||
| routed = ( | ||
| self.is_circuit_routed(self.state, CouplingMap(self.device.build_coupling_map())) if laid_out else False | ||
| ) | ||
|
|
||
| actions = [] | ||
|
|
||
| og = True # Original (restricted) MDP | ||
| flexible = False # General MDP | ||
|
|
||
| # Initial state | ||
| if not synthesized and not laid_out and not routed: | ||
| if flexible: | ||
| actions.extend(self.actions_synthesis_indices) | ||
| actions.extend(self.actions_mapping_indices) | ||
| actions.extend(self.actions_layout_indices) | ||
| actions.extend(self.actions_opt_indices) | ||
| if og: | ||
| actions.extend(self.actions_synthesis_indices) | ||
| actions.extend(self.actions_opt_indices) | ||
|
|
||
| if synthesized and not laid_out and not routed: | ||
| if flexible: | ||
| actions.extend(self.actions_mapping_indices) | ||
| actions.extend(self.actions_layout_indices) | ||
| actions.extend(self.actions_opt_indices) | ||
| if og: | ||
| actions.extend(self.actions_mapping_indices) | ||
| actions.extend(self.actions_layout_indices) | ||
| actions.extend(self.actions_opt_indices) | ||
|
|
||
| # Not *depicted* in paper; necessary because optimization can destroy the native gate set | ||
| if not synthesized and laid_out and not routed: | ||
| if flexible: | ||
| actions.extend(self.actions_synthesis_indices) | ||
| actions.extend(self.actions_routing_indices) | ||
| actions.extend(self.actions_opt_indices) | ||
| if og: | ||
| actions.extend(self.actions_synthesis_indices) | ||
| actions.extend(self.actions_routing_indices) | ||
| actions.extend(self.actions_opt_indices) | ||
|
|
||
| # Not *depicted* in paper; necessary because of mapping-only passes | ||
| if synthesized and laid_out and not routed: | ||
| if flexible: | ||
| actions.extend(self.actions_routing_indices) | ||
| actions.extend(self.actions_opt_indices) | ||
| if og: | ||
| actions.extend(self.actions_routing_indices) | ||
|
|
||
| # Not *depicted* in paper; necessary because routing can insert non-native SWAPs | ||
| if not synthesized and laid_out and routed: | ||
| if flexible: | ||
| actions.extend(self.actions_synthesis_indices) | ||
| actions.extend(self.actions_opt_indices) | ||
| if og: | ||
| actions.extend(self.actions_synthesis_indices) | ||
| actions.extend(self.actions_opt_indices) | ||
|
|
||
| # Final state | ||
| if synthesized and laid_out and routed: | ||
| if flexible: | ||
| actions.extend([self.action_terminate_index]) | ||
| actions.extend(self.actions_opt_indices) | ||
| if og: | ||
| actions.extend([self.action_terminate_index]) | ||
| actions.extend(self.actions_opt_indices) | ||
|
|
||
| return actions | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.