1use std::{cmp::Reverse, env, fs, path::Path, sync::Arc};
5
6pub use oxide_artifacts::{
7 ArtifactCompileOptions, ArtifactDebugPolicy, ArtifactEntryKind, ArtifactPayloadKind,
8 OwnedArtifactBundle, OwnedArtifactEntry, OwnedArtifactPayload,
9};
10
11use crate::{
12 context::Context,
13 device::DeviceAttribute,
14 error::{Error, Result, Status},
15 jit::JitOptions,
16 kernel::launch::{KernelSignature, PreparedLaunch},
17 module::{LaunchConfig, Module, ModuleImage},
18};
19
20#[derive(Debug, Clone)]
22pub struct ArtifactMetadata {
23 pub name: String,
25 pub target: String,
27 pub compile_options: ArtifactCompileOptions,
29 pub entries: Vec<OwnedArtifactEntry>,
31}
32
33impl ArtifactMetadata {
34 #[must_use]
36 pub fn from_bundle(bundle: &OwnedArtifactBundle) -> Self {
37 Self {
38 name: bundle.name.clone(),
39 target: bundle.target.clone(),
40 compile_options: bundle.compile_options,
41 entries: bundle.entries.clone(),
42 }
43 }
44
45 #[must_use]
47 pub fn entry(&self, symbol: &str) -> Option<&OwnedArtifactEntry> {
48 self.entries.iter().find(|entry| entry.symbol == symbol)
49 }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54#[non_exhaustive]
55pub enum ImageKind {
56 Ptx,
58 Cubin,
60 Fatbin,
62}
63
64#[derive(Debug, Clone)]
66pub struct PrecompiledImage<'a> {
67 pub kind: ImageKind,
69 pub image: ModuleImage<'a>,
71 pub metadata: ArtifactMetadata,
73}
74
75impl<'a> PrecompiledImage<'a> {
76 #[must_use]
80 pub fn new(kind: ImageKind, image: ModuleImage<'a>, metadata: ArtifactMetadata) -> Self {
81 Self {
82 kind,
83 image,
84 metadata,
85 }
86 }
87}
88
89#[derive(Debug)]
93pub struct ArtifactLibrary {
94 bundles: Vec<OwnedArtifactBundle>,
95}
96
97impl ArtifactLibrary {
98 #[must_use]
104 pub unsafe fn new(bundles: Vec<OwnedArtifactBundle>) -> Self {
105 Self { bundles }
106 }
107
108 pub fn from_current_exe() -> Result<Self> {
114 unsafe { Self::from_binary_path(env::current_exe()?) }
116 }
117
118 pub unsafe fn from_binary_path(path: impl AsRef<Path>) -> Result<Self> {
128 unsafe { Self::from_binary_bytes(&fs::read(path)?) }
130 }
131
132 pub unsafe fn from_binary_bytes(bytes: &[u8]) -> Result<Self> {
145 let bundles = oxide_artifacts::read_artifact_bundles_from_object_bytes(bytes)?;
146 Ok(unsafe { Self::new(bundles) })
148 }
149
150 pub unsafe fn from_section(bytes: &[u8]) -> Result<Self> {
163 let bundles = oxide_artifacts::parse_artifact_section(bytes)?
164 .into_iter()
165 .map(Into::into)
166 .collect();
167 Ok(unsafe { Self::new(bundles) })
169 }
170
171 #[must_use]
173 pub fn bundles(&self) -> &[OwnedArtifactBundle] {
174 &self.bundles
175 }
176
177 pub fn load(&self, context: &Arc<Context>, name: &str) -> Result<Module> {
187 let capability = capability(context)?;
188 let mut candidates = Vec::new();
189 for bundle in self.bundles.iter().filter(|bundle| bundle.name == name) {
190 let Some(target) = Target::parse(&bundle.target) else {
191 continue;
192 };
193 for payload in &bundle.payloads {
194 let kind = match payload.kind {
195 ArtifactPayloadKind::Ptx => ImageKind::Ptx,
196 ArtifactPayloadKind::Cubin => ImageKind::Cubin,
197 _ => continue,
198 };
199 if target.is_candidate(capability, kind) {
200 let score = (
201 u8::from(kind == ImageKind::Cubin),
202 target.capability,
203 target.specificity(),
204 );
205 candidates.push((score, bundle, payload, kind));
206 }
207 }
208 }
209
210 candidates.sort_by_key(|(score, ..)| Reverse(*score));
211 let mut last_error = None;
212 for (_, bundle, payload, kind) in candidates {
213 let image = match kind {
214 ImageKind::Ptx => ModuleImage::from_ptx(&payload.bytes[..])?,
215 _ => unsafe { ModuleImage::from_bytes_unchecked(&payload.bytes[..]) },
217 };
218
219 let image = PrecompiledImage::new(kind, image, ArtifactMetadata::from_bundle(bundle));
220 match context.load_precompiled(&image) {
221 Ok(module) => return Ok(module),
222 Err(error) if can_try_next_image(&error) => last_error = Some(error),
223 Err(error) => return Err(error),
224 }
225 }
226 Err(last_error.unwrap_or_else(|| Error::NoCompatibleArtifact {
227 name: name.to_owned().into(),
228 major: capability.0,
229 minor: capability.1,
230 }))
231 }
232}
233
234fn capability(context: &Context) -> Result<(u32, u32)> {
235 let major = context
236 .device()
237 .attribute(DeviceAttribute::ComputeCapabilityMajor)?;
238 let minor = context
239 .device()
240 .attribute(DeviceAttribute::ComputeCapabilityMinor)?;
241 Ok((
242 u32::try_from(major).map_err(|_| Error::out_of_range("compute capability major"))?,
243 u32::try_from(minor).map_err(|_| Error::out_of_range("compute capability minor"))?,
244 ))
245}
246
247#[derive(Debug, Clone, Copy)]
248struct Target {
249 capability: (u32, u32),
250 suffix: Option<char>,
251}
252
253impl Target {
254 fn parse(target: &str) -> Option<Self> {
255 let target = target
256 .strip_prefix("sm_")
257 .or_else(|| target.strip_prefix("compute_"))?;
258 let digits = target.trim_end_matches(['a', 'f']);
259 if digits.is_empty() || !digits.bytes().all(|digit| digit.is_ascii_digit()) {
260 return None;
261 }
262
263 let code: u32 = digits.parse().ok()?;
264 let suffix = match &target[digits.len()..] {
265 "" => None,
266 "a" => Some('a'),
267 "f" => Some('f'),
268 _ => return None,
269 };
270 Some(Self {
271 capability: (code / 10, code % 10),
272 suffix,
273 })
274 }
275
276 fn is_candidate(self, device: (u32, u32), kind: ImageKind) -> bool {
277 match self.suffix {
278 Some('a') => self.capability == device,
279 Some('f') => self.capability.0 == device.0 && self.capability <= device,
280 _ => {
281 self.capability <= device
282 && (kind == ImageKind::Ptx || self.capability.0 == device.0)
283 }
284 }
285 }
286
287 fn specificity(self) -> u8 {
288 match self.suffix {
289 Some('a') => 2,
290 Some('f') => 1,
291 _ => 0,
292 }
293 }
294}
295
296fn can_try_next_image(error: &Error) -> bool {
297 match error {
298 Error::Cuda {
299 code:
300 Status::InvalidImage
301 | Status::InvalidPtx
302 | Status::NoBinaryForGpu
303 | Status::UnsupportedPtxVersion,
304 } => true,
305 #[cfg(feature = "nvjitlink_13_4")]
306 Error::NvJitLink { code, .. } => {
307 use crate::nvjitlink::Status as LinkStatus;
308 matches!(
309 code,
310 LinkStatus::InvalidInput
311 | LinkStatus::UnrecognizedInput
312 | LinkStatus::IncorrectInputType
313 | LinkStatus::PtxCompile
314 | LinkStatus::ArchMismatch
315 | LinkStatus::UnsupportedArch
316 | LinkStatus::UnrecognizedArch
317 | LinkStatus::OutdatedLibrary
318 )
319 }
320 Error::UnsupportedArchitecture { .. } => true,
321 _ => false,
322 }
323}
324
325impl Context {
326 pub fn load_precompiled(self: &Arc<Self>, image: &PrecompiledImage<'_>) -> Result<Module> {
336 let policy = image.metadata.compile_options;
337 if image.kind == ImageKind::Ptx && policy != ArtifactCompileOptions::default() {
338 load_with_policy(self, image, image.image.as_bytes())
339 } else {
340 self.load_module_with_metadata(
341 &image.image,
342 JitOptions::default(),
343 Some(Arc::new(image.metadata.clone())),
344 )
345 }
346 }
347}
348
349#[cfg(feature = "nvjitlink_13_4")]
350fn load_with_policy(
351 context: &Arc<Context>,
352 image: &PrecompiledImage<'_>,
353 bytes: &[u8],
354) -> Result<Module> {
355 use crate::{
356 architecture::GpuArchitecture,
357 nvjitlink::{InputType, LinkOptions, Linker},
358 };
359 let (major, minor) = capability(context)?;
360 let suffix = Target::parse(&image.metadata.target)
361 .and_then(|target| target.suffix)
362 .map_or(String::new(), |suffix| suffix.to_string());
363 let architecture: GpuArchitecture = format!("sm_{major}{minor}{suffix}").parse()?;
364 let mut options = LinkOptions::new(architecture);
365 let policy = image.metadata.compile_options;
366 options.raw_options.push(format!(
367 "-fma={}",
368 u8::from(policy.fma_contraction_enabled())
369 ));
370 match policy.debug_policy() {
371 ArtifactDebugPolicy::None => (),
372 ArtifactDebugPolicy::LineTables => options.line_info = true,
373 ArtifactDebugPolicy::Full => options.raw_options.push("-g".into()),
374 }
375
376 let mut linker = Linker::create(options)?;
377 linker.add_data(InputType::Ptx, bytes, &image.metadata.name)?;
378 let binary = linker.complete()?;
379 context.load_module_with_metadata(
380 &ModuleImage::from_compiler_output(binary.as_bytes())?,
381 JitOptions::default(),
382 Some(Arc::new(image.metadata.clone())),
383 )
384}
385
386#[cfg(not(feature = "nvjitlink_13_4"))]
387fn load_with_policy(_: &Arc<Context>, _: &PrecompiledImage<'_>, _: &[u8]) -> Result<Module> {
388 Err(Error::Compiler {
389 message: "artifact compile policy requires the nvjitlink_13_4 feature".into(),
390 })
391}
392
393impl Module {
394 #[must_use]
396 pub fn artifact_metadata(&self) -> Option<&ArtifactMetadata> {
397 self.inner.artifact_metadata.as_deref()
398 }
399
400 pub unsafe fn prepare<K: KernelSignature>(
412 &self,
413 symbol: &str,
414 config: LaunchConfig,
415 ) -> Result<PreparedLaunch<K>> {
416 unsafe { PreparedLaunch::create(&self.function(symbol)?, config) }
418 }
419}