transfer_context_v2.rs 6.71 KB
Newer Older
1
2
3
4
5
6
7
8
9
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

#[cfg(feature = "testing-cuda")]
mod benchmarks {
    use std::sync::Arc;

    use criterion::{BenchmarkId, Criterion, criterion_group};
    use cudarc::driver::{CudaContext, CudaStream};
10

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    use tokio::runtime::Runtime;
    use tokio_util::task::TaskTracker;

    use dynamo_llm::block_manager::block::transfer::context;

    struct BenchmarkRuntime {
        _runtime: Runtime,
        handle: tokio::runtime::Handle,
        stream: Arc<CudaStream>,
        nixl_agent: Arc<Option<nixl_sys::Agent>>,
    }

    impl BenchmarkRuntime {
        fn new() -> Self {
            let runtime = Runtime::new().expect("Failed to create benchmark runtime");
            let handle = runtime.handle().clone();

            let cuda_ctx = Arc::new(CudaContext::new(0).expect("Failed to create CUDA context"));
            let stream = cuda_ctx.default_stream();
            let nixl_agent = Arc::new(None);

            Self {
                _runtime: runtime,
                handle,
                stream,
                nixl_agent,
            }
        }

        fn create_transfer_context(&self) -> context::v2::TransferContext {
            context::v2::TransferContext::new(
                self.nixl_agent.clone(),
                self.stream.clone(),
                self.handle.clone(),
            )
        }
    }

    /// Benchmark blocking synchronization in tight loop
    /// This measures the baseline performance of direct CUDA event sync
    fn bench_blocking(c: &mut Criterion) {
        let runtime = BenchmarkRuntime::new();
        let ctx = runtime.create_transfer_context();

        let mut group = c.benchmark_group("blocking_sync");
        group.warm_up_time(std::time::Duration::from_millis(500));
        group.measurement_time(std::time::Duration::from_secs(3));

        group.bench_function("sync", |b| {
            b.iter(|| {
                let event = ctx.record_event().unwrap();
                event.synchronize_blocking().unwrap();
            })
        });

        group.finish();
    }

    /// Benchmark single-threaded async synchronization
    /// This measures only the tokio spawn_blocking overhead vs direct blocking
    fn bench_async_single(c: &mut Criterion) {
        let runtime = BenchmarkRuntime::new();
        let ctx = runtime.create_transfer_context();

        let mut group = c.benchmark_group("async_sync");
        group.warm_up_time(std::time::Duration::from_millis(500));
        group.measurement_time(std::time::Duration::from_secs(3));

        group.bench_function("sync", |b| {
            b.iter(|| {
                runtime._runtime.block_on(async {
                    let event = ctx.record_event().unwrap();
                    event.synchronize().await.unwrap();
                })
            })
        });

        group.finish();
    }

    /// Benchmark concurrent async synchronization at different scales
    /// This shows where async becomes beneficial due to parallelism
    fn bench_concurrent_async(c: &mut Criterion) {
        let runtime = BenchmarkRuntime::new();
        let mut group = c.benchmark_group("concurrent_async");
        group.warm_up_time(std::time::Duration::from_millis(500));
        group.measurement_time(std::time::Duration::from_secs(3));

        // Test different concurrency levels
        for concurrency in [1, 5, 10, 25, 50, 100].iter() {
            group.bench_with_input(
                BenchmarkId::new("concurrent", concurrency),
                concurrency,
                |b, &concurrency| {
                    let ctx = runtime.create_transfer_context();
                    b.iter(|| {
                        runtime._runtime.block_on(async {
                            // Spawn concurrent tasks using TaskTracker
                            let tracker = TaskTracker::new();

                            for _ in 0..concurrency {
                                let ctx_clone = ctx.clone();
                                tracker.spawn(async move {
                                    let event = ctx_clone.record_event().unwrap();
                                    event.synchronize().await.unwrap();
                                });
                            }

                            // Wait for all tasks to complete
                            tracker.close();
                            tracker.wait().await;
                        });
                    });
                },
            );
        }

        group.finish();
    }

    /// Benchmark throughput: events per second at different concurrency levels
    fn bench_throughput(c: &mut Criterion) {
        let runtime = BenchmarkRuntime::new();
        let mut group = c.benchmark_group("throughput");
        group.sample_size(50); // Fewer samples for throughput tests
        group.warm_up_time(std::time::Duration::from_millis(500));
        group.measurement_time(std::time::Duration::from_secs(3));

        for concurrency in [1, 10, 50].iter() {
            let events_per_task = 10; // Process multiple events per task

            group.bench_with_input(
                BenchmarkId::new("events_per_sec", concurrency),
                concurrency,
                |b, &concurrency| {
                    let ctx = runtime.create_transfer_context();
                    b.iter(|| {
                        runtime._runtime.block_on(async {
                            let tracker = TaskTracker::new();

                            for _ in 0..concurrency {
                                let ctx_clone = ctx.clone();
                                tracker.spawn(async move {
                                    // Process multiple events per task
                                    for _ in 0..events_per_task {
                                        let event = ctx_clone.record_event().unwrap();
                                        event.synchronize().await.unwrap();
                                    }
                                });
                            }

                            tracker.close();
                            tracker.wait().await;
                        });
                    });
                },
            );
        }

        group.finish();
    }

    criterion_group!(
        benches,
        // Core comparison benchmarks
        bench_blocking,
        bench_async_single,
        // Concurrency benchmarks
        bench_concurrent_async,
        bench_throughput
    );
}

#[cfg(feature = "testing-cuda")]
criterion::criterion_main!(benchmarks::benches);

#[cfg(not(feature = "testing-cuda"))]
fn main() {
    println!(
        "Benchmarks require 'testing-cuda' feature. Run with: cargo bench --features testing-cuda"
    );
}