[Bug] `tvm.contrib.thrust.sort` (`thrust.cu`): missing `policy` on `thrust::sequence` breaks CUDA stream ordering / graph capture, and unpaired `mr.do_allocate` leaks `12 * size` bytes of GPU memory per segmented sort

Abierto
#21,116 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 3 días

@yhna940 ya está trabajando en esto.

Desde el 3/12/2026.

  • #21117 de @yhna940 — abierto

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
35/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Estancado
Stack tecnológico
cpp

Línea de trabajo

Read src/runtime/extra/contrib/thrust/thrust.cu, focusing on thrust_sort, WorkspaceMemoryResource, and get_thrust_exec_policy; the issue links the relevant code and provides a standalone reproduction. Check the two thrust::sequence calls and the segmented-sort allocations, then run the reproduction’s CUDA Graph capture and repeated-sort checks. Done means capture succeeds and repeated segmented sorts do not retain temporary GPU memory; linked pull request #21117 is already open.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

needs-triage type: bug
Expected behavior

thrust_sort in src/runtime/extra/contrib/thrust/thrust.cu should:

  1. Execute all Thrust operations on TVM's active CUDA stream (policy), preserving stream ordering and CUDA Graph capture compatibility.
  2. Release all temporary buffers allocated via WorkspaceMemoryResource::do_allocate before returning, so repeated segmented sorts without an explicit workspace do not leak GPU VRAM.
Actual behavior

Checked at main commit 84657c01e5d3, thrust_sort has two bugs:

https://github.com/apache/tvm/blob/84657c01e5d3672cfd299bd3d5c77bff3888a1a9/src/runtime/extra/contrib/thrust/thrust.cu#L120-L173

  1. Both thrust::sequence calls omit policy (L122 and L135):

    • Single-segment path (L122): thrust::sequence(indices_ptr, indices_ptr + n_values);
    • Segmented path (L135): thrust::sequence(argsort_order, argsort_order + size);
      Without policy, Thrust launches sequence on the legacy default stream 0 and synchronizes implicitly instead of running on TVM's par_nosync(&mr).on(stream). On non-blocking streams this introduces a stream-ordering race against subsequent par_nosync calls (sort_by_key / stable_sort_by_key) and causes CUDA Graph stream capture to fail with cudaErrorStreamCaptureUnsupported / cudaErrorStreamCaptureInvalidated (901).
  2. Unconditional GPU memory leak on every segmented sort when workspace == nullptr (L133–L134 and L157–L158):

    • L134 allocates sizeof(int64_t) * size bytes for argsort_order via mr.do_allocate(...).
    • L158 allocates sizeof(int) * size bytes for segment_ids via mr.do_allocate(...).
    • Neither allocation is ever passed to mr.do_deallocate(...).
    • When workspace == nullptr, WorkspaceMemoryResource delegates do_allocate to the thread-local persistent pool thrust::mr::tls_disjoint_pool(...) (L62–L64, L77). Because do_deallocate is never called, the pool never reclaims those blocks, permanently leaking at least 12 * size bytes (plus pool power-of-two rounding) of GPU VRAM on every segmented thrust_sort call until OOM.
Environment
  • OS: Ubuntu 24.04 (x86_64)
  • GPU: NVIDIA A100 80GB (sm_80)
  • CUDA: 12.9.86
  • TVM commit: 84657c01e5d3672cfd299bd3d5c77bff3888a1a9
Steps to reproduce

Extract lines 51–173 of src/runtime/extra/contrib/thrust/thrust.cu (WorkspaceMemoryResource, get_thrust_exec_policy, and thrust_sort) as tvm_thrust_excerpt.inc, then compile and run:

sed -n '51,173p' src/runtime/extra/contrib/thrust/thrust.cu > tvm_thrust_excerpt.inc
nvcc -O2 -std=c++17 --extended-lambda repro_tvm_thrust.cu -o repro_tvm_thrust && ./repro_tvm_thrust

repro_tvm_thrust.cu:

#include <cstdio>
#include <cstdint>
#include <algorithm>
#include <functional>
#include <memory>
#include <stdexcept>
#include <iostream>
#include <string>
#include <cuda_runtime.h>
#include <thrust/device_ptr.h>
#include <thrust/gather.h>
#include <thrust/mr/device_memory_resource.h>
#include <thrust/mr/disjoint_tls_pool.h>
#include <thrust/mr/memory_resource.h>
#include <thrust/sequence.h>
#include <thrust/sort.h>

enum { kDLUInt = 1, kDLCUDA = 2 };
struct DLDataType { uint8_t code; uint8_t bits; uint16_t lanes; };
struct DLTensor { void* data; int ndim; DLDataType dtype; int64_t* shape; };

static cudaStream_t g_tvm_stream = 0;
static void* TVMFFIEnvGetStream(int, int) { return (void*)g_tvm_stream; }
#define TVM_FFI_ICHECK(cond) if (!(cond)) throw std::runtime_error("TVM_FFI_ICHECK failed: " #cond); else if (false) std::cerr
#define TVM_FFI_CHECK_CUDA_ERROR(call) do { cudaError_t e = (call); if (e != cudaSuccess) throw std::runtime_error(cudaGetErrorString(e)); } while (0)

namespace tvm_buggy {
#include "tvm_thrust_excerpt.inc"
}

namespace tvm_fixed {
using WorkspaceMemoryResource = tvm_buggy::WorkspaceMemoryResource;

template <typename DataType, typename IndicesType>
void thrust_sort(DLTensor* input, DLTensor* out_values, DLTensor* out_indices, bool is_ascend,
                 int n_values, DLTensor* workspace) {
  thrust::device_ptr<DataType> data_ptr(static_cast<DataType*>(input->data));
  thrust::device_ptr<DataType> values_ptr(static_cast<DataType*>(out_values->data));
  thrust::device_ptr<IndicesType> indices_ptr(static_cast<IndicesType*>(out_indices->data));
  WorkspaceMemoryResource mr(workspace);
  auto policy = tvm_buggy::get_thrust_exec_policy(&mr);
  size_t size = 1;
  for (int i = 0; i < input->ndim; ++i) size *= input->shape[i];
  thrust::copy(policy, data_ptr, data_ptr + size, values_ptr);
  if (size == static_cast<size_t>(input->shape[input->ndim - 1])) {
    thrust::sequence(policy, indices_ptr, indices_ptr + static_cast<ptrdiff_t>(n_values));
    if (is_ascend) thrust::sort_by_key(policy, values_ptr, values_ptr + n_values, indices_ptr);
    else thrust::sort_by_key(policy, values_ptr, values_ptr + n_values, indices_ptr, thrust::greater<DataType>());
  } else {
    void* raw_ao = mr.do_allocate(sizeof(int64_t) * size, sizeof(int64_t));
    thrust::device_ptr<int64_t> argsort_order(static_cast<int64_t*>(raw_ao));
    thrust::sequence(policy, argsort_order, argsort_order + static_cast<ptrdiff_t>(size));
    if (is_ascend) thrust::stable_sort_by_key(policy, values_ptr, values_ptr + size, argsort_order);
    else thrust::stable_sort_by_key(policy, values_ptr, values_ptr + size, argsort_order, thrust::greater<DataType>());
    auto counting_iter = thrust::counting_iterator<int64_t>(0);
    auto lin_to_axis = [n_values] __host__ __device__(int64_t i) { return i % n_values; };
    auto init_idx = thrust::make_transform_iterator(counting_iter, lin_to_axis);
    thrust::gather(policy, argsort_order, argsort_order + size, init_idx, indices_ptr);
    void* raw_seg = mr.do_allocate(sizeof(int) * size, sizeof(int));
    thrust::device_ptr<int> segment_ids(static_cast<int*>(raw_seg));
    auto lin_to_seg = [n_values] __host__ __device__(int64_t i) { return i / n_values; };
    thrust::transform(policy, argsort_order, argsort_order + size, segment_ids, lin_to_seg);
    auto key_val_zip = thrust::make_zip_iterator(thrust::make_tuple(values_ptr, indices_ptr));
    thrust::stable_sort_by_key(policy, segment_ids, segment_ids + size, key_val_zip);
    mr.do_deallocate(raw_seg, sizeof(int) * size, sizeof(int));
    mr.do_deallocate(raw_ao, sizeof(int64_t) * size, sizeof(int64_t));
  }
}
}

int main() {
  cudaStream_t st;
  cudaStreamCreateWithFlags(&st, cudaStreamNonBlocking);
  g_tvm_stream = st;

  // Test 1: CUDA Graph capture on 1D and 2D thrust_sort
  {
    int64_t sh1[1] = {1024};
    float *d_in, *d_val; int32_t *d_idx;
    cudaMalloc(&d_in, 1024 * sizeof(float));
    cudaMalloc(&d_val, 1024 * sizeof(float));
    cudaMalloc(&d_idx, 1024 * sizeof(int32_t));
    DLTensor tin{d_in, 1, {2,32,1}, sh1}, tval{d_val, 1, {2,32,1}, sh1}, tidx{d_idx, 1, {0,32,1}, sh1};
    void* ws_ptr; cudaMalloc(&ws_ptr, 16 * 1024 * 1024);
    int64_t ws_sh[1] = {16 * 1024 * 1024};
    DLTensor ws{ws_ptr, 1, {kDLUInt, 8, 1}, ws_sh};

    cudaStreamBeginCapture(st, cudaStreamCaptureModeGlobal);
    std::string exc1 = "none";
    try { tvm_buggy::thrust_sort<float, int32_t>(&tin, &tval, &tidx, true, 1024, &ws); }
    catch (const std::exception& e) { exc1 = e.what(); }
    cudaGraph_t g1 = nullptr;
    cudaError_t cap_bug1 = cudaStreamEndCapture(st, &g1);
    if (g1) cudaGraphDestroy(g1);
    cudaGetLastError();

    cudaStreamBeginCapture(st, cudaStreamCaptureModeGlobal);
    tvm_fixed::thrust_sort<float, int32_t>(&tin, &tval, &tidx, true, 1024, &ws);
    cudaGraph_t g2 = nullptr;
    cudaError_t cap_fix1 = cudaStreamEndCapture(st, &g2);
    if (g2) cudaGraphDestroy(g2);
    printf("STREAM_CAPTURE_1D: buggy_rc=%d (%s) exc=[%s] | fixed_rc=%d (%s)\n",
           (int)cap_bug1, cudaGetErrorName(cap_bug1), exc1.c_str(), (int)cap_fix1, cudaGetErrorName(cap_fix1));

    int64_t sh2[2] = {2, 512};
    DLTensor tin2{d_in, 2, {2,32,1}, sh2}, tval2{d_val, 2, {2,32,1}, sh2}, tidx2{d_idx, 2, {0,32,1}, sh2};
    cudaStreamBeginCapture(st, cudaStreamCaptureModeGlobal);
    std::string exc2 = "none";
    try { tvm_buggy::thrust_sort<float, int32_t>(&tin2, &tval2, &tidx2, true, 512, &ws); }
    catch (const std::exception& e) { exc2 = e.what(); }
    cudaGraph_t g3 = nullptr;
    cudaError_t cap_bug2 = cudaStreamEndCapture(st, &g3);
    if (g3) cudaGraphDestroy(g3);
    cudaGetLastError();

    cudaStreamBeginCapture(st, cudaStreamCaptureModeGlobal);
    tvm_fixed::thrust_sort<float, int32_t>(&tin2, &tval2, &tidx2, true, 512, &ws);
    cudaGraph_t g4 = nullptr;
    cudaError_t cap_fix2 = cudaStreamEndCapture(st, &g4);
    if (g4) cudaGraphDestroy(g4);
    printf("STREAM_CAPTURE_2D: buggy_rc=%d (%s) exc=[%s] | fixed_rc=%d (%s)\n",
           (int)cap_bug2, cudaGetErrorName(cap_bug2), exc2.c_str(), (int)cap_fix2, cudaGetErrorName(cap_fix2));

    cudaFree(ws_ptr); cudaFree(d_in); cudaFree(d_val); cudaFree(d_idx);
  }

  // Test 2: Unconditional GPU VRAM leak on 2D segmented sort (workspace == nullptr)
  {
    const int64_t rows = 2, cols = 1024 * 1024;  // size = 2,097,152 -> 12 * size = 24 MiB/call
    const size_t N = rows * cols;
    int64_t sh2[2] = {rows, cols};
    float *d_in, *d_val; int32_t *d_idx;
    cudaMalloc(&d_in, N * sizeof(float));
    cudaMalloc(&d_val, N * sizeof(float));
    cudaMalloc(&d_idx, N * sizeof(int32_t));
    cudaMemset(d_in, 0, N * sizeof(float));
    DLTensor tin{d_in, 2, {2,32,1}, sh2}, tval{d_val, 2, {2,32,1}, sh2}, tidx{d_idx, 2, {0,32,1}, sh2};

    tvm_fixed::thrust_sort<float, int32_t>(&tin, &tval, &tidx, true, (int)cols, nullptr);
    cudaStreamSynchronize(st);
    size_t free_f0, free_f1, free_b0, free_b1, total_m;
    cudaMemGetInfo(&free_f0, &total_m);
    for (int it = 0; it < 16; ++it)
      tvm_fixed::thrust_sort<float, int32_t>(&tin, &tval, &tidx, true, (int)cols, nullptr);
    cudaStreamSynchronize(st);
    cudaMemGetInfo(&free_f1, &total_m);
    long long fixed_leaked_mb = (long long)(free_f0 - free_f1) / (1024 * 1024);

    cudaMemGetInfo(&free_b0, &total_m);
    for (int it = 0; it < 16; ++it)
      tvm_buggy::thrust_sort<float, int32_t>(&tin, &tval, &tidx, true, (int)cols, nullptr);
    cudaStreamSynchronize(st);
    cudaMemGetInfo(&free_b1, &total_m);
    long long buggy_leaked_mb = (long long)(free_b0 - free_b1) / (1024 * 1024);
    printf("VRAM_LEAK_16_CALLS (24 MiB/call expected): fixed_delta_MiB=%lld buggy_delta_MiB=%lld\n",
           fixed_leaked_mb, buggy_leaked_mb);

    cudaFree(d_in); cudaFree(d_val); cudaFree(d_idx);
  }
  cudaStreamDestroy(st);
  return 0;
}
Observed output (NVIDIA A100 80GB, sm_80, CUDA 12.9.86)
STREAM_CAPTURE_1D: buggy_rc=901 (cudaErrorStreamCaptureInvalidated) exc=[parallel_for: failed to synchronize: cudaErrorStreamCaptureUnsupported: operation not permitted when stream is capturing] | fixed_rc=0 (cudaSuccess)
STREAM_CAPTURE_2D: buggy_rc=901 (cudaErrorStreamCaptureInvalidated) exc=[parallel_for: failed to synchronize: cudaErrorStreamCaptureUnsupported: operation not permitted when stream is capturing] | fixed_rc=0 (cudaSuccess)
VRAM_LEAK_16_CALLS (24 MiB/call expected): fixed_delta_MiB=0 buggy_delta_MiB=630

Passing policy to both thrust::sequence calls and pairing mr.do_deallocate eliminates both the stream-capture failure (cudaSuccess) and the 630 MiB VRAM leak (0 MiB net delta over 16 calls).

Suggested fix
  1. Pass policy to both thrust::sequence calls (L122, L135):
    thrust::sequence(policy, indices_ptr, indices_ptr + n_values);
    ...
    thrust::sequence(policy, argsort_order, argsort_order + size);
    
  2. Pair both manual mr.do_allocate calls with mr.do_deallocate before returning from the segmented branch (or wrap them in an RAII guard so exceptions also release them):
    mr.do_deallocate(segment_ids.get(), sizeof(int) * size, sizeof(int));
    mr.do_deallocate(argsort_order.get(), sizeof(int64_t) * size, sizeof(int64_t));
    
Triage
  • needs-triage
  • backend:cuda
  • runtime:c++
Lenguaje dominante
Python
Estrellas
13.9k
Forks
4.1k
Merge medio
4 d 22 h
PR fusionados (30 d)
22

Preparar el entorno

Este proyecto no incluye contenedor de desarrollo, Dockerfile ni guía de contribución, así que la configuración corre por tu cuenta: empieza por su README y consulta nuestra guía para la primera contribución para los pasos generales.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de apache/tvm

Todos los issues de apache/tvm

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.