Repository navigation
Conversation
Free synchronous allocations with cuMemFreeAsync on a separate nonblocking stream. Wait on the background worker to avoid blocking unrelated stream operations. Fall back to cuMemFree if unsupported or stream creation fails.
Restore capture mode after querying or waiting for retirement events. Destroy completion events before releasing external context owners. Signed-off-by: ruolingp <[email protected]>
Separate completion polling from owner cleanup. Keep blocking resource destruction away from completion polling. Signed-off-by: ruolingp <[email protected]>
Move driver queries, event recording, and recycling out of Stream::drop. Keep stream resources alive until queued GPU work completes. Signed-off-by: ruolingp <[email protected]>
Snapshot context-wide completion before retiring per-thread streams. Isolate context cleanup so one blocked owner cannot delay another context. Signed-off-by: ruolingp <[email protected]>
elibol
left a comment
There was a problem hiding this comment.
Thanks for tackling the retirement stall. I found two host-runtime performance regressions that need a closer look before merging; the inline comments narrow down the affected paths.
Compared merge base f13e7dfc04c4d8ce86d7ab8e16835b38fe011057 with head c55561178332ab4a25b1786130c12eb56b46414b, using identical release-build microbenchmarks on RTX 5090 with CUDA 13.3 and Rust 1.98.0. These are medians from ten alternating before/after process pairs, after warmup. Timing includes waiting for cleanup to release its retained context references.
| Scenario | Work per run | Base | Head |
|---|---|---|---|
| Create/drop idle streams | 5,000 cycles | 0.621 ms | 4.276 ms |
| Drop preallocated synchronous buffers and drain cleanup | 2,000 × 8 KiB | 2.318 ms | 4.146 ms |
In both scenarios, every head run was slower than every baseline run. Interleaving allocation and drop improved in median (8.702 → 6.869 ms for 2,000 allocations), so the allocation finding is specifically about the free/retirement path. Recording and retiring 2,000 events on an idle stream also showed higher median time (3.699 → 5.431 ms), but I have not isolated its contributing operations.
The six shared_allocation tests pass at this head. These measurements cover host resource management; they do not establish a kernel or application-level slowdown. This was a desktop GPU with some background activity, not an isolated benchmark machine.
Reproducer and commands
Place this example at cuda-core/examples/retirement_perf_review.rs in separate checkouts of the two revisions. Build from the repository root, using a separate Cargo target directory for each checkout:
CUDA_TOOLKIT_PATH=/usr/local/cuda-13.3 \
CUDA_HOME=/usr/local/cuda-13.3 \
CARGO_TARGET_DIR="$PWD/target-retirement-review" \
cargo build --release --locked -p cuda-core --example retirement_perf_reviewRun each command ten times per revision, alternating which revision runs first. The output columns are mode, iteration count, enqueue/loop time in microseconds, total time through cleanup in microseconds, and number of distinct stream handles.
./target-retirement-review/release/examples/retirement_perf_review streams 5000
./target-retirement-review/release/examples/retirement_perf_review free_batch 2000
./target-retirement-review/release/examples/retirement_perf_review alloc_cycle 2000
./target-retirement-review/release/examples/retirement_perf_review completed_events 2000/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
use cuda_core::{Context, RawDeviceBuffer};
use std::sync::Arc;
use std::time::{Duration, Instant};
fn drain(ctx: &Arc<Context>, expected: usize) {
let deadline = Instant::now() + Duration::from_secs(30);
while Arc::strong_count(ctx) > expected {
assert!(
Instant::now() < deadline,
"retirement did not drain: {} context references",
Arc::strong_count(ctx)
);
std::thread::yield_now();
}
ctx.bind_to_thread()
.expect("retirement recorded a CUDA error");
}
fn alloc(ctx: &Arc<Context>, bytes: usize) -> RawDeviceBuffer {
ctx.bind_to_thread().unwrap();
// SAFETY: adopt this unique cuMemAlloc allocation without reading it or
// submitting any device work. The retained context owns its allocation.
unsafe {
let ptr = cuda_core::memory::malloc_sync(bytes).unwrap();
RawDeviceBuffer::from_raw_parts(ptr, bytes, ctx.clone())
}
}
fn main() {
let args: Vec<_> = std::env::args().collect();
let mode = args.get(1).map(String::as_str).unwrap_or("streams");
let n: usize = args.get(2).map(|s| s.parse().unwrap()).unwrap_or(5000);
let ctx = Context::new(0).unwrap();
ctx.synchronize().unwrap();
// Warm driver and worker setup before collecting timings. The stream test
// starts with one reusable idle stream, rather than a batch-sized pool.
drop(ctx.new_stream().unwrap());
drain(&ctx, 1);
drop(alloc(&ctx, 8192));
drain(&ctx, 1);
let mut handles = Vec::with_capacity(n);
let (submit, total) = match mode {
"streams" => {
let start = Instant::now();
for _ in 0..n {
let stream = ctx.new_stream().unwrap();
handles.push(stream.cu_stream() as usize);
drop(stream);
}
let submit = start.elapsed();
drain(&ctx, 1);
(submit, start.elapsed())
}
"alloc_cycle" => {
let start = Instant::now();
for _ in 0..n {
drop(alloc(&ctx, 8192));
}
let submit = start.elapsed();
drain(&ctx, 1);
(submit, start.elapsed())
}
"free_batch" => {
let buffers: Vec<_> = (0..n).map(|_| alloc(&ctx, 8192)).collect();
let start = Instant::now();
drop(buffers);
let submit = start.elapsed();
drain(&ctx, 1);
(submit, start.elapsed())
}
"completed_events" => {
let stream = ctx.new_stream().unwrap();
let buffer = alloc(&ctx, 8192);
let expected = Arc::strong_count(&ctx);
let start = Instant::now();
for _ in 0..n {
cuda_core::completion::retain_until_complete(buffer.clone(), &stream).unwrap();
}
let submit = start.elapsed();
drain(&ctx, expected);
let total = start.elapsed();
drop((buffer, stream));
drain(&ctx, 1);
(submit, total)
}
other => panic!("unknown mode {other}"),
};
handles.sort_unstable();
handles.dedup();
println!(
"{mode},{n},{:.3},{:.3},{}",
submit.as_secs_f64() * 1e6,
total.as_secs_f64() * 1e6,
handles.len()
);
ctx.synchronize().unwrap();
}| return; | ||
| } | ||
| // Ordinary owned streams enqueue only CPU work on the dropping thread. | ||
| crate::completion::defer_stream(move || retired.retire_owned()); |
There was a problem hiding this comment.
Idle-stream reuse becomes substantially more expensive. This unconditionally defers owned-stream retirement, including streams that have no queued work, so their handles cannot re-enter the pool until the worker processes them.
A tight context.new_stream() / drop(stream) loop, starting with one warmed pooled stream and no GPU work, takes 0.621 → 4.276 ms for 5,000 iterations including final cleanup. The baseline uses one distinct handle; the head uses 28–94 across the repeated runs. The full time ranges are 0.614–0.648 ms before and 2.176–4.606 ms after.
This isolates a regression in the idle-stream lifecycle and reuse path, without kernel execution or device-buffer allocation in the timed loop. Could you investigate that overhead as part of this fix? The reproducer is in the review summary.
There was a problem hiding this comment.
Eligible idle streams now return directly to the pool
| Ok(stream) => { | ||
| // SAFETY: all leases drained; this stream shares the retained context. | ||
| unsafe { crate::memory::free_async(ptr, stream.cu_stream()) } | ||
| .and_then(|()| stream.synchronize()) |
There was a problem hiding this comment.
Cleanup of completed synchronous allocations is slower. Allocating 2,000 buffers of 8 KiB each before starting the timer, then dropping them and waiting for retirement to drain, takes 2.318 → 4.146 ms. The full time ranges are 1.967–2.419 ms before and 4.058–4.290 ms after. No GPU accesses are outstanding on these buffers.
This path now queries memory-pool support, obtains a stream, submits the free, and synchronizes for each allocation. The measurement isolates free/retirement cost from allocation and kernel latency; it does not yet establish which of those operations or worker interactions dominates. Could you investigate this case alongside the original unrelated-stream stall? The reproducer is in the review summary.
There was a problem hiding this comment.
Fixed by batching frees on the worker’s per-thread stream and synchronizing once per context per batch, removing per-allocation stream creation and synchronization.
Signed-off-by: ruolingp <[email protected]>
Signed-off-by: ruolingp <[email protected]>
Signed-off-by: ruolingp <[email protected]>
|
The new commited changes focus on three areas:
|
Summary
Prevent owned stream destruction from blocking on queued GPU work or driver contention, while keeping stream resources and context owners alive until completion. Free synchronous allocations with cuMemFreeAsync on a private stream when supported, avoiding context-wide stalls. Fix #1768
Changes
Testing
Validated on an NVIDIA RTX PRO 4500 Blackwell.
Checklist