Skip to main content

virtio_accel_coreml/
lib.rs

1//! Core ML host backend for GPU and Apple Neural Engine capable Macs.
2//!
3//! The production path accepts device-neutral TOSA 1.0 FlatBuffers, validates and analyzes them
4//! with `virtio-accel-tosa`, and lowers supported static floating-point and exact INT8 graphs
5//! inside this host-native crate. Core ML models use an explicit CPU-and-accelerator policy:
6//! `CPUAndNeuralEngine` by default, `CPUAndGPU`, or `All` when requested. All permit CPU
7//! participation. FP32 NeuralNetwork graphs exclude ANE to preserve their precision.
8//! Program buffers are page-aligned allocations wrapped directly by `MLMultiArray`;
9//! output execution is accepted only when Core ML uses the same allocation as its output backing.
10
11#![cfg_attr(not(target_os = "macos"), forbid(unsafe_code))]
12
13mod artifact;
14mod fp8;
15mod lower;
16mod mlprogram;
17pub use fp8::{
18    COREML_TOSA_FP8_CAPABILITY, COREML_TOSA_FP8_TARGET, COREML_TOSA_QUANTIZED_CAPABILITY,
19    COREML_TOSA_QUANTIZED_TARGET,
20};
21
22pub use artifact::{ArtifactBuildError, CoreMlArtifact, FeatureRole};
23pub use lower::{
24    COREML_TOSA_CAPABILITY, COREML_TOSA_TARGET, LoweringError, supports_tosa_dtype,
25    supports_tosa_operator,
26};
27pub use mlprogram::{COREML_TOSA_INTEGER_CAPABILITY, COREML_TOSA_INTEGER_TARGET};
28
29use virtio_accel_tosa::CapabilityDescriptor;
30#[cfg(not(target_os = "macos"))]
31use virtio_accel_tosa::TosaCapabilityProvider;
32
33#[cfg(target_os = "macos")]
34const FLOAT_CAPABILITIES: &[CapabilityDescriptor] = &[COREML_TOSA_CAPABILITY];
35#[cfg(target_os = "macos")]
36const ALL_CAPABILITIES: &[CapabilityDescriptor] = &[
37    COREML_TOSA_CAPABILITY,
38    COREML_TOSA_INTEGER_CAPABILITY,
39    COREML_TOSA_FP8_CAPABILITY,
40    COREML_TOSA_QUANTIZED_CAPABILITY,
41];
42#[cfg(not(target_os = "macos"))]
43const NO_CAPABILITIES: &[CapabilityDescriptor] = &[];
44
45use virtio_accel_core::{ArtifactFormat, TargetIdentity};
46
47/// Provider artifact format for [`CoreMlArtifact`].
48pub const ARTIFACT_FORMAT: ArtifactFormat = match ArtifactFormat::new(0x434d_4c50) {
49    Some(format) => format,
50    None => panic!("Core ML artifact format must be nonzero"),
51};
52
53/// Core ML path-artifact ABI v1 targeting CPU plus Apple Neural Engine execution.
54pub const TARGET_IDENTITY: TargetIdentity = TargetIdentity([
55    0x434f_5245,
56    0x4d4c_0001,
57    0x414e_4503,
58    0x4d41_434f,
59    0x000e_0000,
60    0,
61    0,
62    0,
63    0,
64    0,
65    0,
66    0,
67]);
68
69/// The Core ML runtime does not publish a finite upper bound for model residency.
70///
71/// Requiring the maximal charge makes the provider promise truthful: a process cannot retain
72/// `u64::MAX` bytes for one model. Device integrations must set their aggregate program-residency
73/// policy accordingly when admitting a Core ML program.
74pub const REQUIRED_RESIDENT_BYTES: u64 = u64::MAX;
75
76/// Explicit Core ML placement policy. All policies permit CPU participation;
77/// none promises exclusive or simultaneous execution on the selected accelerators.
78#[repr(u32)]
79#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
80pub enum CoreMlComputeUnits {
81    /// CPU and Neural Engine; excludes GPU execution. The compatibility default.
82    #[default]
83    CpuAndNeuralEngine = 0,
84    /// CPU and GPU; excludes Neural Engine execution.
85    CpuAndGpu = 1,
86    /// CPU, GPU and Neural Engine; Core ML chooses placement within the allowed set.
87    All = 2,
88}
89
90impl CoreMlComputeUnits {
91    // NeuralNetwork models do not carry typed intermediates: ANE may narrow FP32
92    // arithmetic. Keep FP32 programs within a precision-preserving subset of the
93    // explicitly selected policy. This is load-time placement, never a retry.
94    #[cfg(target_os = "macos")]
95    fn native_policy(self, requires_fp32: bool) -> u32 {
96        match (self, requires_fp32) {
97            (Self::CpuAndNeuralEngine, true) => 3, // private bridge CPUOnly
98            (Self::All, true) => Self::CpuAndGpu as u32,
99            _ => self as u32,
100        }
101    }
102}
103
104/// Failure to initialize a Core ML backend instance.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub enum InitError {
107    /// The backend is only executable on macOS 14 or newer.
108    UnsupportedPlatform,
109    /// The configured model root is missing, not a directory, or not representable as UTF-8.
110    InvalidModelRoot,
111    /// Core ML does not report an accessible Apple Neural Engine.
112    NeuralEngineUnavailable,
113    /// Core ML does not report an accessible GPU.
114    GpuUnavailable,
115}
116
117impl std::fmt::Display for InitError {
118    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        write!(formatter, "{self:?}")
120    }
121}
122
123impl std::error::Error for InitError {}
124
125#[cfg(target_os = "macos")]
126mod macos;
127#[cfg(target_os = "macos")]
128pub use macos::{
129    CoreMlAccelerator, CoreMlBuffer, CoreMlContext, CoreMlEvent, CoreMlProgram, CoreMlQueue,
130};
131
132/// Non-macOS placeholder that keeps workspace consumers portable.
133#[cfg(not(target_os = "macos"))]
134#[derive(Clone, Copy, Debug, Default)]
135pub struct CoreMlAccelerator;
136
137#[cfg(not(target_os = "macos"))]
138impl CoreMlAccelerator {
139    /// Report that Core ML is unavailable on this target.
140    pub fn new(_model_root: impl AsRef<std::path::Path>) -> Result<Self, InitError> {
141        Err(InitError::UnsupportedPlatform)
142    }
143
144    /// Report that the native TOSA-to-Core ML execution path is unavailable on this target.
145    pub fn new_tosa() -> Result<Self, InitError> {
146        Self::new_tosa_with_compute_units(CoreMlComputeUnits::default())
147    }
148
149    /// Report that the requested Core ML placement policy is unavailable on this target.
150    pub fn new_tosa_with_compute_units(_units: CoreMlComputeUnits) -> Result<Self, InitError> {
151        Err(InitError::UnsupportedPlatform)
152    }
153}
154
155#[cfg(not(target_os = "macos"))]
156impl TosaCapabilityProvider for CoreMlAccelerator {
157    fn tosa_capabilities(&self) -> &'static [CapabilityDescriptor] {
158        NO_CAPABILITIES
159    }
160}