for...else / while...else bodies are silently discarded when the loop is unrolled
Maintainers usually reply within 1 day
Nobody has claimed this yet.
- #5175 by @udsy19 — closed without merging
Assessment
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Newbie friendliness
- 55/100
- Issue type
- Bug
- Clarity
- Clearly specified
- Activity status
- Quiet
- Domain
- compilers, testing-qa
Research direction
Start in cudaq/lib/Optimizer/Transforms/LoopUnrollPatterns.inc at UnrollCountedLoop::matchAndRewrite, then inspect cudaq/test/Transforms/loop.qke and the cc-loop-unroll pipeline. Add coverage that runs constant-bound for/else and while/else loops through unrolling, including a break case. Done means the else body executes only when the loop finishes without break, for both classical and quantum kernels.
Written by the indexing model from the issue text.
Description
Required prerequisites
- Consult the security policy. If reporting a security vulnerability, do not report the bug using this form. Use the process described in the policy to report the issue.
- Make sure you've read the documentation. Your issue may be addressed there.
- Search the issue tracker to verify that this hasn't already been reported. +1 or comment there if it has.
- If possible, make a PR with a failing test to give us a starting point to work on!
Describe the bug
Inside a @cudaq.kernel, a Python for … else or while … else loop whose trip count is a
compile-time constant silently loses its else body. No warning and no error is raised, and
for a quantum kernel the gates in the else clause simply disappear from the executed circuit.
The Python bridge emits the else region correctly, and the rest of the compiler handles it —
cc-loop-normalize preserves it, LowerToCFG and LowerUnwind lower it. The loss happens in the
loop unroller.
UnrollCountedLoop::matchAndRewrite in
cudaq/lib/Optimizer/Transforms/LoopUnrollPatterns.inc (from line 157) clones three of the
cc.loop op's four regions and then replaces the op:
rewriter.cloneRegionBefore(loop.getWhileRegion(), endBlock); // ~line 231
rewriter.cloneRegionBefore(bodyRegion, endBlock); // ~line 234
rewriter.cloneRegionBefore(loop.getStepRegion(), endBlock); // ~line 247
...
rewriter.replaceOp(loop, endBlock->getArguments()); // ~line 307
loop.getElseRegion() is never cloned or even inspected, so the region dies with the op. There is
no match for getElseRegion / hasPythonElse anywhere in LoopUnroll.cpp,
LoopUnrollPatterns.inc, LoopNormalize.cpp, LoopNormalizePatterns.inc, LoopPeeling.cpp, or
LoopAnalysis.cpp. The same pattern file is also included by the classical-optimization pass
(ClassicalOptimization.cpp:29).
for…else is a deliberately supported feature (added by #1573) and is documented in
cudaq/include/cudaq/Optimizer/Dialect/CC/CCOps.td (see the Python for else statement section
around line 215, and AnyRegion:$elseRegion at line 257).
Steps to reproduce the bug
A wrong quantum circuit:
import cudaq
@cudaq.kernel
def circ():
q = cudaq.qvector(2)
for i in range(2):
h(q[0])
else:
x(q[1]) # no break, so Python runs this -> q1 must be |1>
print(cudaq.sample(circ, shots_count=200))
Output on CUDA-Q 0.15.1 (macOS arm64, cuda_quantum_cu13 wheel):
{ 00:200 }
Expected { 01:200 }: h applied twice to q0 is the identity, and the else body flips q1.
print(circ) shows the bridge produced the else region correctly:
%2:2 = cc.loop while ((%arg0 = %c0_i64, %arg1 = %0) -> (i64, i64)) {
%3 = arith.cmpi slt, %arg0, %c2_i64 : i64
cc.condition %3(%arg0, %arg1 : i64, i64)
} do {
^bb0(%arg0: i64, %arg1: i64):
%3 = quake.extract_ref %1[0] : (!quake.veq<2>) -> !quake.ref
quake.h %3 : (!quake.ref) -> ()
cc.continue %arg0, %arg0 : i64, i64
} step {
^bb0(%arg0: i64, %arg1: i64):
%3 = arith.addi %arg0, %c1_i64 : i64
cc.continue %3, %arg1 : i64, i64
} else {
^bb0(%arg0: i64, %arg1: i64):
%3 = quake.extract_ref %1[1] : (!quake.veq<2>) -> !quake.ref
quake.x %3 : (!quake.ref) -> ()
cc.continue %arg0, %arg0 : i64, i64
}
The classical form makes the arithmetic obvious:
@cudaq.kernel
def k() -> int:
r = 0
for i in range(4):
r = r + 1
else:
r = r + 7
return r
Python gives 11; CUDA-Q gives 4. The while … else equivalent behaves identically
(11 vs 4).
Control that isolates it to unrolling. Making the trip count a runtime value so the loop
cannot be unrolled makes every case correct, including break correctly skipping the else:
dyn(0) cudaq= 7 python= 7 OK
dyn(1) cudaq= 8 python= 8 OK
dyn(4) cudaq= 11 python= 11 OK
dyn_break(0) cudaq= 7 python= 7 OK
dyn_break(2) cudaq= 9 python= 9 OK
dyn_break(5) cudaq= 102 python= 102 OK
and for the quantum kernel above with range(n) instead of range(2):
runtime bound, no break : { 01:200 } correct, else runs
runtime bound, break : { 00:200 } correct, else skipped
A constant-bound loop that does break also produces the right answer, but only by
coincidence: the else is supposed to be skipped in that case, and the compiler skips it
unconditionally. So the bug presents as "the else clause never executes".
Expected behavior
The else body should run when the loop terminates without a break, regardless of whether the
trip count is a compile-time constant.
Is this a regression? If it is, put the last known working version here.
Not a regression — the unroll pass has never handled the else region.
Environment
- CUDA-Q version: 0.15.1 (
cuda_quantum_cu13, commitaca5853a76d499ecc3d5f97c2e06163ae99d9c75); source read atmain228f099a0 - Python version: 3.13
- C++ compiler: n/a (wheel install)
- Operating system: macOS 26.5.1 arm64
Why this survived
The only in-tree coverage of the else region is cudaq/test/Transforms/loop.qke
(@python_for_else_loop at line 611, @python_while_else_loop at line 671), and that file's
RUN line is
// RUN: cudaq-opt %s | cudaq-opt | FileCheck %s
— a round-trip parse/print test only. The else region is never pushed through cc-loop-unroll.
Merged PR #3200 ("Fix a couple of bugs for python loops", commit 220e20873) is the closest prior
work: it lifted the verifier restriction that blocked while-else, fixed the pretty printer's
terminator printing, and added the missing unwind-lowering branch. Its three touched files were
lib/Optimizer/Dialect/CC/CCOps.cpp, lib/Optimizer/Transforms/LowerUnwind.cpp, and
test/Quake/loop.qke (now test/Transforms/loop.qke after the #4524 reorganization) — the
round-trip-only test file. The unroll pass was not part of that fix, which is how this gap
survived.
Suggested fix
Two options; I have opened a PR implementing the first and would happily switch to the second if
maintainers prefer.
(a) Conservative guard (what the PR does). Decline to unroll a loop that has a Python else
region, mirroring the existing loopOp.hasPythonElse() bail-out in
lib/Optimizer/Transforms/Mapping.cpp:2591:
if (loop.hasPythonElse()) {
if (signalFailure)
loop.emitOpError("python for/while-else loop cannot be unrolled");
return failure();
}
The loop stays rolled and LowerToCFG, which handles the else region correctly, takes over. The
runtime-bound control above is exactly this path, and it is correct in every case.
The tradeoff, stated plainly: this turns a silent wrong answer into a hard compile error for
pipelines that require complete unrolling. signalFailure defaults to false in the pass
(Passes.td:1021) and every in-tree createLoopUnroll call site
(Pipelines.cpp:68,168,211, py_alt_launch_kernel.cpp:1207, kernel_builder.cpp:1001) leaves it
at that default, so the simulator paths become correct rather than erroring. But the
unrolling-pipeline cudaq-opt pipeline defaults signal-failure-if-any-loop-cannot-be-completely-unrolled
to true, and targets that genuinely need a fully expanded circuit (QIR base profile, hardware)
will now hit an error downstream. I think an error beats a wrong quantum circuit, but it is a
behaviour change on those targets and a maintainer should decide.
(b) Complete fix (no tradeoff). Clone the else region into the fall-through after the last
unrolled iteration, so the loop still unrolls and the else body runs. The existing structure is
already favourable:
breakops in the body are rewritten to branch directly toendBlock
(LoopUnrollPatterns.inc:264), so they would naturally bypass an else region placed on the
fall-through edge — which is exactly Python's semantics.- At the end of the unroll loop,
insBlockis the last continue block and sits immediately before
endBlock, sorewriter.cloneRegionBefore(loop.getElseRegion(), endBlock)puts the clone's
entry block atinsBlock->getNextNode()in both theunrollBy > 0andunrollBy == 0cases. - The cloned else region's
cc.continueterminators would be replaced with branches to
endBlock, mirroring whatLowerToCFG.cppalready does for the else region
(updateBodyBranches(&loopOp.getElseRegion(), rewriter, endBlock, nullptr)).
So the change would be to replace the final
cf::BranchOp::create(rewriter, loc, endBlock, iterationOpers) with a branch to the cloned else
entry block, plus the terminator rewrite. I did not implement this in the PR because I have no
LLVM/MLIR build available and did not want to ship an untested rewriter change; the one point I
could not settle by reading is how an unresolved cc.unwind_* op inside the else region should
behave once it is cloned out of the loop.
- Dominant language
- C++
- Stars
- 1.2k
- Forks
- 508
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 100
Getting set up
Starts the project's dev container in your browser, under your own GitHub account.
- No Dockerfile or Docker Compose file
- No pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from NVIDIA/cuda-quantum
-
Difficulty 1/5 Under an hour Newbie friendliness 88/100
NVIDIA/cuda-quantum#6035 ·
Maintainers usually reply within 1 day
-
Difficulty 1/5 1-3 hours Newbie friendliness 77/100
NVIDIA/cuda-quantum#6034 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
NVIDIA/cuda-quantum#6033 ·
Maintainers usually reply within 1 day
-
Point the CUDA-Q Pulse research preview docs to the released cudaq-pulse packagePossibly taken @fedonman claimed this 2 days ago. Open
Difficulty 1/5 1-3 hours Newbie friendliness 88/100
NVIDIA/cuda-quantum#6031 ·
Maintainers usually reply within 1 day
-
Realtime fnv1a_hash sign-extends char, so a non-ASCII handler name gets a platform-dependent function idPossibly taken @fedonman claimed this 2 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 77/100
NVIDIA/cuda-quantum#6029 ·
Maintainers usually reply within 1 day
All issues in NVIDIA/cuda-quantum
Similar issues
-
Difficulty 1/5 Under an hour Newbie friendliness 90/100
Maintainers usually reply within 2 days
-
bug data-types
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
ClickHouse/clickhouse-cpp#645 ·
Maintainers usually reply within 1 day
-
bug compatibility difficulty:easy prio:normal
Difficulty 2/5 1-3 hours Newbie friendliness 74/100
NatronGitHub/openfx-misc#524 ·
Maintainers usually reply within 1 day
-
documentation enhancement help wanted P0
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
Awesome-Embedded-Learning-Studio/Tutorial_AwesomeModernCPP#359 ·
Maintainers usually reply within 1 day
-
Type: Bug
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
openscad/openscad#7360 · 2 comments ·
Maintainers usually reply within 1 day