Avoid deepcopy in SymbolicOperator arithmetic#1415
Conversation
__add__, __sub__, __mul__ and accumulate copied the operand with copy.deepcopy before mutating it in place. Term keys are tuples of tuples and coefficients are numbers or sympy expressions, all immutable, so copying the terms dictionary is enough to keep the result independent of the operand. Add a small _clone helper that does this and use it in place of deepcopy.
There was a problem hiding this comment.
Code Review
This pull request replaces expensive copy.deepcopy calls with a custom _clone method in SymbolicOperator to improve performance. The review feedback points out that in the accumulate method, cloning cls.zero() when start is None is redundant and suggests an optimized ternary expression instead.
| def accumulate(cls, operators, start=None): | ||
| """Sums over SymbolicOperators.""" | ||
| total = copy.deepcopy(start or cls.zero()) | ||
| total = (start or cls.zero())._clone() |
There was a problem hiding this comment.
When start is None, start or cls.zero() evaluates to cls.zero(), which is a newly created empty operator. Calling _clone() on it is redundant and adds unnecessary overhead. Using an explicit is not None check avoids this redundant clone and is also safer if start is an empty operator that might evaluate to falsy.
| total = (start or cls.zero())._clone() | |
| total = start._clone() if start is not None else cls.zero() |
There was a problem hiding this comment.
Done. The falsy case can't actually come up since SymbolicOperator doesn't define __bool__ or __len__, but the explicit check reads better anyway.
This is the patch offered in #1407.
SymbolicOperator.__add__,__sub__,__mul__andaccumulateeach start bycopying the operand with
copy.deepcopyand then mutate the copy in place withthe matching
__iadd__/__isub__/__imul__. deepcopy walks the wholetermsdictionary and recursively copies every key and every value.None of that recursion buys anything here. A term key is a tuple of
(index, action)tuples, and a coefficient is an int, float, complex or sympyexpression. All of those are immutable, so the copy only needs to be independent
at the dictionary level: the in-place operators rebind
self.terms[term]and addor remove keys, they never mutate a key or a coefficient object in place. A plain
dict(self.terms)is therefore enough to make a result that is safe to mutatewithout touching the original.
This adds a small
_clonehelper that builds an empty instance and copies theterms dictionary into it, and uses it in the four spots that called deepcopy. For
operators with many terms it's a good deal cheaper than the deep copy, and the
out-of-place guarantee (
a + bleaves bothaandbunchanged) is the same asbefore.
Tests
The existing
symbolic_operator_test.pyalready covers this: the add, subtract,multiply and divide tests each assert the operation is done out of place, and
qubit_operator_test.pyexercisesaccumulate. I checked that every changed lineis hit by the current suite, and
ops/operators/,utils/andtransforms/opconversions/pass. black and mypy are clean on the file.Benchmarks
Random QubitOperators over 30 qubits, both operands the same size:
Measured on my laptop (Intel Core Ultra 5 225, Windows, Python 3.12, numpy 2.5).
Times are medians over 25 repetitions after a warmup. I ran the whole
base/patch comparison twice in alternation with fixed seeds and the speedups
agreed within about 10 percent, so the table pools both rounds.