aprender-cupti 0.31.1

Rust bindings for NVIDIA CUPTI profiling - ComputeBrick analysis
Documentation
1
2
3
4
5
6
7
8
9
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Callback API for real-time CUDA event notifications.
//!
//! The callback API provides synchronous notifications of CUDA runtime and
//! driver API calls, enabling real-time monitoring and debugging.

use crate::error::CuptiResult;
use std::ffi::c_void;

/// Domain for callback subscriptions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CallbackDomain {
    /// CUDA Runtime API callbacks
    RuntimeApi,
    /// CUDA Driver API callbacks
    DriverApi,
    /// Resource tracking callbacks
    Resource,
    /// Synchronization callbacks
    Synchronize,
    /// NVTX (NVIDIA Tools Extension) callbacks
    Nvtx,
}

impl CallbackDomain {
    /// Get CUPTI domain ID.
    pub fn cupti_id(&self) -> u32 {
        match self {
            CallbackDomain::RuntimeApi => 1,
            CallbackDomain::DriverApi => 2,
            CallbackDomain::Resource => 3,
            CallbackDomain::Synchronize => 4,
            CallbackDomain::Nvtx => 5,
        }
    }
}

/// Callback identifier for specific API calls.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CallbackId {
    // Runtime API
    /// cudaMalloc
    CudaMalloc,
    /// cudaFree
    CudaFree,
    /// cudaMemcpy
    CudaMemcpy,
    /// cudaMemcpyAsync
    CudaMemcpyAsync,
    /// cudaLaunchKernel
    CudaLaunchKernel,
    /// cudaDeviceSynchronize
    CudaDeviceSynchronize,
    /// cudaStreamSynchronize
    CudaStreamSynchronize,

    // Driver API
    /// cuMemAlloc
    CuMemAlloc,
    /// cuMemFree
    CuMemFree,
    /// cuLaunchKernel
    CuLaunchKernel,
    /// cuCtxSynchronize
    CuCtxSynchronize,

    // Resource
    /// Context creation
    ContextCreated,
    /// Context destruction
    ContextDestroyed,
    /// Stream creation
    StreamCreated,
    /// Stream destruction
    StreamDestroyed,
    /// Module load
    ModuleLoaded,
    /// Module unload
    ModuleUnloaded,

    /// Custom/other callback
    Other(u32),
}

impl CallbackId {
    /// Get CUPTI callback ID.
    pub fn cupti_id(&self) -> u32 {
        match self {
            CallbackId::CudaMalloc => 1,
            CallbackId::CudaFree => 2,
            CallbackId::CudaMemcpy => 3,
            CallbackId::CudaMemcpyAsync => 4,
            CallbackId::CudaLaunchKernel => 5,
            CallbackId::CudaDeviceSynchronize => 6,
            CallbackId::CudaStreamSynchronize => 7,
            CallbackId::CuMemAlloc => 100,
            CallbackId::CuMemFree => 101,
            CallbackId::CuLaunchKernel => 102,
            CallbackId::CuCtxSynchronize => 103,
            CallbackId::ContextCreated => 200,
            CallbackId::ContextDestroyed => 201,
            CallbackId::StreamCreated => 202,
            CallbackId::StreamDestroyed => 203,
            CallbackId::ModuleLoaded => 204,
            CallbackId::ModuleUnloaded => 205,
            CallbackId::Other(id) => *id,
        }
    }
}

/// When the callback is invoked relative to the API call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallbackSite {
    /// Before API call executes
    Enter,
    /// After API call completes
    Exit,
}

/// Data passed to a callback function.
#[derive(Debug)]
pub struct CallbackData {
    /// Domain of the callback
    pub domain: CallbackDomain,
    /// Callback ID
    pub callback_id: CallbackId,
    /// Entry or exit point
    pub site: CallbackSite,
    /// Correlation ID to match enter/exit
    pub correlation_id: u64,
    /// Context handle (if applicable)
    pub context: Option<u64>,
    /// Function name (if available)
    pub function_name: Option<String>,
    /// Return value (for exit callbacks)
    pub return_value: Option<i32>,
}

/// Callback function type.
pub type CallbackFn = Box<dyn Fn(&CallbackData) + Send + Sync>;

/// Subscriber for callback events.
pub struct CallbackSubscriber {
    /// Unique subscriber ID
    id: u64,
    /// Registered callbacks by domain
    callbacks: Vec<(CallbackDomain, Option<CallbackId>, CallbackFn)>,
    /// Whether the subscriber is active
    active: bool,
}

impl CallbackSubscriber {
    /// Create a new callback subscriber.
    pub fn new() -> Self {
        static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
        Self {
            id: NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
            callbacks: Vec::new(),
            active: false,
        }
    }

    /// Get subscriber ID.
    pub fn id(&self) -> u64 {
        self.id
    }

    /// Subscribe to all callbacks in a domain.
    pub fn subscribe_domain<F>(&mut self, domain: CallbackDomain, callback: F) -> CuptiResult<()>
    where
        F: Fn(&CallbackData) + Send + Sync + 'static,
    {
        self.callbacks.push((domain, None, Box::new(callback)));
        Ok(())
    }

    /// Subscribe to a specific callback.
    pub fn subscribe<F>(
        &mut self,
        domain: CallbackDomain,
        callback_id: CallbackId,
        callback: F,
    ) -> CuptiResult<()>
    where
        F: Fn(&CallbackData) + Send + Sync + 'static,
    {
        self.callbacks
            .push((domain, Some(callback_id), Box::new(callback)));
        Ok(())
    }

    /// Enable the subscriber (start receiving callbacks).
    pub fn enable(&mut self) -> CuptiResult<()> {
        self.active = true;
        // In real implementation: cuptiEnableCallback for each subscription
        Ok(())
    }

    /// Disable the subscriber (stop receiving callbacks).
    pub fn disable(&mut self) -> CuptiResult<()> {
        self.active = false;
        // In real implementation: cuptiDisableCallback
        Ok(())
    }

    /// Check if subscriber is active.
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Internal: dispatch callback to registered handlers.
    #[doc(hidden)]
    pub fn dispatch(&self, data: &CallbackData) {
        if !self.active {
            return;
        }

        for (domain, callback_id, handler) in &self.callbacks {
            if *domain == data.domain {
                match callback_id {
                    None => handler(data),
                    Some(id) if *id == data.callback_id => handler(data),
                    _ => {}
                }
            }
        }
    }
}

impl Default for CallbackSubscriber {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for creating callback subscriptions.
#[derive(Default)]
pub struct CallbackBuilder {
    subscriptions: Vec<(CallbackDomain, Option<CallbackId>)>,
}

impl CallbackBuilder {
    /// Create a new callback builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Subscribe to kernel launches.
    #[must_use]
    pub fn on_kernel_launch(mut self) -> Self {
        self.subscriptions.push((
            CallbackDomain::RuntimeApi,
            Some(CallbackId::CudaLaunchKernel),
        ));
        self.subscriptions
            .push((CallbackDomain::DriverApi, Some(CallbackId::CuLaunchKernel)));
        self
    }

    /// Subscribe to memory operations.
    #[must_use]
    pub fn on_memory_ops(mut self) -> Self {
        self.subscriptions
            .push((CallbackDomain::RuntimeApi, Some(CallbackId::CudaMalloc)));
        self.subscriptions
            .push((CallbackDomain::RuntimeApi, Some(CallbackId::CudaFree)));
        self.subscriptions
            .push((CallbackDomain::RuntimeApi, Some(CallbackId::CudaMemcpy)));
        self
    }

    /// Subscribe to synchronization events.
    #[must_use]
    pub fn on_synchronization(mut self) -> Self {
        self.subscriptions.push((CallbackDomain::Synchronize, None));
        self
    }

    /// Subscribe to all runtime API calls.
    #[must_use]
    pub fn on_runtime_api(mut self) -> Self {
        self.subscriptions.push((CallbackDomain::RuntimeApi, None));
        self
    }

    /// Subscribe to all driver API calls.
    #[must_use]
    pub fn on_driver_api(mut self) -> Self {
        self.subscriptions.push((CallbackDomain::DriverApi, None));
        self
    }

    /// Build the subscriber with the given handler.
    pub fn build<F>(self, handler: F) -> CuptiResult<CallbackSubscriber>
    where
        F: Fn(&CallbackData) + Send + Sync + Clone + 'static,
    {
        let mut subscriber = CallbackSubscriber::new();
        for (domain, callback_id) in self.subscriptions {
            let h = handler.clone();
            match callback_id {
                Some(id) => subscriber.subscribe(domain, id, h)?,
                None => subscriber.subscribe_domain(domain, h)?,
            }
        }
        Ok(subscriber)
    }
}

/// Raw callback function pointer type (for FFI).
pub type RawCallbackFn = unsafe extern "C" fn(
    user_data: *mut c_void,
    domain: u32,
    callback_id: u32,
    callback_data: *const c_void,
);

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::sync::Arc;

    #[test]
    fn test_callback_domain_id() {
        assert_eq!(CallbackDomain::RuntimeApi.cupti_id(), 1);
        assert_eq!(CallbackDomain::DriverApi.cupti_id(), 2);
    }

    #[test]
    fn test_callback_subscriber() {
        let mut subscriber = CallbackSubscriber::new();
        assert!(!subscriber.is_active());

        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        subscriber
            .subscribe_domain(CallbackDomain::RuntimeApi, move |_data| {
                counter_clone.fetch_add(1, Ordering::SeqCst);
            })
            .unwrap();

        subscriber.enable().unwrap();
        assert!(subscriber.is_active());

        // Simulate callback
        let data = CallbackData {
            domain: CallbackDomain::RuntimeApi,
            callback_id: CallbackId::CudaMalloc,
            site: CallbackSite::Enter,
            correlation_id: 1,
            context: None,
            function_name: Some("cudaMalloc".to_string()),
            return_value: None,
        };

        subscriber.dispatch(&data);
        assert_eq!(counter.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_callback_builder() {
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        let subscriber = CallbackBuilder::new()
            .on_kernel_launch()
            .on_memory_ops()
            .build(move |_data| {
                counter_clone.fetch_add(1, Ordering::SeqCst);
            })
            .unwrap();

        // Has subscriptions but not active yet
        assert!(!subscriber.is_active());
    }

    #[test]
    fn test_callback_filtering() {
        let mut subscriber = CallbackSubscriber::new();
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        // Only subscribe to CudaMalloc
        subscriber
            .subscribe(
                CallbackDomain::RuntimeApi,
                CallbackId::CudaMalloc,
                move |_data| {
                    counter_clone.fetch_add(1, Ordering::SeqCst);
                },
            )
            .unwrap();

        subscriber.enable().unwrap();

        // CudaMalloc should trigger
        let malloc_data = CallbackData {
            domain: CallbackDomain::RuntimeApi,
            callback_id: CallbackId::CudaMalloc,
            site: CallbackSite::Enter,
            correlation_id: 1,
            context: None,
            function_name: None,
            return_value: None,
        };
        subscriber.dispatch(&malloc_data);
        assert_eq!(counter.load(Ordering::SeqCst), 1);

        // CudaFree should NOT trigger
        let free_data = CallbackData {
            domain: CallbackDomain::RuntimeApi,
            callback_id: CallbackId::CudaFree,
            site: CallbackSite::Enter,
            correlation_id: 2,
            context: None,
            function_name: None,
            return_value: None,
        };
        subscriber.dispatch(&free_data);
        assert_eq!(counter.load(Ordering::SeqCst), 1); // Still 1
    }
}