-
Notifications
You must be signed in to change notification settings - Fork 447
Add broadcast operation transformation passes #5207
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
Open
atgeller
wants to merge
2
commits into
NVIDIA:main
Choose a base branch
from
atgeller:broadcast-passes
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.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
132 changes: 132 additions & 0 deletions
132
cudaq/lib/Optimizer/Transforms/ConsolidateBroadcasts.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,132 @@ | ||
| /******************************************************************************* | ||
| * Copyright (c) 2022 - 2026 NVIDIA Corporation & Affiliates. * | ||
| * All rights reserved. * | ||
| * * | ||
| * This source code and the accompanying materials are made available under * | ||
| * the terms of the Apache License 2.0 which accompanies this distribution. * | ||
| ******************************************************************************/ | ||
|
|
||
| #include "LoopAnalysis.h" | ||
| #include "PassDetails.h" | ||
| #include "QuakeOperatorUtilities.h" | ||
| #include "cudaq/Optimizer/Transforms/Passes.h" | ||
| #include "mlir/Interfaces/SideEffectInterfaces.h" | ||
|
|
||
| namespace cudaq::opt { | ||
| #define GEN_PASS_DEF_CONSOLIDATEBROADCASTS | ||
| #include "cudaq/Optimizer/Transforms/Passes.h.inc" | ||
| } // namespace cudaq::opt | ||
|
|
||
| #define DEBUG_TYPE "consolidate-broadcasts" | ||
|
|
||
| using namespace mlir; | ||
|
|
||
| namespace { | ||
|
|
||
| /// Does \p region hold nothing but the loop's own control: no side effects, | ||
| /// and no way out of the loop? | ||
| bool isControlOnly(Region ®ion) { | ||
| return !region | ||
| .walk([](Operation *op) { | ||
| if (!isMemoryEffectFree(op) || | ||
| isa<cudaq::cc::BreakOp, cudaq::cc::UnwindBreakOp>(op)) | ||
| return WalkResult::interrupt(); | ||
| return WalkResult::advance(); | ||
| }) | ||
| .wasInterrupted(); | ||
| } | ||
|
|
||
| /// Match `for (i = 0; i < N; ++i) { op(v[i]); ... }`, where `v` is a veq of | ||
| /// size `N`, and replace the entire loop with `op(v); ...`. | ||
| LogicalResult rollLoop(cudaq::cc::LoopOp loop) { | ||
| // A counted loop runs a constant number of iterations from 0, stepping by 1, | ||
| // with no early exit and no `do while` form. It must also leave nothing | ||
| // behind. | ||
| if (!cudaq::opt::isaCountedLoop(loop) || | ||
| !llvm::all_of(loop->getResults(), [](Value v) { return v.use_empty(); })) | ||
| return failure(); | ||
| auto components = cudaq::opt::getLoopComponents(loop); | ||
| assert(components && "counted loop must have components"); | ||
| auto iterations = components->getIterationsConstant(); | ||
| if (!iterations) | ||
| return failure(); | ||
|
|
||
| // An `else` region must not be dropped, and the while and step regions, | ||
| // which the rewrite also drops, must hold nothing but the loop's control. | ||
| if (loop.hasPythonElse() || !isControlOnly(loop.getWhileRegion()) || | ||
| !isControlOnly(loop.getStepRegion())) | ||
| return failure(); | ||
|
|
||
| Region &body = loop.getBodyRegion(); | ||
| if (!body.hasOneBlock()) | ||
| return failure(); | ||
| Block &block = body.front(); | ||
| // Only one argument, the induction variable | ||
| if (block.getNumArguments() != 1) | ||
| return failure(); | ||
|
|
||
| // In the loop body, we're matching on the form | ||
| // %var = quake.extract_ref [%induction_var] %veq | ||
| // quake.op %var | ||
| // ... | ||
| // cc.continue | ||
| // Where each op is a broadcast operator | ||
| auto extract = dyn_cast<cudaq::quake::ExtractRefOp>(block.front()); | ||
| if (!extract || extract.getIndex() != block.getArgument(0)) | ||
| return failure(); | ||
|
|
||
| auto isBroadcastable = [&extract](Operation &op) { | ||
| auto gate = dyn_cast<cudaq::quake::OperatorInterface>(op); | ||
| if (!gate) | ||
| return false; | ||
| if (!cudaq::opt::isBroadcastOperator(gate)) | ||
| return false; | ||
| if (!gate.getControls().empty() || gate.getTargets().size() != 1 || | ||
| gate.getTargets()[0] != extract.getRef()) | ||
| return false; | ||
|
|
||
| return true; | ||
| }; | ||
|
|
||
| SmallVector<cudaq::quake::OperatorInterface> broadcastable; | ||
|
|
||
| for (Operation &op : block.without_terminator()) { | ||
| if (extract == &op) | ||
| continue; | ||
| if (!isBroadcastable(op)) | ||
| return failure(); | ||
| broadcastable.emplace_back(&op); | ||
| } | ||
| if (broadcastable.empty()) | ||
| return failure(); | ||
|
|
||
| // The loop must walk the whole vector. | ||
| Value veq = extract.getVeq(); | ||
| if (cudaq::quake::getVeqSize(veq) != iterations) | ||
| return failure(); | ||
|
|
||
| // Given the body above, the operators' parameters are all defined outside | ||
| // the loop, so the clones are well-formed there. The sole target is the last | ||
| // operand. | ||
| OpBuilder builder(loop); | ||
| for (auto gate : broadcastable) { | ||
| Operation *broadcast = builder.clone(*gate.getOperation()); | ||
| broadcast->setOperand(broadcast->getNumOperands() - 1, veq); | ||
| } | ||
| loop.erase(); | ||
| return success(); | ||
| } | ||
|
|
||
| struct ConsolidateBroadcastsPass | ||
| : public cudaq::opt::impl::ConsolidateBroadcastsBase< | ||
| ConsolidateBroadcastsPass> { | ||
| using ConsolidateBroadcastsBase::ConsolidateBroadcastsBase; | ||
|
|
||
| void runOnOperation() override { | ||
| SmallVector<cudaq::cc::LoopOp> loops; | ||
| getOperation().walk([&](cudaq::cc::LoopOp loop) { loops.push_back(loop); }); | ||
| for (auto loop : loops) | ||
| (void)rollLoop(loop); | ||
| } | ||
| }; | ||
| } // namespace | ||
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,78 @@ | ||
| /******************************************************************************* | ||
| * Copyright (c) 2022 - 2026 NVIDIA Corporation & Affiliates. * | ||
| * All rights reserved. * | ||
| * * | ||
| * This source code and the accompanying materials are made available under * | ||
| * the terms of the Apache License 2.0 which accompanies this distribution. * | ||
| ******************************************************************************/ | ||
|
|
||
| #include "PassDetails.h" | ||
| #include "cudaq/Optimizer/Transforms/Passes.h" | ||
| #include "mlir/IR/PatternMatch.h" | ||
| #include "mlir/Transforms/GreedyPatternRewriteDriver.h" | ||
|
|
||
| namespace cudaq::opt { | ||
| #define GEN_PASS_DEF_EXPANDBROADCASTS | ||
| #include "cudaq/Optimizer/Transforms/Passes.h.inc" | ||
| } // namespace cudaq::opt | ||
|
|
||
| #define DEBUG_TYPE "expand-broadcasts" | ||
|
|
||
| using namespace mlir; | ||
|
|
||
| namespace { | ||
| /// Replace a single-qubit operator whose target is a constant sized veq of | ||
| /// size \e N with \e N copies of that operator, one per element of the veq. | ||
| /// The controls, parameters, and attributes of the original operator are | ||
| /// replicated verbatim on each copy. | ||
| template <typename OP> | ||
| class ExpandBroadcastPat : public OpRewritePattern<OP> { | ||
| public: | ||
| using OpRewritePattern<OP>::OpRewritePattern; | ||
|
|
||
| LogicalResult matchAndRewrite(OP op, | ||
| PatternRewriter &rewriter) const override { | ||
| // Only an uncontrolled operator broadcasts | ||
| if (op.getTargets().size() != 1 || !op.getControls().empty()) | ||
| return failure(); | ||
| Value target = op.getTargets()[0]; | ||
| if (!isa<cudaq::quake::VeqType>(target.getType())) | ||
| return failure(); | ||
| auto size = cudaq::quake::getVeqSize(target); | ||
| if (!size) | ||
| return failure(); | ||
|
|
||
| auto loc = op.getLoc(); | ||
| // The sole target is the last operand (skip angles for rotations) | ||
| unsigned targetPos = op->getNumOperands() - 1; | ||
| for (std::size_t i = 0; i < *size; ++i) { | ||
| Value ref = cudaq::quake::ExtractRefOp::create(rewriter, loc, target, i); | ||
| Operation *clone = rewriter.clone(*op.getOperation()); | ||
| clone->setOperand(targetPos, ref); | ||
| } | ||
| rewriter.eraseOp(op); | ||
| return success(); | ||
| } | ||
| }; | ||
|
|
||
| struct ExpandBroadcastsPass | ||
| : public cudaq::opt::impl::ExpandBroadcastsBase<ExpandBroadcastsPass> { | ||
| using ExpandBroadcastsBase::ExpandBroadcastsBase; | ||
|
|
||
| void runOnOperation() override { | ||
| auto *ctx = &getContext(); | ||
| RewritePatternSet patterns(ctx); | ||
| patterns.insert< | ||
| ExpandBroadcastPat<cudaq::quake::HOp>, | ||
| ExpandBroadcastPat<cudaq::quake::PhasedRxOp>, | ||
| ExpandBroadcastPat<cudaq::quake::R1Op>, ExpandBroadcastPat<cudaq::quake::RxOp>, | ||
| ExpandBroadcastPat<cudaq::quake::RyOp>, ExpandBroadcastPat<cudaq::quake::RzOp>, | ||
| ExpandBroadcastPat<cudaq::quake::SOp>, ExpandBroadcastPat<cudaq::quake::TOp>, | ||
| ExpandBroadcastPat<cudaq::quake::U2Op>, ExpandBroadcastPat<cudaq::quake::U3Op>, | ||
| ExpandBroadcastPat<cudaq::quake::XOp>, ExpandBroadcastPat<cudaq::quake::YOp>, | ||
| ExpandBroadcastPat<cudaq::quake::ZOp>>(ctx); | ||
| if (failed(applyPatternsGreedily(getOperation(), std::move(patterns)))) | ||
| signalPassFailure(); | ||
| } | ||
| }; | ||
| } // namespace |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems like any sort of Unwind*Op ought to trigger this. (Although an UnwindContinueOp would be odd indeed here.)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is it possible to see a non "Unwind" return here in the IR?