Skip to content

✨ Enhance Matrix functionality with new methods and optimizations#1802

Merged
burgholzer merged 11 commits into
mainfrom
matrix-utilities
Jun 22, 2026
Merged

✨ Enhance Matrix functionality with new methods and optimizations#1802
burgholzer merged 11 commits into
mainfrom
matrix-utilities

Conversation

@simon1hofmann

@simon1hofmann simon1hofmann commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

Description

Extends mlir::qco matrix utilities with fixed-size helpers, n-qubit embedding/reordering, and a real symmetric 4×4 eigensolver. These are building blocks for native two-qubit gate synthesis (Weyl decomposition and related passes).

New APIs

  • symmetricEigen4 — eigendecomposition of a real symmetric 4×4 matrix via EISPACK tred2/tql2 (adapted from John Burkardt’s MIT-licensed C port); includes a Matrix4x4 overload that uses realPart()
  • kron — Kronecker product for single-qubit factors (MSB-first wire order)
  • reorderTwoQubitMatrix — conjugate a 4×4 gate to act on wires {0,1}
  • embedSingleQubitInNqubit / embedTwoQubitInNqubit — embed fixed gates into larger Hilbert spaces

Matrix4x4 / DynamicMatrix improvements

  • transpose, diagonal, fromDiagonal, column, setColumn, realPart, imagPart, isIdentity
  • DynamicMatrix::operator*= and scalar operator* overloads for 2×2 / 4×4 / dynamic matrices
  • Fast paths for 2×2 and 4×4 DynamicMatrix multiply; single-pass isIdentity
  • Shared internal helpers (multiply2x2/multiply4x4, isIdentityEntries)

AI Assistance

Used Composer 2.5 via Cursor for parts of this change. I reviewed the full
diff and take responsibility for everything in this PR.

Checklist

  • The pull request only contains commits that are focused and relevant to this change.
  • I have added appropriate tests that cover the new/changed functionality.
  • I have updated the documentation to reflect these changes.
  • I have added entries to the changelog for any noteworthy additions, changes, fixes, or removals.
  • I have added migration instructions to the upgrade guide (if needed).
  • The changes follow the project's style guidelines and introduce no new warnings.
  • The changes are fully tested and pass the CI checks.
  • I have reviewed my own code changes.

If PR contains AI-assisted content:

  • I have disclosed the use of AI tools in the PR description as per our AI Usage Guidelines.
  • AI-assisted commits include an Assisted-by: [Model Name] via [Tool Name] footer.
  • I confirm that I have personally reviewed and understood all AI-generated content, and accept full responsibility for it.

@codecov

codecov Bot commented Jun 22, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.13545% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
mlir/lib/Dialect/QCO/Utils/Matrix.cpp 99.1% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@burgholzer burgholzer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Had some time, so I thought I'd give this a first review already 😌

Comment thread mlir/include/mlir/Dialect/QCO/Utils/Matrix.h
Comment thread mlir/include/mlir/Dialect/QCO/Utils/Matrix.h Outdated
Comment thread mlir/include/mlir/Dialect/QCO/Utils/Matrix.h Outdated
Comment thread mlir/include/mlir/Dialect/QCO/Utils/Matrix.h
Comment thread mlir/include/mlir/Dialect/QCO/Utils/Matrix.h Outdated
Comment thread mlir/include/mlir/Dialect/QCO/Utils/Matrix.h Outdated
Comment thread mlir/include/mlir/Dialect/QCO/Utils/Matrix.h Outdated
Comment thread mlir/lib/Dialect/QCO/Utils/Matrix.cpp Outdated
Comment thread mlir/lib/Dialect/QCO/Utils/Matrix.cpp Outdated
@simon1hofmann simon1hofmann marked this pull request as ready for review June 22, 2026 11:46
@simon1hofmann

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: c127182e-49b3-4509-b494-605de637fa80

📥 Commits

Reviewing files that changed from the base of the PR and between 01cfccb and 3f38d9c.

📒 Files selected for processing (2)
  • mlir/include/mlir/Dialect/QCO/Utils/Matrix.h
  • mlir/lib/Dialect/QCO/Utils/Matrix.cpp

📝 Walkthrough

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced matrix utility operations for QCO MLIR dialect, including transpose and identity checking
    • Added symmetric eigenvalue decomposition capabilities
    • Improved quantum gate embedding and multi-qubit reordering functionality
    • Introduced Kronecker product support for quantum circuit operations
  • Tests

    • Expanded test coverage for matrix operations and eigensolvers

Walkthrough

Expands the QCO MLIR matrix utilities in Matrix.h and Matrix.cpp by adding transpose, identity, diagonal, row/column, Kronecker product, qubit embedding and reordering, scalar multiplication, trace, and a symmetric 4x4 eigenvalue decomposition to Matrix2x2, Matrix4x4, and DynamicMatrix. Introduces the SymmetricEigen4 struct and internal bit-index helpers. Extends unit tests to cover all new APIs.

Changes

QCO Matrix Utility Expansion

Layer / File(s) Summary
Public API contracts: new methods, SymmetricEigen4, and scalar overloads
mlir/include/mlir/Dialect/QCO/Utils/Matrix.h
Declares all new methods on Matrix2x2, Matrix4x4, and DynamicMatrix; introduces forward declarations and the SymmetricEigen4 struct; adds scalar-on-left multiplication free functions; and adds required header includes.
Internal approximation helpers and multiply signature refactor
mlir/lib/Dialect/QCO/Utils/Matrix.cpp
Introduces entryIsApprox, rewrites entriesAreApprox and isIdentityEntries to use it, refactors multiply2x2/multiply4x4 to accept ArrayRef/MutableArrayRef, adds qubitBitAt and otherQubitBitsMatch bit-index helpers, adds checkedHilbertDim, and updates Matrix1x1::isApprox.
Matrix2x2 new method implementations and embedding refactor
mlir/lib/Dialect/QCO/Utils/Matrix.cpp
Implements Matrix2x2::transpose, isIdentity, and refactors embedInNqubit/embedInTwoQubit to use the new bit-index helpers.
Matrix4x4 new method implementations and symmetric eigensolver
mlir/lib/Dialect/QCO/Utils/Matrix.cpp
Implements Matrix4x4::transpose, isIdentity, diagonal, fromDiagonal, kron, row/column accessors and setters, realPart/imagPart, embedInNqubit, reorderForQubits, and the full symmetric eigensolver (symmetricTred24, symmetricTql24, symmetricEigen4) with fatal error on non-convergence.
DynamicMatrix new method implementations
mlir/lib/Dialect/QCO/Utils/Matrix.cpp
Implements DynamicMatrix::trace, operator*(DynamicMatrix) with 2x2/4x4 specializations and generic fallback, scalar operator* and operator*=, isIdentity, and updates isApprox(Matrix1x1).
Unit test extensions and new test cases
mlir/unittests/Dialect/QCO/Utils/test_unitary_matrix.cpp
Adds includes for new test facilities; extends existing tests with swap determinant, isIdentity, and scalar multiply-assign; relocates IsApproxOverloads; and adds comprehensive tests for all new APIs including transpose, diagonal, row/column, kron, reorder, embedding, multiplication, scalar left-multiply, and symmetric eigensolver scenarios.
CHANGELOG update
CHANGELOG.md
Extends the unreleased Added entry's citation list and inserts the PR link definition for #1802.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant Matrix4x4
  participant symmetricTred24
  participant symmetricTql24
  Caller->>Matrix4x4: symmetricEigen4()
  Matrix4x4->>symmetricTred24: tridiagonalize real symmetric 4x4 input
  symmetricTred24-->>Matrix4x4: tridiagonal form + orthogonal accumulator Q
  Matrix4x4->>symmetricTql24: QL iteration on tridiagonal
  symmetricTql24-->>Matrix4x4: converged eigenvalues and eigenvectors
  Matrix4x4-->>Caller: SymmetricEigen4 {eigenvalues[4], eigenvectors Matrix4x4}
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

enhancement, c++, MLIR

Suggested reviewers

  • burgholzer
  • denialhaag

Poem

🐇 Hop hop through matrices, eigenvalues align,
Kronecker products bloom, each qubit in line.
The 4x4 symmetric spins and converges true,
Transpose and embed—the rabbit sees it through!
From scalar left-mult to isIdentity glee,
The QCO matrix grows, wild and free! 🎉

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.40% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Enhance Matrix functionality with new methods and optimizations' is generic and vague, using non-descriptive terms ('Enhance', 'functionality') that don't convey the specific nature of the substantial changes (eigensolver, Kronecker product, embedding, symmetric matrix operations). Use a more specific title such as 'Add matrix eigendecomposition, Kronecker product, and n-qubit embedding utilities' to clearly convey the main additions to the codebase.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The PR description is comprehensive and well-structured, covering new APIs, improvements to Matrix4x4/DynamicMatrix, and the AI assistance disclosure with appropriate checklist items marked. All key sections from the template are addressed with substantive detail.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch matrix-utilities

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@mlir/include/mlir/Dialect/QCO/Utils/Matrix.h`:
- Around line 791-794: Add member documentation to the SymmetricEigen4 struct
for consistency with other structs in the file. Add a brief /// comment above
the eigenvalues member that describes what it contains (the eigenvalues of the
matrix), and add a /// comment above the eigenvectors member that describes what
it contains (the corresponding eigenvectors as a Matrix4x4). Follow the same
documentation style used in other struct members throughout the file.

In `@mlir/lib/Dialect/QCO/Utils/Matrix.cpp`:
- Around line 458-470: The column() and setColumn() methods in Matrix4x4 lack
bounds validation on the col parameter, unlike the row APIs, allowing invalid
column indices to cause out-of-bounds access. Add assert statements in both
column() and setColumn() to verify that col is less than K_COLS before
performing any array indexing operations.
- Line 326: The bit shift operation `1ULL << numQubits` at line 326 and another
occurrence at line 518 lack validation for the numQubits parameter, which can
cause undefined behavior when numQubits is 64 or greater and signed integer
overflow when numQubits is 63 or greater. Create a checked helper function that
validates numQubits is within a safe range (less than 63 to prevent both shift
overflow and signed integer overflow) before performing the bit shift, then
replace both instances of the unsafe `1ULL << numQubits` expression with calls
to this helper function to guard against overflow.
- Around line 350-351: The functions Matrix2x2::embedInTwoQubit and
Matrix4x4::reorderForQubits return Matrix4x4 but end with assert(false && ...)
statements. In NDEBUG builds, these assertions are removed, causing the
functions to fall through without returning a value, resulting in undefined
behavior. Replace the assert(false && "Invalid qubit index for single-qubit
embed") call with llvm::reportFatalInternalError() passing the error message,
which will properly terminate execution in both debug and release builds.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7dba2258-18ab-43b4-b8b2-19b7ae967b83

📥 Commits

Reviewing files that changed from the base of the PR and between 43709be and 01cfccb.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • mlir/include/mlir/Dialect/QCO/Utils/Matrix.h
  • mlir/lib/Dialect/QCO/Utils/Matrix.cpp
  • mlir/unittests/Dialect/QCO/Utils/test_unitary_matrix.cpp

Comment thread mlir/include/mlir/Dialect/QCO/Utils/Matrix.h
Comment thread mlir/lib/Dialect/QCO/Utils/Matrix.cpp Outdated
Comment thread mlir/lib/Dialect/QCO/Utils/Matrix.cpp Outdated
Comment thread mlir/lib/Dialect/QCO/Utils/Matrix.cpp Outdated
@simon1hofmann

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@simon1hofmann

simon1hofmann commented Jun 22, 2026

Copy link
Copy Markdown
Contributor Author

Had some time, so I thought I'd give this a first review already 😌

Thanks a lot for the quick review 🙏
I went through your comments and also applied CodeRabbit's suggestions.
Would be ready for another review now :)

@simon1hofmann simon1hofmann requested a review from burgholzer June 22, 2026 12:20

@burgholzer burgholzer left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM. Just two minor comments/suggestions left. Feel free to address and resolve these and merge this afterwards.

One overall comment on the whole PR iteration process: it would be good if you wouldn't resolve review comments that you replied to as part of incorporating feedback. People using the GitHub App/Notifications (like me) do not see these comments without going through all resolved comments, opening them up, and checking whether there have been any replies. Most of the time, it is best for the person who wrote the last comment in a discussion thread to leave it to someone else to actually resolve the conversation. Makes the whole process a little smoother. When I get a request for a re-review, I will typically first go through all open conversations of the previous review before going through the actual code.
I assume you are resolving the comments to indicate that you have addressed the comments and to keep a clean slate. Hopefully the above is only a slight adaptation to your workflow.
Let me know if any of that does not make sense.

Comment thread mlir/lib/Dialect/QCO/Utils/Matrix.cpp Outdated
Comment thread mlir/lib/Dialect/QCO/Utils/Matrix.cpp Outdated
simon1hofmann and others added 3 commits June 22, 2026 15:18
Co-authored-by: Lukas Burgholzer <burgholzer@me.com>
Signed-off-by: simon1hofmann <119581649+simon1hofmann@users.noreply.github.com>
@simon1hofmann

Copy link
Copy Markdown
Contributor Author

LGTM. Just two minor comments/suggestions left. Feel free to address and resolve these and merge this afterwards.

One overall comment on the whole PR iteration process: it would be good if you wouldn't resolve review comments that you replied to as part of incorporating feedback. People using the GitHub App/Notifications (like me) do not see these comments without going through all resolved comments, opening them up, and checking whether there have been any replies. Most of the time, it is best for the person who wrote the last comment in a discussion thread to leave it to someone else to actually resolve the conversation. Makes the whole process a little smoother. When I get a request for a re-review, I will typically first go through all open conversations of the previous review before going through the actual code. I assume you are resolving the comments to indicate that you have addressed the comments and to keep a clean slate. Hopefully the above is only a slight adaptation to your workflow. Let me know if any of that does not make sense.

I usually resolve comments where I do no think a re-review is necessary, but makes total sense to let the other person resolve that comment. Will keep that in mind in the following PR's!

I addressed the remaining comments, should be good to go in after all tests are green.

@burgholzer burgholzer merged commit 6e15803 into main Jun 22, 2026
29 checks passed
@burgholzer burgholzer deleted the matrix-utilities branch June 22, 2026 14:00
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.

2 participants