Skip to content

fix: prevent allocation retirement from blocking unrelated streams - #1839

Open
Ninzore wants to merge 9 commits into
NVIDIA:mainfrom
Ninzore:fix/stream-retirement
Open

Ninzore wants to merge 9 commits into
NVIDIA:mainfrom
Ninzore:fix/stream-retirement

Conversation

@Ninzore

@Ninzore Ninzore commented Nov 19, 2026 •

Copy link
Copy Markdown

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

  • Move owned stream retirement to a background worker.
  • Separate completion polling from resource cleanup.
  • Make completion cleanup capture-safe.
  • Retain per-thread stream owners until context-wide work completes.

Testing
Validated on an NVIDIA RTX PRO 4500 Blackwell.

  • Each commit passes 112 existing cuda-core tests; 2 ignored.
  • Each commit passes formatting and Clippy with warnings denied.
  • Reproduced the original failure; the fixed version passes 20 rounds of the same shared-allocation tests.
  • Existing device-buffer tests pass 5 rounds.

Checklist

  • All four new commits signed off (git commit -s).
  • All commits cryptographically signed and shown as Verified on GitHub — the four new commits are signed locally; GitHub verification remains pending.
  • SPDX headers on new source files — not applicable; no new source files committed.

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]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 19, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@elibol elibol left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_review

Run 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();
}

Comment thread cuda-core/src/runtime.rs
return;
}
// Ordinary owned streams enqueue only CPU work on the dropping thread.
crate::completion::defer_stream(move || retired.retire_owned());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eligible idle streams now return directly to the pool

Comment thread cuda-core/src/allocation.rs Outdated
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())

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Ninzore

Ninzore commented Nov 25, 2026

Copy link
Copy Markdown
Author

The new commited changes focus on three areas:

  • Batch synchronous memory frees in the background: Reduce per-free bookkeeping and let the calling thread return sooner, allowing allocation and reclamation to overlap.
  • Return idle streams to the pool promptly: Reduce unnecessary background retirement queuing while preserving stream pooling.
  • Preserve resource lifetimes: Keep owners and CUDA contexts alive until GPU work completes, preventing premature release.
Workload Metric Before all patches 348895e Previous a8d9182 Final 027fdc9 Final vs. before-all
streams 5000 Submission 1408.345 1411.345 1406.030 −0.16%
streams 5000 Completion 1408.575 1411.575 1406.375 −0.16%
free_batch 2000 Submission 203.024 202.848 94.699 −53.36%
free_batch 2000 Completion 4054.179 4008.927 3258.727 −19.62%
alloc_cycle 2000 Submission 10678.694 11004.007 4912.950 −53.99%
alloc_cycle 2000 Completion 12134.452 12436.147 7381.512 −39.17%
completed_events 2000 Submission 20691.662 20621.904 21418.897 +3.51%
completed_events 2000 Completion 20697.587 20630.683 21436.322 +3.57%

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: shared_allocation pending_copy test fails under parallel test threads

2 participants