Add faster implementation of ptrace for kets#2657
Merged
Merged
Conversation
Ericgig
reviewed
Mar 21, 2025
Ericgig
left a comment
Member
There was a problem hiding this comment.
Thank you.
This look quite useful.
The function does not belong in tensor.py...
I know qobj.py is already too big, but it should probably come after the ptrace function already there for now. This would avoid adding a circular import.
Contributor
Author
|
Thanks for the comments. I moved the implementation to |
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Description
For my application,
Qobj.ptrace()was a bottleneck, so I added a specialization for kets that is significantly faster.The new implementation uses
np.einsumto combine the computation of the outer product and the partial trace into one operation, instead of doing these two operations sequentially.In this example, the new implementation is around 600x faster on my machine.
The new implementation can also handle significantly larger states:
rand_ket([2, 3, 4, 5]*3, distribution="fill").ptrace(keep_dims)fails using the old implementation because the intermediate density matrix is too large, but the new implementation computes the result in less than 0.1s.Note: I did not use
qutip.einsumbecause this only seems to wrap the string-indexed version ofnp.einsumand not the array-indexed version. The latter is more useful is cases like the present one, since its easier do generate the einsum subscripts programatically.