Skip to content

Add a Power block to yaoblocks - #582

Open
harry-phasecraft wants to merge 26 commits into
QuantumBFS:masterfrom
PhaseCraft:master
Open

harry-phasecraft wants to merge 26 commits into
QuantumBFS:masterfrom
PhaseCraft:master

Conversation

@harry-phasecraft

Copy link
Copy Markdown

Add a PowBlock. This is a block with a contents and a power that acts as $U^{pow}$ on the circuit.

This helps performance with large repetative circuits.

@jlbosse jlbosse left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks a lot for this!

I left some comments to make sure that edge cases work correctly for reverse mode AD and also to make the power constructor match the chain constructor as much as possible.

Comment thread lib/YaoBlocks/test/autodiff/mat_back.jl Resolved

function apply_back!(st, block::PowBlock{D, BT, PT}, collector) where {D, BT<:AbstractBlock, PT<:Integer}
blk = block.pow >= 0 ? content(block) : adjoint(content(block))
res = Any[]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Unlike ChainBlock we know what the content of PowBlock is. So can we maybe be more specific than Any here because we exactly know what will end up in res?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

We just discussed this and concluded that e.g. RepeatedBlock does the same Any, so this should be fine.

Comment thread lib/YaoBlocks/src/autodiff/mat_back.jl Resolved
Comment thread lib/YaoBlocks/test/composite/pow.jl Resolved
@jlbosse

jlbosse commented Apr 7, 2026

Copy link
Copy Markdown
Collaborator

@GiggleLiu or @Roger-luo:
Can we ask either of you to give this a review? From my side the following questions are still open:

  • Should this be named PowBlock or Power? None of the other algebraic blocks Add or Scale has Block in the name.
  • Which of unsafe_getindex or unsafe_getcol are we missing here? They are implemented for e.g. the Scale.
  • Should we keep the power constructor, or make ^ the one canonical constructor for this?

@codecov

codecov Bot commented Apr 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.37864% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.18%. Comparing base (8f17bfb) to head (a4195c8).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
lib/YaoPlots/src/vizcircuit.jl 72.50% 11 Missing ⚠️
lib/YaoBlocks/src/composite/power.jl 95.83% 1 Missing ⚠️
lib/YaoBlocks/src/layout.jl 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #582      +/-   ##
==========================================
- Coverage   89.22%   89.18%   -0.04%     
==========================================
  Files          89       90       +1     
  Lines        5855     5957     +102     
==========================================
+ Hits         5224     5313      +89     
- Misses        631      644      +13     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Roger-luo

Copy link
Copy Markdown
Member

Should we keep the power constructor, or make ^ the one canonical constructor for this?

I would be leaning to keep ^ as the only constructor given you can already use the struct constructor itself explicitly.

Should this be named PowBlock or Power? None of the other algebraic blocks Add or Scale has Block in the name.

Yes Power makes sense to me.

Which of unsafe_getindex or unsafe_getcol are we missing here? They are implemented for e.g. the Scale.

I believe this was something @GiggleLiu added for coefficient propagation? As long as the main gate tests pass I'm ok with having it, but in case you need it, unsafe_getindex is the one preferred

@harry-phasecraft harry-phasecraft changed the title Add a pow block to yaoblocks Add a Power block to yaoblocks Apr 16, 2026
@jlbosse

jlbosse commented Apr 16, 2026

Copy link
Copy Markdown
Collaborator

One more thing that seems to be missing is decomposition of this into native gates. If I do

    rules = [
        Yao.Optimise.merge_pauli,
        Yao.Optimise.merge_scale,
        Yao.Optimise.eliminate_nested,
        Yao.Optimise.raise_chain,
        Yao.Optimise.combine_similar,
        Yao.Optimise.to_basictypes
    ]
    simplified_circuit = Yao.Optimise.simplify(circuit, rules=rules)

with some circuit containing a Power I get some error about length being missing.

@jlbosse jlbosse left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Main comment is regarding eigenbasis which probably needs a small fix, otherwise this looks good now!

Comment thread lib/YaoBlocks/src/composite/power.jl Resolved
Comment thread lib/YaoBlocks/src/treeutils/optimise.jl Resolved
Comment on lines +58 to +66
function eigenbasis(op::Power)
b = op.pow >= 0 ? content(op) : adjoint(content(op))
E = chain(b.n)
blks = chain(b.n)
Ei, Vi = eigenbasis(b)
push!(E, fill(Ei, abs(op.pow))...)
push!(blks, fill(Vi, abs(op.pow))...)
return E, blks
end

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The eigenvectors of U^n are those of U and the eigenvalues of U^n are the eigenvalues of U raised to the n-th power. So I think this should simply be

function eigenbasis(op::Power) 
    E, V = eigenbasis(content(op))
    return E ^ op.pow, V
end

where you need to check the E ^ op.pow part again. Currently it might return a Power block again, but we probably want a matblock with the eigenvalues (to the pow-th power) on the diagonal.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is solved now.

Comment thread lib/YaoBlocks/src/composite/power.jl Outdated
Comment on lines +43 to +45
function nparameters(pb::Power)
return iszero(pb.pow) ? 0 : nparameters(pb.content)
end

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Here I am not sure of the iszero check is correct, or whether this should always just return nparameters(content(pb)). We'd have to check the parameter dispatching and reverse mode AD code then.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

For me the problem is that if pow is 0 then there are no parameters regardless of what the content is which means. Is this because it will mess with how you might think dispatch etc will work if this returns 0 ?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

We definitely want that dispatch!(circuit, rand(nparameters(circuit)) always works. And it seems to me this might be easier to achieve (that is: with fewer lines of code) if we always return nparameters(content(powblock)) here. This might also simplify the reverse mode AD logic, where we might be able to to avoid branching on pow == 0 and instead just end up with some empty for loops.

And conceptually I guess the thing is that block ^ 0 means "repeat block 0 times" and not "do nothing".

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I made the suggested changes now. Will need QuantumBFS/LuxurySparse.jl#82 though before it fully works.

Co-authored-by: Jan Lukas Bosse <janlukas.bosse@gmail.com>
@jlbosse

jlbosse commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator

@GiggleLiu or @Roger-luo I believe this is now ready for review from one of you. From my point of view it is all good to merge now.

@GiggleLiu

Copy link
Copy Markdown
Member

Thank @jlbosse and @harry-phasecraft , thank you for your contribution. The code quality looks good. I have a routine question: do you have a concrete application that requires this gate type?

Whenever we add a new composite block type, it complicates the design. So we expect the gain to be concrete enough. For example here, the autodiff behavior is different from traditional blocks, more chances to have bugs.

@GiggleLiu

Copy link
Copy Markdown
Member

I ran a focused review against a4195c8 and found four correctness issues that should be addressed before merge:

  1. Matrix reverse AD assumes unitary content. In lib/YaoBlocks/src/autodiff/mat_back.jl:107-120, the recurrence at line 117 cancels factors using unitarity, but positive powers permit non-unitary blocks. This reproduces with:

    test_mat_back(ComplexF64, Power(2.0 * Rx(0.3), 2), [2.0, 0.3]; δ=1e-6) # false

    The zero-power case is also incorrect: invertible content can produce nonzero gradients, while Power(0.0 * Rx(0.3), 0) throws SingularException in mat_back, even though the matrix is the constant identity. Please use the general derivative of U^n for positive non-unitary content and explicitly emit one zero per content parameter for n == 0.

  2. Power is missing the block indexing interface. There are no unsafe_getindex or unsafe_getcol methods, so both (X^2)[bit"0", bit"0"] and (X^2)[:, bit"0"] throw MethodError. Every other relevant composite block implements these operations.

  3. PropertyTrait(::Power) = PreserveAll() is incorrect for zero powers. For example, (2.0 * X)^0 has the identity matrix, but isunitary and isreflexive return false; (im * X)^0 is Hermitian, but ishermitian returns false. This also makes a subsequent negative power reject an actually unitary block. Zero needs a property special case, or Power needs an exact fallback rather than unconditional forwarding.

  4. The plotting implementation does not synchronize wire frontiers. Drawing Power(put(2, 1=>X), 5) leaves CircuitGrid.frontier == [1, 0]; a following gate on wire 2 is placed inside the power box. The box also uses the full address range rather than the content occupied locations. Please advance/barrier every wire spanned by the box after drawing the content and add a sparse-occupancy regression test.

Release metadata also looks inconsistent: this changes YaoBlocks and YaoPlots while their versions remain at 0.14.4 and 0.9.6, but the root Yao version is bumped to 0.9.4.

Stable CI passes. The YaoBlocks nightly failure is in unrelated ReflectGate tests. Codecov still reports 87.38% patch coverage with 13 changed lines uncovered.

@jlbosse

jlbosse commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

do you have a concrete application that requires this gate type?
Our main use case was (optimizing) trotter circuits and Quantum Phase estimation circuits. They naturally have a structure where one sub-circuit gets taken to some power. If we then want to further do some circuit rewriting on that sub-circuit, it is much cheaper to just rewrite the content of a Power block once, rather than doing it pow times within a long ChainBlock.

Regarding your review comments: Thanks for the thorough review, I hope they should all be addressed now.

Sorry for the delay on this...

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants