Skip to content

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

@aeddins-ibm

Description

@aeddins-ibm

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions