Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

avoid typechecking coefficients individually in SparsePauliOp.init() #11187

Closed
aeddins-ibm opened this issue Nov 3, 2023 · 1 comment · Fixed by #11133
Closed

avoid typechecking coefficients individually in SparsePauliOp.init() #11187

aeddins-ibm opened this issue Nov 3, 2023 · 1 comment · Fixed by #11133
Labels
type: feature request New feature or request

Comments

@aeddins-ibm
Copy link
Contributor

What should we add?

I'm not certain but for large SparsePauliOp objects, it seems like the type-checking is a bottleneck for initializing the object (which also happens inside various SPO methods such as compose()):

if isinstance(coeffs, np.ndarray) and coeffs.dtype == object:
dtype = object
elif coeffs is not None:
if not isinstance(coeffs, (np.ndarray, Sequence)):
coeffs = [coeffs]
if any(isinstance(coeff, ParameterExpression) for coeff in coeffs):
dtype = object
else:
dtype = complex

In the most common case, we can avoid calling isinstance thousands of times by changing the logic to:

        if isinstance(coeffs, np.ndarray):
            if coeffs.dtype == object:
                dtype = object
            else:
                dtype = complex
        elif coeffs is not None:
            if not isinstance(coeffs, (np.ndarray, Sequence)):
                coeffs = [coeffs]
            if any(isinstance(coeff, ParameterExpression) for coeff in coeffs):
                dtype = object
            else:
                dtype = complex

Very crude timing test (seconds indicated at lower left); may want to confirm benchmark before committing. I repeated with seed=2 (not shown).
image

@aeddins-ibm aeddins-ibm added the type: feature request New feature or request label Nov 3, 2023
@jakelishman
Copy link
Member

Coincidentally, I'd also spotted this recently and there's fix in #11133.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: feature request New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants