-
Notifications
You must be signed in to change notification settings - Fork 42
✨ Add MLIR pass for merging rotation gates #1019
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
Merged
Merged
Changes from 42 commits
Commits
Show all changes
45 commits
Select commit
Hold shift + click to select a range
c606307
Begin implementing merge pass [skip ci]
denialhaag 5bf980e
Continue implementing merge pass [skip ci]
denialhaag 02f92c5
At least fix the segmentation fault [no ci]
denialhaag e8dc6d5
Make some progress [skip ci]
denialhaag a64c0cf
Actually make it work for rx gates!
denialhaag 0ca5c6a
Remove setParams() again
denialhaag 76060dd
Fix linter warnings
denialhaag 1c6d7ec
Define createNewUser() function
denialhaag c3c4991
Support more gates without testing if it works
denialhaag df0ed8f
Test more single-qubit gates
denialhaag b7ccbbf
Test two-qubit gates
denialhaag c0e65ae
Only support simple gates for now
denialhaag f315ac2
Fix linter warnings
denialhaag 00114af
Fix remaining linter warning
denialhaag 5605dde
Also support rzx gate
denialhaag a3713c9
Define rewriteSingleAdditiveParam() function
denialhaag e71748c
Perform addition on underlying doubles
denialhaag 6a29212
Support cancellation of gates without testing it
denialhaag d1d0653
Test cancellation
denialhaag 8f7269f
Support cancellation also for xxminusyy and xxplusyy
denialhaag 733fc23
Support cancellation also for u and u2 without testing it
denialhaag 77f8d67
Add separators to tests
denialhaag 0151be7
Fix matching
denialhaag 06270d4
Test cancellation of u and u2
denialhaag 7c89b99
Improve test comments
denialhaag a2f481a
Fix linter warnings
denialhaag 7e1d6ef
Fix more linter warnings
denialhaag 161f6e7
One more attempt at fixing linter warnings
denialhaag f8205b0
Merge branch 'main' into merge-pass
denialhaag 0164648
Erase op at the very end
denialhaag 9336060
Improve docstrings
denialhaag 23078e5
Merge branch 'main' into merge-pass
denialhaag fb8465b
Only support strict merging of simple rotation gates for now
denialhaag 608f81b
Improve tests for single-qubit gates
denialhaag bfa273c
Improve tests for multi-qubit gates
denialhaag a9f82a1
Add entry to changelog
denialhaag 96a9af6
Clean up check statements
denialhaag 76f6c13
Add more test cases of incompatible gates
denialhaag 9f9ddcc
Also test variable angles
denialhaag 577244d
Reuse set of mergeable gates
denialhaag 4d8510f
🎨 pre-commit fixes
pre-commit-ci[bot] 464a255
Merge branch 'main' into merge-pass
burgholzer aa3d444
Also support p gate
denialhaag ddaefd1
Add comment to test
denialhaag c20b21f
Define template function to reduce code duplication
denialhaag 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
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 |
---|---|---|
@@ -0,0 +1,45 @@ | ||
/* | ||
* Copyright (c) 2023 - 2025 Chair for Design Automation, TUM | ||
* Copyright (c) 2025 Munich Quantum Software Company GmbH | ||
* All rights reserved. | ||
* | ||
* SPDX-License-Identifier: MIT | ||
* | ||
* Licensed under the MIT License | ||
*/ | ||
|
||
#include "mlir/Dialect/Common/Compat.h" | ||
#include "mlir/Dialect/MQTOpt/Transforms/Passes.h" | ||
|
||
#include <mlir/IR/PatternMatch.h> | ||
#include <mlir/Support/LLVM.h> | ||
#include <utility> | ||
|
||
namespace mqt::ir::opt { | ||
|
||
#define GEN_PASS_DEF_MERGEROTATIONGATES | ||
#include "mlir/Dialect/MQTOpt/Transforms/Passes.h.inc" | ||
|
||
/** | ||
* @brief This pattern attempts to merge consecutive rotation gates. | ||
*/ | ||
struct MergeRotationGates final | ||
: impl::MergeRotationGatesBase<MergeRotationGates> { | ||
|
||
void runOnOperation() override { | ||
// Get the current operation being operated on. | ||
auto op = getOperation(); | ||
auto* ctx = &getContext(); | ||
|
||
// Define the set of patterns to use. | ||
mlir::RewritePatternSet patterns(ctx); | ||
populateMergeRotationGatesPatterns(patterns); | ||
|
||
// Apply patterns in an iterative and greedy manner. | ||
if (mlir::failed(APPLY_PATTERNS_GREEDILY(op, std::move(patterns)))) { | ||
signalPassFailure(); | ||
} | ||
} | ||
}; | ||
|
||
} // namespace mqt::ir::opt |
219 changes: 219 additions & 0 deletions
219
mlir/lib/Dialect/MQTOpt/Transforms/MergeRotationGatesPattern.cpp
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 |
---|---|---|
@@ -0,0 +1,219 @@ | ||
/* | ||
* Copyright (c) 2023 - 2025 Chair for Design Automation, TUM | ||
* Copyright (c) 2025 Munich Quantum Software Company GmbH | ||
* All rights reserved. | ||
* | ||
* SPDX-License-Identifier: MIT | ||
* | ||
* Licensed under the MIT License | ||
*/ | ||
|
||
#include "mlir/Dialect/MQTOpt/IR/MQTOptDialect.h" | ||
#include "mlir/Dialect/MQTOpt/Transforms/Passes.h" | ||
#include "mlir/IR/BuiltinAttributes.h" | ||
|
||
#include <algorithm> | ||
#include <cstddef> | ||
#include <iterator> | ||
#include <mlir/Dialect/Arith/IR/Arith.h> | ||
#include <mlir/IR/MLIRContext.h> | ||
#include <mlir/IR/Operation.h> | ||
#include <mlir/IR/PatternMatch.h> | ||
#include <mlir/IR/Value.h> | ||
#include <mlir/IR/ValueRange.h> | ||
#include <mlir/Support/LLVM.h> | ||
#include <mlir/Support/LogicalResult.h> | ||
#include <stdexcept> | ||
#include <string> | ||
#include <unordered_set> | ||
|
||
namespace mqt::ir::opt { | ||
|
||
static const std::unordered_set<std::string> MERGEABLE_GATES = { | ||
"gphase", "rx", "ry", "rz", "rxx", "ryy", "rzz", "rzx"}; | ||
|
||
/** | ||
* @brief This pattern attempts to merge consecutive rotation gates. | ||
*/ | ||
struct MergeRotationGatesPattern final | ||
: mlir::OpInterfaceRewritePattern<UnitaryInterface> { | ||
DRovara marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
explicit MergeRotationGatesPattern(mlir::MLIRContext* context) | ||
: OpInterfaceRewritePattern(context) {} | ||
|
||
/** | ||
* @brief Checks if two gates can be merged. | ||
* | ||
* @param a The first gate. | ||
* @param b The second gate. | ||
* @return True if the gates can be merged, false otherwise. | ||
*/ | ||
[[nodiscard]] static bool areGatesMergeable(mlir::Operation& a, | ||
mlir::Operation& b) { | ||
const auto aName = a.getName().stripDialect().str(); | ||
const auto bName = b.getName().stripDialect().str(); | ||
|
||
return ((aName == bName) && (MERGEABLE_GATES.count(aName) == 1)); | ||
} | ||
|
||
/** | ||
* @brief Checks if all users of an operation are the same. | ||
* | ||
* @param users The users to check. | ||
* @return True if all users are the same, false otherwise. | ||
*/ | ||
[[nodiscard]] static bool | ||
areUsersUnique(const mlir::ResultRange::user_range& users) { | ||
return std::none_of(users.begin(), users.end(), | ||
[&](auto* user) { return user != *users.begin(); }); | ||
} | ||
|
||
mlir::LogicalResult match(UnitaryInterface op) const override { | ||
const auto& users = op->getUsers(); | ||
if (!areUsersUnique(users)) { | ||
return mlir::failure(); | ||
} | ||
auto* user = *users.begin(); | ||
if (!areGatesMergeable(*op, *user)) { | ||
return mlir::failure(); | ||
} | ||
auto unitaryUser = mlir::dyn_cast<UnitaryInterface>(user); | ||
if (op.getAllOutQubits() != unitaryUser.getAllInQubits()) { | ||
return mlir::failure(); | ||
} | ||
if (op.getPosCtrlInQubits().size() != | ||
unitaryUser.getPosCtrlInQubits().size() || | ||
op.getNegCtrlInQubits().size() != | ||
unitaryUser.getNegCtrlInQubits().size()) { | ||
// We only need to check the sizes, because the order of the controls was | ||
// already checked by the previous condition. | ||
burgholzer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return mlir::failure(); | ||
} | ||
return mlir::success(); | ||
} | ||
|
||
/** | ||
* @brief Merges two consecutive rotation gates into a single gate. | ||
* | ||
* The function supports gphase, rx, ry, rz, rxx, ryy, rzz, and rzx. | ||
* The gates are merged by adding their angles. | ||
* The merged gate is not removed if the angles add up to zero. | ||
* | ||
* @param op The first instance of the rotation gate. | ||
* @param rewriter The pattern rewriter. | ||
*/ | ||
void static rewriteAdditiveAngle(UnitaryInterface op, | ||
mlir::PatternRewriter& rewriter) { | ||
auto const type = op->getName().stripDialect().str(); | ||
|
||
auto user = mlir::dyn_cast<UnitaryInterface>(*op->getUsers().begin()); | ||
auto loc = user->getLoc(); | ||
|
||
auto opParam = op.getParams()[0]; | ||
auto userParam = user.getParams()[0]; | ||
|
||
auto add = rewriter.create<mlir::arith::AddFOp>(loc, opParam, userParam); | ||
const llvm::SmallVector<mlir::Value, 1> newParamsVec{add.getResult()}; | ||
const mlir::ValueRange newParams(newParamsVec); | ||
|
||
auto userInQubits = user.getInQubits(); | ||
auto userPosCtrlInQubits = user.getPosCtrlInQubits(); | ||
auto userNegCtrlInQubits = user.getNegCtrlInQubits(); | ||
|
||
UnitaryInterface newUser; | ||
if (type == "gphase") { | ||
newUser = rewriter.create<GPhaseOp>( | ||
loc, userInQubits.getType(), userPosCtrlInQubits.getType(), | ||
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{}, | ||
mlir::DenseBoolArrayAttr{}, newParams, userInQubits, | ||
userPosCtrlInQubits, userNegCtrlInQubits); | ||
} else if (type == "rx") { | ||
newUser = rewriter.create<RXOp>( | ||
loc, userInQubits.getType(), userPosCtrlInQubits.getType(), | ||
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{}, | ||
mlir::DenseBoolArrayAttr{}, newParams, userInQubits, | ||
userPosCtrlInQubits, userNegCtrlInQubits); | ||
} else if (type == "ry") { | ||
newUser = rewriter.create<RYOp>( | ||
loc, userInQubits.getType(), userPosCtrlInQubits.getType(), | ||
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{}, | ||
mlir::DenseBoolArrayAttr{}, newParams, userInQubits, | ||
userPosCtrlInQubits, userNegCtrlInQubits); | ||
} else if (type == "rz") { | ||
newUser = rewriter.create<RZOp>( | ||
loc, userInQubits.getType(), userPosCtrlInQubits.getType(), | ||
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{}, | ||
mlir::DenseBoolArrayAttr{}, newParams, userInQubits, | ||
userPosCtrlInQubits, userNegCtrlInQubits); | ||
} else if (type == "rxx") { | ||
newUser = rewriter.create<RXXOp>( | ||
loc, userInQubits.getType(), userPosCtrlInQubits.getType(), | ||
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{}, | ||
mlir::DenseBoolArrayAttr{}, newParams, userInQubits, | ||
userPosCtrlInQubits, userNegCtrlInQubits); | ||
} else if (type == "ryy") { | ||
newUser = rewriter.create<RYYOp>( | ||
loc, userInQubits.getType(), userPosCtrlInQubits.getType(), | ||
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{}, | ||
mlir::DenseBoolArrayAttr{}, newParams, userInQubits, | ||
userPosCtrlInQubits, userNegCtrlInQubits); | ||
} else if (type == "rzz") { | ||
newUser = rewriter.create<RZZOp>( | ||
loc, userInQubits.getType(), userPosCtrlInQubits.getType(), | ||
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{}, | ||
mlir::DenseBoolArrayAttr{}, newParams, userInQubits, | ||
userPosCtrlInQubits, userNegCtrlInQubits); | ||
} else if (type == "rzx") { | ||
newUser = rewriter.create<RZXOp>( | ||
loc, userInQubits.getType(), userPosCtrlInQubits.getType(), | ||
userNegCtrlInQubits.getType(), mlir::DenseF64ArrayAttr{}, | ||
mlir::DenseBoolArrayAttr{}, newParams, userInQubits, | ||
userPosCtrlInQubits, userNegCtrlInQubits); | ||
} else { | ||
throw std::runtime_error("Unsupported operation type: " + type); | ||
} | ||
burgholzer marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Prepare erasure of op | ||
const auto& opAllInQubits = op.getAllInQubits(); | ||
const auto& newUserAllInQubits = newUser.getAllInQubits(); | ||
for (size_t i = 0; i < newUser->getOperands().size(); i++) { | ||
const auto& operand = newUser->getOperand(i); | ||
const auto found = std::find(newUserAllInQubits.begin(), | ||
newUserAllInQubits.end(), operand); | ||
if (found == newUserAllInQubits.end()) { | ||
continue; | ||
} | ||
const auto idx = std::distance(newUserAllInQubits.begin(), found); | ||
rewriter.modifyOpInPlace( | ||
newUser, [&] { newUser->setOperand(i, opAllInQubits[idx]); }); | ||
} | ||
|
||
// Replace user with newUser | ||
rewriter.replaceOp(user, newUser); | ||
|
||
// Erase op | ||
rewriter.eraseOp(op); | ||
} | ||
|
||
void rewrite(UnitaryInterface op, | ||
mlir::PatternRewriter& rewriter) const override { | ||
auto const type = op->getName().stripDialect().str(); | ||
|
||
if (MERGEABLE_GATES.count(type) == 1) { | ||
rewriteAdditiveAngle(op, rewriter); | ||
} else { | ||
throw std::runtime_error("Unsupported operation type: " + type); | ||
} | ||
} | ||
}; | ||
|
||
/** | ||
* @brief Populates the given pattern set with the `MergeRotationGatesPattern`. | ||
* | ||
* @param patterns The pattern set to populate. | ||
*/ | ||
void populateMergeRotationGatesPatterns(mlir::RewritePatternSet& patterns) { | ||
patterns.add<MergeRotationGatesPattern>(patterns.getContext()); | ||
} | ||
|
||
} // namespace mqt::ir::opt |
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.