cuStateVecEx Vector move assignment leaks the state vector it overwrites

Aperta
#1,146 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 2 giorni

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
57/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
cpp

Direzione di ricerca

Start with lib/vectorspace_custatevecex.h, especially Vector::operator=(Vector&&) and its destructor, to trace ownership of the cuStateVecEx descriptor. The issue includes a CUDA reproducer, repro_issue2_leak.cu; build and run it with the stated qsim and cuQuantum paths to check memory before and after assignment. Done when overwriting a live vector releases its old device allocation and the reproducer returns memory after cleanup.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Describe the issue

VectorSpaceCuStateVecEx::Vector::operator=(Vector&&) (lib/vectorspace_custatevecex.h L108-L125) copies r.ptr_ into ptr_ without first destroying the state-vector descriptor that ptr_ already owns:

Vector& operator=(Vector&& r) {
  if (this != &r) {
    mp_ = r.mp_;
    ptr_ = r.ptr_;   // the old ptr_ is overwritten without custatevecExStateVectorDestroy
    ...

The destructor (L102-L106) is the only place that calls custatevecExStateVectorDestroy. So the overwritten state vector's device memory is never released. The move constructor (L91-L100) is fine, because a newly constructed object doesn't own anything yet. The reproducer below shows this directly: every state that gets overwritten stays allocated.

The other GPU backends don't have this problem. VectorSpaceCUDA::Vector, used by gpu_mode=0 and 1, keeps its buffer in a std::unique_ptr (vectorspace_cuda.h L48, L80) and doesn't define its own move assignment. Assigning into it therefore frees the old buffer.

Current callers on main. I couldn't find a code path that triggers this through qsimcirq today:

  • SimulatorHelper in pybind_interface/pybind_main.cpp only assigns into a state that starts out null.
  • lib/expect.h (L56-L57) only replaces its temporary when it is null or smaller than the state, and qsimcirq always passes one of the right size after the first call.

Any other assignment into a live state leaks, for example state = state_space.Create(n) or state = StateSpace::Null(). #1100 ran into this when an interim version released its states with state = StateSpace::Null(); in a destructor, and repeated simulate-and-free cycles leaked device memory. #1100 now avoids the move assignment.

Possible fix (sketch, not tested): destroy the currently owned descriptor before taking over r's:

Vector& operator=(Vector&& r) {
  if (this != &r) {
    if (ptr_ != nullptr) {
      ErrorCheck(custatevecExStateVectorDestroy(ptr_));
    }
    mp_ = r.mp_;
    ptr_ = r.ptr_;
    // ... rest unchanged
Tell us how to reproduce the issue

Save this as repro_issue2_leak.cu:

// Reproducer: VectorSpaceCuStateVecEx::Vector move assignment does not free
// the state vector it overwrites (lib/vectorspace_custatevecex.h).
//
// Build (QSIM = a qsim checkout, CUQUANTUM_ROOT = a cuQuantum install):
//   nvcc -std=c++17 -I "$QSIM/lib" -I "$CUQUANTUM_ROOT/include" \
//        repro_issue2_leak.cu -L "$CUQUANTUM_ROOT/lib" -lcustatevec -lcublas \
//        -Xlinker -rpath -Xlinker "$CUQUANTUM_ROOT/lib" -o repro_issue2_leak
// Run on one GPU:
//   CUDA_VISIBLE_DEVICES=0 ./repro_issue2_leak

#include <cstdio>

#include <cuda_runtime.h>

#include "statespace_custatevecex.h"

using StateSpace = qsim::StateSpaceCuStateVecEx<float>;

// Device memory in use, in MiB, relative to the first call.
static double UsedMiB() {
  static size_t baseline = 0;
  cudaDeviceSynchronize();
  size_t free_bytes = 0, total_bytes = 0;
  cudaMemGetInfo(&free_bytes, &total_bytes);
  if (baseline == 0) baseline = free_bytes;
  return (double(baseline) - double(free_bytes)) / (1024.0 * 1024.0);
}

static void Report(const char* step) {
  std::printf("%-44s %8.0f MiB in use\n", step, UsedMiB());
}

int main() {
  const unsigned num_qubits = 26;     // 2^26 complex64 amplitudes = 512 MiB
  qsim::MultiProcessCuStateVecEx mp;  // single process
  StateSpace state_space(mp);
  Report("start");

  {  // Control: a state freed by its destructor returns its memory.
    auto control = state_space.Create(num_qubits);
    state_space.SetStateZero(control);
    Report("control: create");
  }
  Report("control: destructor ran");

  {  // Bug: move-assigning over a live state leaks the state it replaces.
    auto state = state_space.Create(num_qubits);
    state_space.SetStateZero(state);
    Report("state = Create()            (A)");
    state = state_space.Create(num_qubits);
    state_space.SetStateZero(state);
    Report("state = Create()            (B replaces A)");
    state = StateSpace::Null();
    Report("state = StateSpace::Null()  (replaces B)");
  }
  Report("after scope (destructor ran)");
  return 0;
}

Build and run it as in its header comment, with QSIM set to a checkout of main and CUQUANTUM_ROOT set to a cuQuantum install:

$ nvcc -std=c++17 -I "$QSIM/lib" -I "$CUQUANTUM_ROOT/include" \
       repro_issue2_leak.cu -L "$CUQUANTUM_ROOT/lib" -lcustatevec -lcublas \
       -Xlinker -rpath -Xlinker "$CUQUANTUM_ROOT/lib" -o repro_issue2_leak
$ CUDA_VISIBLE_DEVICES=0 ./repro_issue2_leak
start                                               0 MiB in use
control: create                                   542 MiB in use
control: destructor ran                             2 MiB in use
state = Create()            (A)                   542 MiB in use
state = Create()            (B replaces A)       1080 MiB in use
state = StateSpace::Null()  (replaces B)         1080 MiB in use
after scope (destructor ran)                     1080 MiB in use
  • Control: a state destroyed normally gives its memory back.
  • B replaces A: A stays allocated.
  • Null() replaces B: nothing is freed.
  • After the scope ends: both state vectors are still allocated.

I got the same numbers on an NVIDIA A100-SXM4-40GB and a Tesla T4.

Tell us the version of qsim or qsimcirq (if relevant)

main @ 50cac4b (qsimcirq 0.23.0.dev0)

Tell us the computing environment (if relevant)

Linux (nvidia/cuda:13.2.0-devel-ubuntu24.04 container), NVIDIA A100-SXM4-40GB and Tesla T4 (identical results), driver 580.159.04, CUDA 13.2, cuQuantum 26.01.0.4 (cuStateVec 1.12.0.4)

Lingua principale
C++
Stelle
702
Fork
219
Merge medio
1g 2h
PR unite (30g)
8

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di quantumlib/qsim

Tutte le issue di quantumlib/qsim

Issue simili

Altre issue su C++

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.