sim-lib-compute-rocm 0.2.0

Runtime-loaded ROCm/rocBLAS tensor compute site for SIM.
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Runtime ROCm/rocBLAS symbol discovery.

use std::{
    ffi::c_void,
    fmt,
    path::{Path, PathBuf},
    sync::Arc,
};

use libloading::Library;

const HIP_NAMES: &[&str] = &["libamdhip64.so.7", "libamdhip64.so.6", "libamdhip64.so"];
const ROCBLAS_NAMES: &[&str] = &[
    "librocblas.so.5",
    "librocblas.so.4",
    "librocblas.so.0",
    "librocblas.so",
];
const ROCBLASLT_NAMES: &[&str] = &["librocblaslt.so.0", "librocblaslt.so"];

const HIP_SYMBOLS: &[&str] = &[
    "hipInit",
    "hipRuntimeGetVersion",
    "hipGetDeviceCount",
    "hipMalloc",
    "hipFree",
    "hipMemcpy",
    "hipDeviceSynchronize",
];
const ROCBLAS_SYMBOLS: &[&str] = &[
    "rocblas_create_handle",
    "rocblas_destroy_handle",
    "rocblas_sgemm",
    "rocblas_gemm_ex",
];
const ROCBLASLT_SYMBOLS: &[&str] = &["rocblaslt_create_handle", "rocblaslt_destroy_handle"];

/// One validated runtime symbol.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RocmSymbolEvidence {
    /// Symbol name.
    pub name: String,
    /// Whether the dynamic library exported the symbol.
    pub present: bool,
}

/// Dynamic-library ABI evidence required by the ROCm provider.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RocmAbiEvidence {
    /// Loaded HIP runtime library path or platform name.
    pub hip_library: String,
    /// Loaded rocBLAS library path or platform name.
    pub rocblas_library: String,
    /// Loaded rocBLASLt library path or platform name, when present.
    pub rocblaslt_library: Option<String>,
    /// HIP runtime version when the runtime can report it.
    pub hip_runtime_version: Option<i32>,
    /// Observed AMD GPU ISA targets such as `gfx1103`.
    pub observed_gfx_targets: Vec<String>,
    /// Checked HIP runtime symbols.
    pub hip_symbols: Vec<RocmSymbolEvidence>,
    /// Checked rocBLAS symbols.
    pub rocblas_symbols: Vec<RocmSymbolEvidence>,
    /// Checked rocBLASLt symbols.
    pub rocblaslt_symbols: Vec<RocmSymbolEvidence>,
}

impl RocmAbiEvidence {
    /// Returns true when Linux, HIP, rocBLAS, and a concrete gfx target exist.
    pub fn is_complete(&self) -> bool {
        cfg!(target_os = "linux")
            && !self.observed_gfx_targets.is_empty()
            && self.hip_symbols.iter().all(|symbol| symbol.present)
            && self.rocblas_symbols.iter().all(|symbol| symbol.present)
    }
}

/// Loaded ROCm runtime libraries kept alive for function-pointer validity.
pub struct RocmLibrarySet {
    evidence: RocmAbiEvidence,
    hip: Library,
    rocblas: Library,
    rocblaslt: Option<Library>,
}

impl RocmLibrarySet {
    /// Joins capsule-loaded libraries to their validated ABI evidence.
    pub fn new(
        evidence: RocmAbiEvidence,
        hip: Library,
        rocblas: Library,
        rocblaslt: Option<Library>,
    ) -> Self {
        Self {
            evidence,
            hip,
            rocblas,
            rocblaslt,
        }
    }

    /// Returns checked ABI evidence.
    pub fn evidence(&self) -> &RocmAbiEvidence {
        &self.evidence
    }

    /// Returns loaded library handles to keep symbols alive.
    pub fn handles(&self) -> (&Library, &Library, Option<&Library>) {
        (&self.hip, &self.rocblas, self.rocblaslt.as_ref())
    }

    pub(crate) fn execution_handles(&self) -> (&Library, &Library) {
        (&self.hip, &self.rocblas)
    }
}

impl fmt::Debug for RocmLibrarySet {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RocmLibrarySet")
            .field("evidence", &self.evidence)
            .finish_non_exhaustive()
    }
}

/// Result of ROCm runtime discovery.
#[derive(Clone, Debug)]
pub struct RocmRuntimeProbe {
    /// Validated loaded runtime, when discovery succeeded.
    pub runtime: Option<Arc<RocmLibrarySet>>,
    /// ABI evidence from the successful runtime or the best failed probe.
    pub evidence: Option<RocmAbiEvidence>,
    /// Diagnostics collected while searching dynamic libraries.
    pub diagnostics: Vec<String>,
}

impl RocmRuntimeProbe {
    /// Builds a successful probe from validated evidence without library
    /// handles. This is intended for deterministic fake-loader tests.
    pub fn fake_present(evidence: RocmAbiEvidence) -> Self {
        Self {
            runtime: None,
            evidence: Some(evidence),
            diagnostics: Vec::new(),
        }
    }

    /// Returns true when discovery validated a usable ROCm provider.
    pub fn is_available(&self) -> bool {
        self.evidence
            .as_ref()
            .is_some_and(RocmAbiEvidence::is_complete)
    }
}

/// ROCm dynamic-loading failure.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RocmLoadError {
    /// Human-readable failure message.
    pub message: String,
}

impl fmt::Display for RocmLoadError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for RocmLoadError {}

/// Loader abstraction used by real and fake ROCm discovery.
pub trait DynamicRocmLoader {
    /// Performs ROCm runtime discovery.
    fn discover(&self) -> Result<RocmRuntimeProbe, RocmLoadError>;
}

/// Capsule membrane used by the provider to receive an explicit probe.
pub trait RocmProbePort {
    /// Returns a capsule-owned ROCm probe without ambient rediscovery.
    fn probe_rocm(&self) -> Result<RocmRuntimeProbe, RocmLoadError>;
}

impl<T: DynamicRocmLoader + ?Sized> RocmProbePort for T {
    fn probe_rocm(&self) -> Result<RocmRuntimeProbe, RocmLoadError> {
        self.discover()
    }
}

/// Real dynamic loader using platform ROCm shared libraries.
#[derive(Clone, Debug)]
pub struct RocmRuntimeLoader {
    search_dirs: Vec<PathBuf>,
    search_system: bool,
    observed_gfx_targets: Vec<String>,
}

impl Default for RocmRuntimeLoader {
    fn default() -> Self {
        Self {
            search_dirs: Vec::new(),
            search_system: true,
            observed_gfx_targets: Vec::new(),
        }
    }
}

impl RocmRuntimeLoader {
    /// Builds a loader that searches platform library paths.
    pub fn new() -> Self {
        Self::default()
    }

    /// Builds a loader that first searches explicit directories.
    pub fn with_search_dirs(search_dirs: Vec<PathBuf>) -> Self {
        Self {
            search_dirs,
            search_system: true,
            observed_gfx_targets: Vec::new(),
        }
    }

    /// Builds a loader restricted to explicit directories. This is used to
    /// prove fail-closed behavior when vendor libraries are unavailable.
    pub fn with_search_dirs_only(search_dirs: Vec<PathBuf>) -> Self {
        Self {
            search_dirs,
            search_system: false,
            observed_gfx_targets: Vec::new(),
        }
    }

    /// Supplies capsule-observed AMD targets without spawning a host tool.
    pub fn with_observed_gfx_targets(mut self, targets: Vec<String>) -> Self {
        self.observed_gfx_targets = targets;
        self
    }
}

impl DynamicRocmLoader for RocmRuntimeLoader {
    fn discover(&self) -> Result<RocmRuntimeProbe, RocmLoadError> {
        let mut diagnostics = Vec::new();
        if !cfg!(target_os = "linux") {
            return Err(RocmLoadError {
                message: "ROCm provider is supported only on Linux".to_owned(),
            });
        }
        let (hip_name, hip) = self.open_first(HIP_NAMES, &mut diagnostics)?;
        let (rocblas_name, rocblas) = self.open_first(ROCBLAS_NAMES, &mut diagnostics)?;
        let rocblaslt = self.open_first(ROCBLASLT_NAMES, &mut diagnostics).ok();

        let hip_symbols = symbol_evidence(&hip, HIP_SYMBOLS);
        let rocblas_symbols = symbol_evidence(&rocblas, ROCBLAS_SYMBOLS);
        let rocblaslt_symbols = rocblaslt
            .as_ref()
            .map(|(_, library)| symbol_evidence(library, ROCBLASLT_SYMBOLS))
            .unwrap_or_default();
        let hip_runtime_version = hip_runtime_version(&hip).ok();
        let observed_gfx_targets = self.observed_gfx_targets.clone();
        let evidence = RocmAbiEvidence {
            hip_library: hip_name,
            rocblas_library: rocblas_name,
            rocblaslt_library: rocblaslt.as_ref().map(|(name, _)| name.clone()),
            hip_runtime_version,
            observed_gfx_targets,
            hip_symbols,
            rocblas_symbols,
            rocblaslt_symbols,
        };
        if !evidence.is_complete() {
            return Ok(RocmRuntimeProbe {
                runtime: None,
                evidence: Some(evidence),
                diagnostics,
            });
        }
        let runtime = Arc::new(RocmLibrarySet::new(
            evidence.clone(),
            hip,
            rocblas,
            rocblaslt.map(|(_, library)| library),
        ));
        Ok(RocmRuntimeProbe {
            runtime: Some(runtime),
            evidence: Some(evidence),
            diagnostics,
        })
    }
}

impl RocmRuntimeLoader {
    fn open_first(
        &self,
        names: &[&str],
        diagnostics: &mut Vec<String>,
    ) -> Result<(String, Library), RocmLoadError> {
        for name in candidate_paths(&self.search_dirs, names, self.search_system) {
            match open_library(&name) {
                Ok(library) => return Ok((name.display().to_string(), library)),
                Err(error) => diagnostics.push(format!("{}: {error}", name.display())),
            }
        }
        Err(RocmLoadError {
            message: format!("ROCm library was not found; tried {}", names.join(", ")),
        })
    }
}

/// Fake loader for deterministic tests.
#[derive(Clone, Debug)]
pub struct FakeRocmLoader {
    probe: Result<RocmRuntimeProbe, RocmLoadError>,
}

impl FakeRocmLoader {
    /// Builds a fake loader that returns validated ROCm evidence.
    pub fn available() -> Self {
        Self {
            probe: Ok(RocmRuntimeProbe::fake_present(complete_fake_evidence())),
        }
    }

    /// Builds a fake loader with incomplete core HIP/rocBLAS ABI evidence.
    pub fn incomplete() -> Self {
        let mut evidence = complete_fake_evidence();
        if let Some(symbol) = evidence
            .rocblas_symbols
            .iter_mut()
            .find(|symbol| symbol.name == "rocblas_sgemm")
        {
            symbol.present = false;
        }
        Self {
            probe: Ok(RocmRuntimeProbe {
                runtime: None,
                evidence: Some(evidence),
                diagnostics: vec!["missing rocblas_sgemm".to_owned()],
            }),
        }
    }

    /// Builds a fake loader with missing optional rocBLASLt evidence.
    pub fn without_rocblaslt() -> Self {
        let mut evidence = complete_fake_evidence();
        if let Some(symbol) = evidence
            .rocblaslt_symbols
            .iter_mut()
            .find(|symbol| symbol.name == "rocblaslt_create_handle")
        {
            symbol.present = false;
        }
        Self {
            probe: Ok(RocmRuntimeProbe {
                runtime: None,
                evidence: Some(evidence),
                diagnostics: vec!["missing rocblaslt_create_handle".to_owned()],
            }),
        }
    }

    /// Builds a fake loader that reports ROCm as absent.
    pub fn absent() -> Self {
        Self {
            probe: Err(RocmLoadError {
                message: "ROCm runtime absent".to_owned(),
            }),
        }
    }
}

impl DynamicRocmLoader for FakeRocmLoader {
    fn discover(&self) -> Result<RocmRuntimeProbe, RocmLoadError> {
        self.probe.clone()
    }
}

/// Discovers ROCm using the real platform dynamic loader.
pub fn discover_rocm_runtime() -> Result<RocmRuntimeProbe, RocmLoadError> {
    RocmRuntimeLoader::new().discover()
}

fn complete_fake_evidence() -> RocmAbiEvidence {
    RocmAbiEvidence {
        hip_library: "fake-libamdhip64".to_owned(),
        rocblas_library: "fake-librocblas".to_owned(),
        rocblaslt_library: Some("fake-librocblaslt".to_owned()),
        hip_runtime_version: Some(6_300_000),
        observed_gfx_targets: vec!["gfx1103".to_owned()],
        hip_symbols: HIP_SYMBOLS
            .iter()
            .map(|name| RocmSymbolEvidence {
                name: (*name).to_owned(),
                present: true,
            })
            .collect(),
        rocblas_symbols: ROCBLAS_SYMBOLS
            .iter()
            .map(|name| RocmSymbolEvidence {
                name: (*name).to_owned(),
                present: true,
            })
            .collect(),
        rocblaslt_symbols: ROCBLASLT_SYMBOLS
            .iter()
            .map(|name| RocmSymbolEvidence {
                name: (*name).to_owned(),
                present: true,
            })
            .collect(),
    }
}

fn candidate_paths(search_dirs: &[PathBuf], names: &[&str], search_system: bool) -> Vec<PathBuf> {
    let mut candidates = Vec::new();
    for directory in search_dirs {
        for name in names {
            candidates.push(directory.join(name));
        }
    }
    if search_system {
        candidates.extend(names.iter().map(PathBuf::from));
    }
    candidates
}

fn symbol_evidence(library: &Library, names: &[&str]) -> Vec<RocmSymbolEvidence> {
    names
        .iter()
        .map(|name| RocmSymbolEvidence {
            name: (*name).to_owned(),
            present: symbol_present(library, name),
        })
        .collect()
}

fn open_library(path: &Path) -> Result<Library, libloading::Error> {
    // SAFETY: The handle remains owned by RocmLibrarySet while symbols are used.
    unsafe { Library::new(path) }
}

fn symbol_present(library: &Library, name: &str) -> bool {
    let mut bytes = name.as_bytes().to_vec();
    bytes.push(0);
    // SAFETY: The lookup only checks whether the library exports the named
    // symbol as an opaque address. The address is not called or dereferenced.
    unsafe { library.get::<*mut c_void>(&bytes).is_ok() }
}

fn hip_runtime_version(library: &Library) -> Result<i32, RocmLoadError> {
    type HipInit = unsafe extern "C" fn(u32) -> i32;
    type HipRuntimeGetVersion = unsafe extern "C" fn(*mut i32) -> i32;
    type HipGetDeviceCount = unsafe extern "C" fn(*mut i32) -> i32;
    // SAFETY: These are the documented HIP signatures. Pointers are initialized,
    // and only status 0 is accepted.
    unsafe {
        let hip_init = library
            .get::<HipInit>(b"hipInit\0")
            .map_err(|error| RocmLoadError {
                message: error.to_string(),
            })?;
        let get_version = library
            .get::<HipRuntimeGetVersion>(b"hipRuntimeGetVersion\0")
            .map_err(|error| RocmLoadError {
                message: error.to_string(),
            })?;
        let get_device_count = library
            .get::<HipGetDeviceCount>(b"hipGetDeviceCount\0")
            .map_err(|error| RocmLoadError {
                message: error.to_string(),
            })?;
        let init_status = hip_init(0);
        if init_status != 0 {
            return Err(RocmLoadError {
                message: format!("hipInit failed with status {init_status}"),
            });
        }
        let mut device_count = 0;
        let count_status = get_device_count(&mut device_count);
        if count_status != 0 || device_count <= 0 {
            return Err(RocmLoadError {
                message: format!("hipGetDeviceCount failed with status {count_status}"),
            });
        }
        let mut version = 0;
        let version_status = get_version(&mut version);
        if version_status != 0 {
            return Err(RocmLoadError {
                message: format!("hipRuntimeGetVersion failed with status {version_status}"),
            });
        }
        Ok(version)
    }
}