[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
Los mantenedores suelen responder en 3 días
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
- Área
- backend, performance
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
Expected behavior
thrust_sort in src/runtime/extra/contrib/thrust/thrust.cu should:
- Execute all Thrust operations on TVM's active CUDA stream (
policy), preserving stream ordering and CUDA Graph capture compatibility. - Release all temporary buffers allocated via
WorkspaceMemoryResource::do_allocatebefore 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:
-
Both
thrust::sequencecalls omitpolicy(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);
Withoutpolicy, Thrust launchessequenceon the legacy default stream0and synchronizes implicitly instead of running on TVM'spar_nosync(&mr).on(stream). On non-blocking streams this introduces a stream-ordering race against subsequentpar_nosynccalls (sort_by_key/stable_sort_by_key) and causes CUDA Graph stream capture to fail withcudaErrorStreamCaptureUnsupported/cudaErrorStreamCaptureInvalidated (901).
- Single-segment path (L122):
-
Unconditional GPU memory leak on every segmented sort when
workspace == nullptr(L133–L134 and L157–L158):- L134 allocates
sizeof(int64_t) * sizebytes forargsort_orderviamr.do_allocate(...). - L158 allocates
sizeof(int) * sizebytes forsegment_idsviamr.do_allocate(...). - Neither allocation is ever passed to
mr.do_deallocate(...). - When
workspace == nullptr,WorkspaceMemoryResourcedelegatesdo_allocateto the thread-local persistent poolthrust::mr::tls_disjoint_pool(...)(L62–L64, L77). Becausedo_deallocateis never called, the pool never reclaims those blocks, permanently leaking at least12 * sizebytes (plus pool power-of-two rounding) of GPU VRAM on every segmentedthrust_sortcall until OOM.
- L134 allocates
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
- Pass
policyto boththrust::sequencecalls (L122, L135):thrust::sequence(policy, indices_ptr, indices_ptr + n_values); ... thrust::sequence(policy, argsort_order, argsort_order + size); - Pair both manual
mr.do_allocatecalls withmr.do_deallocatebefore 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
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de apache/tvm
-
[Bug] [Relax] `relax.op.unique(return_inverse=True)` returns an input-shaped inverse for N-D input when `axis` is NonePosiblemente ocupada Un pull request vinculado a esta issue está abierto o ya se fusionó. Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 3 días
-
[Bug][TOPI] `topi.scanop` (`cumsum` / `cumprod`) performs out-of-bounds write/read on empty tensorsAbiertoneeds-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 82/100
Los mantenedores suelen responder en 3 días
-
[Bug] [Relax] take_backward does not normalize negative axis causing heap OOB write and wrong gradientsPosiblemente ocupada @pierceluu10 la tomó hace 4 días. Abiertoneeds-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 3 días
-
[Bug][Relax][ONNX] NonZero returns the wrong output shape for scalar inputsPosiblemente ocupada @tandede la tomó hace 9 días. Abiertoneeds-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 70/100
Los mantenedores suelen responder en 3 días
-
needs-triage type: bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
apache/tvm#21043 · 1 comentario ·
Los mantenedores suelen responder en 3 días
Todos los issues de apache/tvm
Issues similares
-
Dificultad 1/5 1-3 horas Aptitud para principiantes 78/100
web-push-libs/pywebpush#216 · 1 comentario ·
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
AgriciDaniel/claude-seo#572 ·
Los mantenedores suelen responder en 5 días
-
area:print-dispatch
Dificultad 2/5 1-3 horas Aptitud para principiantes 92/100
Los mantenedores suelen responder en 1 día
-
area: docs domain: technical-writing good first issue type: documentation
Dificultad 2/5 1-3 horas Aptitud para principiantes 80/100
Deepak3699/Ai_Mentor#919 ·
Los mantenedores suelen responder en 2 días
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día