Skip to main content

singe_cuda/module/
artifact.rs

1//! Discovery and selection of producer-authored embedded artifact bundles.
2//! Loading and typed preparation reuse the ordinary context, module and kernel APIs.
3
4use 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/// Original producer metadata retained by the native module and its prepared functions.
21#[derive(Debug, Clone)]
22pub struct ArtifactMetadata {
23    /// Producer-assigned artifact bundle name.
24    pub name: String,
25    /// Producer target string, such as `sm_90` or `compute_90`.
26    pub target: String,
27    /// Producer compilation policy, including FMA contraction and debug information.
28    pub compile_options: ArtifactCompileOptions,
29    /// Producer-declared kernel symbols and their entry metadata.
30    pub entries: Vec<OwnedArtifactEntry>,
31}
32
33impl ArtifactMetadata {
34    /// Copies the bundle's producer metadata without retaining its code payloads.
35    #[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    /// Returns the first producer entry whose symbol equals `symbol`, or `None` if no entry matches.
46    #[must_use]
47    pub fn entry(&self, symbol: &str) -> Option<&OwnedArtifactEntry> {
48        self.entries.iter().find(|entry| entry.symbol == symbol)
49    }
50}
51
52/// Device-code format of a precompiled image.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54#[non_exhaustive]
55pub enum ImageKind {
56    /// PTX assembly, finalized by the driver or native linker before execution.
57    Ptx,
58    /// A compiled CUDA device binary.
59    Cubin,
60    /// A CUDA fat binary containing one or more device-code images.
61    Fatbin,
62}
63
64/// Precompiled bytes and producer metadata, using the existing module-image storage.
65#[derive(Debug, Clone)]
66pub struct PrecompiledImage<'a> {
67    /// Declared device-code format of `image`.
68    pub kind: ImageKind,
69    /// Borrowed or owned precompiled device-code bytes.
70    pub image: ModuleImage<'a>,
71    /// Producer compilation policy and entry descriptions retained with the loaded module.
72    pub metadata: ArtifactMetadata,
73}
74
75impl<'a> PrecompiledImage<'a> {
76    /// Combines the image bytes, declared format, and producer metadata.
77    ///
78    /// The image's constructor established that its bytes are loadable; `kind` is not checked against them.
79    #[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/// Owned producer artifact bundles discovered in a host object file or artifact section.
90///
91/// Loading selects candidate PTX or cubin payloads for a context's device and retains the selected bundle's producer metadata with the module.
92#[derive(Debug)]
93pub struct ArtifactLibrary {
94    bundles: Vec<OwnedArtifactBundle>,
95}
96
97impl ArtifactLibrary {
98    /// Stores the supplied artifact bundles without parsing or validating their payloads.
99    ///
100    /// # Safety
101    ///
102    /// Every cubin payload must be a complete device binary whose headers describe sizes and offsets within its bytes, since [`Self::load`] passes it to CUDA's length-less loader.
103    #[must_use]
104    pub unsafe fn new(bundles: Vec<OwnedArtifactBundle>) -> Self {
105        Self { bundles }
106    }
107
108    /// Reads embedded artifact bundles from the current executable.
109    ///
110    /// # Errors
111    ///
112    /// Returns an error if the current executable path cannot be determined, its contents cannot be read, or object-file or artifact-section parsing fails.
113    pub fn from_current_exe() -> Result<Self> {
114        // SAFETY: the producer embedded these payloads when it built the running executable, whose code the process already trusts.
115        unsafe { Self::from_binary_path(env::current_exe()?) }
116    }
117
118    /// Reads embedded artifact bundles from the host object file at `path`.
119    ///
120    /// # Safety
121    ///
122    /// The same as [`Self::new`], for every cubin payload embedded in the file.
123    ///
124    /// # Errors
125    ///
126    /// Returns an error if the file cannot be read or its object-file or artifact-section contents cannot be parsed.
127    pub unsafe fn from_binary_path(path: impl AsRef<Path>) -> Result<Self> {
128        // SAFETY: the caller vouches for the payloads embedded in the file.
129        unsafe { Self::from_binary_bytes(&fs::read(path)?) }
130    }
131
132    /// Reads artifact bundles from the embedded `.oxart` sections of a host object image.
133    ///
134    /// A valid object without artifact sections produces an empty library.
135    /// Returned bundles own their metadata and payload bytes.
136    ///
137    /// # Safety
138    ///
139    /// The same as [`Self::new`], for every cubin payload embedded in `bytes`.
140    ///
141    /// # Errors
142    ///
143    /// Returns an error if the object file, a section name or contents, or an embedded artifact bundle cannot be parsed.
144    pub unsafe fn from_binary_bytes(bytes: &[u8]) -> Result<Self> {
145        let bundles = oxide_artifacts::read_artifact_bundles_from_object_bytes(bytes)?;
146        // SAFETY: the caller vouches for the payloads embedded in `bytes`.
147        Ok(unsafe { Self::new(bundles) })
148    }
149
150    /// Parses artifact bundles from the contents of an artifact section.
151    ///
152    /// Accepts concatenated bundles and trailing zero padding.
153    /// Returned bundles own their metadata and payload bytes.
154    ///
155    /// # Safety
156    ///
157    /// The same as [`Self::new`], for every cubin payload in `bytes`.
158    ///
159    /// # Errors
160    ///
161    /// Returns an error for malformed or truncated bundle data, unsupported artifact versions, invalid metadata, or invalid payload descriptions.
162    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        // SAFETY: the caller vouches for the payloads in `bytes`.
168        Ok(unsafe { Self::new(bundles) })
169    }
170
171    /// Borrows all stored bundles in their discovery order.
172    #[must_use]
173    pub fn bundles(&self) -> &[OwnedArtifactBundle] {
174        &self.bundles
175    }
176
177    /// Tries native binaries before PTX, preferring newer and more specific targets.
178    /// Target metadata only filters candidates; CUDA and nvJitLink determine image compatibility.
179    ///
180    /// # Errors
181    ///
182    /// Returns an error if the device compute capability cannot be queried or converted.
183    /// Returns `Error::NoCompatibleArtifact` if no named bundle has an eligible PTX or cubin payload.
184    /// Image-compatibility failures try the next candidate; if every candidate fails, the last such error is returned.
185    /// Other loading or policy-finalization failures return immediately.
186    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                // SAFETY: the library's constructor vouched for every cubin payload, and `kind` is cubin only for cubin payloads.
216                _ => 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    /// Loads a precompiled image while preserving producer policy and entry metadata.
327    /// PTX policies requiring finalization use the existing nvJitLink integration.
328    /// CUBIN and executable fatbin policies describe compilation already performed by the producer.
329    ///
330    /// # Errors
331    ///
332    /// Propagates context binding and module loading errors.
333    /// PTX with a nondefault compilation policy requires `nvjitlink_13_4`; without it, returns `Error::Compiler`.
334    /// With the feature enabled, device capability queries, target architecture parsing, native linker creation or finalization, and artifact-name conversion can also fail.
335    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    /// Returns the retained producer metadata, or `None` for modules loaded without it.
395    #[must_use]
396    pub fn artifact_metadata(&self) -> Option<&ArtifactMetadata> {
397        self.inner.artifact_metadata.as_deref()
398    }
399
400    /// Binds an existing image entry to the ordinary typed launch contract.
401    ///
402    /// # Safety
403    ///
404    /// `K` must describe this symbol's ABI, indexing and semantic requirements.
405    /// Producer entry metadata does not prove field layout, bounds, initialization or alias permission.
406    ///
407    /// # Errors
408    ///
409    /// Propagates errors from looking up `symbol` and validating the typed launch.
410    /// Validation can fail if native parameter sizes or offsets disagree with `K`, parameter layout overflows, the launch violates the signature's requirements or device limits, or CUDA cannot query the required kernel or device attributes.
411    pub unsafe fn prepare<K: KernelSignature>(
412        &self,
413        symbol: &str,
414        config: LaunchConfig,
415    ) -> Result<PreparedLaunch<K>> {
416        // SAFETY: the function is `symbol` from this module, and the caller guarantees `K` describes its ABI and semantics, which `PreparedLaunch::create` requires.
417        unsafe { PreparedLaunch::create(&self.function(symbol)?, config) }
418    }
419}