Skip to content

fix: Correct conjugate transpose in apply_unitary_density_bmm#316

Open
yurekami wants to merge 1 commit into
mit-han-lab:mainfrom
yurekami:fix/issue-254-density-matrix-bmm
Open

fix: Correct conjugate transpose in apply_unitary_density_bmm#316
yurekami wants to merge 1 commit into
mit-han-lab:mainfrom
yurekami:fix/issue-254-density-matrix-bmm

Conversation

@yurekami

Copy link
Copy Markdown

Summary

Fixes #254

This PR fixes a critical bug in the apply_unitary_density_bmm function where the density matrix evolution ρ → U ρ U† was computed incorrectly.

The Bug

The code was computing only the conjugate of the matrix instead of the conjugate transpose (Hermitian adjoint):

# Before (WRONG)
matdag = torch.conj(mat)  # Only conjugate, missing transpose

# After (CORRECT)
if len(mat.shape) > 2:
    matdag = torch.conj(mat.permute(0, 2, 1))  # Batched
else:
    matdag = torch.conj(mat.permute(1, 0))     # Single

For U† (Hermitian adjoint), we need both:

  • Element-wise complex conjugation (U*)
  • Matrix transposition (^T)

Example

As reported in the issue, applying Y gate to |00⟩⟨00| was giving wrong results:

  • Expected: diag(0, 1, 0, 0)
  • Got: Incorrect matrix

Files Changed

  • torchquantum/functional/gate_wrapper.py - line 301
  • torchquantum/density/density_func.py - line 210

Note

The einsum implementation (apply_unitary_density_einsum) was already correct. This fix aligns the bmm implementation with it.

🤖 Generated with Claude Code

Fixes mit-han-lab#254

The apply_unitary_density_bmm function was computing only the conjugate
of the matrix (U*) instead of the conjugate transpose (U†) when applying
ρ → U ρ U†.

For the Hermitian adjoint U†, we need both:
- Element-wise complex conjugation
- Matrix transposition

Before: matdag = torch.conj(mat)           # Only conjugate
After:  matdag = torch.conj(mat.permute(...))  # Conjugate + transpose

This fix corrects the density matrix evolution for all gates.

Files fixed:
- torchquantum/functional/gate_wrapper.py (line 301)
- torchquantum/density/density_func.py (line 210)

The einsum implementation was already correct; this aligns the bmm
implementation with it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
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.

Maybe there's a bug in 'apply_unitary_density_bmm' function?

1 participant