Skip to content

Commit a37facd

Browse files
authored
Fix memory leak in custatevec (#146)
1 parent a36f488 commit a37facd

1 file changed

Lines changed: 10 additions & 3 deletions

File tree

  • python/quantum-pecos/src/pecos/simulators/custatevec

python/quantum-pecos/src/pecos/simulators/custatevec/state.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ def __init__(self, num_qubits: int, seed: int | None = None) -> None:
4343
num_qubits (int): Number of qubits being represented.
4444
seed (int): Seed for randomness.
4545
"""
46+
self.libhandle = None
4647
if not isinstance(num_qubits, int):
4748
msg = "``num_qubits`` should be of type ``int``."
4849
raise TypeError(msg)
@@ -59,6 +60,7 @@ def __init__(self, num_qubits: int, seed: int | None = None) -> None:
5960
self.compute_type = ComputeType.COMPUTE_64F
6061

6162
# Allocate the statevector in GPU and initialize it to |0>
63+
self.cupy_vector = None
6264
self.reset()
6365

6466
####################################################
@@ -106,15 +108,20 @@ def free(ptr: int, _size: int, stream: Any) -> None: # noqa: ANN401
106108
def reset(self) -> Self:
107109
"""Reset the quantum state for another run without reinitializing."""
108110
# Initialize all qubits in the zero state
109-
self.cupy_vector = cp.zeros(shape=2**self.num_qubits, dtype=self.cp_type)
110-
self.cupy_vector[0] = 1
111+
if self.cupy_vector is not None:
112+
self.cupy_vector[:] = 0
113+
self.cupy_vector[0] = 1
114+
else:
115+
self.cupy_vector = cp.zeros(shape=2**self.num_qubits, dtype=self.cp_type)
116+
self.cupy_vector[0] = 1
111117
return self
112118

113119
def __del__(self) -> None:
114120
"""Clean up GPU resources when the object is destroyed."""
115121
# CuPy will release GPU memory when the variable ``self.cupy_vector`` is no longer
116122
# reachable. However, we need to manually destroy the library handle.
117-
cusv.destroy(self.libhandle)
123+
if self.libhandle:
124+
cusv.destroy(self.libhandle)
118125

119126
@property
120127
def vector(self) -> ArrayLike:

0 commit comments

Comments
 (0)