Skip to main content

Model

Struct Model 

Source
pub struct Model { /* private fields */ }

Implementations§

Source§

impl Model

Source

pub fn load_async( path: impl AsRef<Path>, compute_units: ComputeUnits, ) -> Result<CompletionFuture<Self>>

Load a compiled model asynchronously.

Returns a CompletionFuture that resolves when loading completes. Use .await in async contexts or .block_on() for synchronous callers.

Requires macOS 12+ / iOS 15+.

Source

pub fn load_from_bytes( data: &[u8], compute_units: ComputeUnits, ) -> Result<CompletionFuture<Self>>

Load a model from in-memory specification bytes asynchronously.

Creates an MLModelAsset from the specification data (synchronously), then loads the model asynchronously via the completion handler API.

The data parameter should contain the contents of a .mlmodel file (the protobuf specification, not a compiled .mlmodelc).

Requires macOS 14.4+ / iOS 17.4+.

Source

pub fn predict_async( &self, inputs: &[(&str, &dyn AsMultiArray)], ) -> Result<CompletionFuture<Prediction>>

Run a prediction asynchronously.

Builds the feature provider from the input tensors, then calls the async prediction API with a completion handler.

Requires macOS 14+ / iOS 17+.

Source§

impl Model

Source

pub fn load(path: impl AsRef<Path>, compute_units: ComputeUnits) -> Result<Self>

Examples found in repository?
examples/load_and_predict.rs (line 13)
7fn main() {
8    let model_path = std::env::args()
9        .nth(1)
10        .unwrap_or_else(|| "tests/fixtures/test_linear.mlmodelc".to_string());
11
12    println!("Loading model: {model_path}");
13    let model = Model::load(&model_path, ComputeUnits::All).expect("Failed to load model");
14
15    // Create a simple input tensor
16    let input_data = vec![1.0f32, 2.0, 3.0, 4.0];
17    let tensor =
18        BorrowedTensor::from_f32(&input_data, &[1, 4]).expect("Failed to create tensor");
19
20    println!("Running prediction...");
21    let prediction = model.predict(&[("input", &tensor)]).expect("Prediction failed");
22
23    let (output, shape) = prediction.get_f32("output").expect("Failed to get output");
24    println!("Output shape: {shape:?}");
25    println!("Output data: {output:?}");
26}
More examples
Hide additional examples
examples/inspect_model.rs (line 13)
7fn main() {
8    let model_path = std::env::args()
9        .nth(1)
10        .unwrap_or_else(|| "tests/fixtures/test_linear.mlmodelc".to_string());
11
12    println!("Loading model: {model_path}");
13    let model = Model::load(&model_path, ComputeUnits::All).expect("Failed to load model");
14
15    println!("\n--- Inputs ---");
16    for desc in model.inputs() {
17        println!(
18            "  {}: {:?} shape={:?} optional={}",
19            desc.name(),
20            desc.feature_type(),
21            desc.shape(),
22            desc.is_optional(),
23        );
24        if let Some(dt) = desc.data_type() {
25            println!("    data_type: {dt}");
26        }
27    }
28
29    println!("\n--- Outputs ---");
30    for desc in model.outputs() {
31        println!(
32            "  {}: {:?} shape={:?}",
33            desc.name(),
34            desc.feature_type(),
35            desc.shape(),
36        );
37        if let Some(dt) = desc.data_type() {
38            println!("    data_type: {dt}");
39        }
40    }
41
42    let meta = model.metadata();
43    println!("\n--- Metadata ---");
44    println!("  author: {:?}", meta.author);
45    println!("  description: {:?}", meta.description);
46    println!("  version: {:?}", meta.version);
47    println!("  license: {:?}", meta.license);
48}
Source

pub fn path(&self) -> &Path

The filesystem path this model was loaded from.

Source

pub fn predict( &self, inputs: &[(&str, &dyn AsMultiArray)], ) -> Result<Prediction>

Run a synchronous prediction with named input tensors.

Accepts any type implementing AsMultiArray (both BorrowedTensor and OwnedTensor).

Examples found in repository?
examples/load_and_predict.rs (line 21)
7fn main() {
8    let model_path = std::env::args()
9        .nth(1)
10        .unwrap_or_else(|| "tests/fixtures/test_linear.mlmodelc".to_string());
11
12    println!("Loading model: {model_path}");
13    let model = Model::load(&model_path, ComputeUnits::All).expect("Failed to load model");
14
15    // Create a simple input tensor
16    let input_data = vec![1.0f32, 2.0, 3.0, 4.0];
17    let tensor =
18        BorrowedTensor::from_f32(&input_data, &[1, 4]).expect("Failed to create tensor");
19
20    println!("Running prediction...");
21    let prediction = model.predict(&[("input", &tensor)]).expect("Prediction failed");
22
23    let (output, shape) = prediction.get_f32("output").expect("Failed to get output");
24    println!("Output shape: {shape:?}");
25    println!("Output data: {output:?}");
26}
Source

pub fn inputs(&self) -> Vec<FeatureDescription>

Get descriptions of all model inputs.

Examples found in repository?
examples/inspect_model.rs (line 16)
7fn main() {
8    let model_path = std::env::args()
9        .nth(1)
10        .unwrap_or_else(|| "tests/fixtures/test_linear.mlmodelc".to_string());
11
12    println!("Loading model: {model_path}");
13    let model = Model::load(&model_path, ComputeUnits::All).expect("Failed to load model");
14
15    println!("\n--- Inputs ---");
16    for desc in model.inputs() {
17        println!(
18            "  {}: {:?} shape={:?} optional={}",
19            desc.name(),
20            desc.feature_type(),
21            desc.shape(),
22            desc.is_optional(),
23        );
24        if let Some(dt) = desc.data_type() {
25            println!("    data_type: {dt}");
26        }
27    }
28
29    println!("\n--- Outputs ---");
30    for desc in model.outputs() {
31        println!(
32            "  {}: {:?} shape={:?}",
33            desc.name(),
34            desc.feature_type(),
35            desc.shape(),
36        );
37        if let Some(dt) = desc.data_type() {
38            println!("    data_type: {dt}");
39        }
40    }
41
42    let meta = model.metadata();
43    println!("\n--- Metadata ---");
44    println!("  author: {:?}", meta.author);
45    println!("  description: {:?}", meta.description);
46    println!("  version: {:?}", meta.version);
47    println!("  license: {:?}", meta.license);
48}
Source

pub fn outputs(&self) -> Vec<FeatureDescription>

Get descriptions of all model outputs.

Examples found in repository?
examples/inspect_model.rs (line 30)
7fn main() {
8    let model_path = std::env::args()
9        .nth(1)
10        .unwrap_or_else(|| "tests/fixtures/test_linear.mlmodelc".to_string());
11
12    println!("Loading model: {model_path}");
13    let model = Model::load(&model_path, ComputeUnits::All).expect("Failed to load model");
14
15    println!("\n--- Inputs ---");
16    for desc in model.inputs() {
17        println!(
18            "  {}: {:?} shape={:?} optional={}",
19            desc.name(),
20            desc.feature_type(),
21            desc.shape(),
22            desc.is_optional(),
23        );
24        if let Some(dt) = desc.data_type() {
25            println!("    data_type: {dt}");
26        }
27    }
28
29    println!("\n--- Outputs ---");
30    for desc in model.outputs() {
31        println!(
32            "  {}: {:?} shape={:?}",
33            desc.name(),
34            desc.feature_type(),
35            desc.shape(),
36        );
37        if let Some(dt) = desc.data_type() {
38            println!("    data_type: {dt}");
39        }
40    }
41
42    let meta = model.metadata();
43    println!("\n--- Metadata ---");
44    println!("  author: {:?}", meta.author);
45    println!("  description: {:?}", meta.description);
46    println!("  version: {:?}", meta.version);
47    println!("  license: {:?}", meta.license);
48}
Source

pub fn metadata(&self) -> ModelMetadata

Get model metadata (author, description, version, license).

Examples found in repository?
examples/inspect_model.rs (line 42)
7fn main() {
8    let model_path = std::env::args()
9        .nth(1)
10        .unwrap_or_else(|| "tests/fixtures/test_linear.mlmodelc".to_string());
11
12    println!("Loading model: {model_path}");
13    let model = Model::load(&model_path, ComputeUnits::All).expect("Failed to load model");
14
15    println!("\n--- Inputs ---");
16    for desc in model.inputs() {
17        println!(
18            "  {}: {:?} shape={:?} optional={}",
19            desc.name(),
20            desc.feature_type(),
21            desc.shape(),
22            desc.is_optional(),
23        );
24        if let Some(dt) = desc.data_type() {
25            println!("    data_type: {dt}");
26        }
27    }
28
29    println!("\n--- Outputs ---");
30    for desc in model.outputs() {
31        println!(
32            "  {}: {:?} shape={:?}",
33            desc.name(),
34            desc.feature_type(),
35            desc.shape(),
36        );
37        if let Some(dt) = desc.data_type() {
38            println!("    data_type: {dt}");
39        }
40    }
41
42    let meta = model.metadata();
43    println!("\n--- Metadata ---");
44    println!("  author: {:?}", meta.author);
45    println!("  description: {:?}", meta.description);
46    println!("  version: {:?}", meta.version);
47    println!("  license: {:?}", meta.license);
48}
Source

pub fn new_state(&self) -> Result<State>

Create a new state for stateful prediction (macOS 15+ / iOS 18+).

Source

pub fn predict_stateful( &self, inputs: &[(&str, &dyn AsMultiArray)], state: &State, ) -> Result<Prediction>

Run prediction with persistent state (macOS 15+ / iOS 18+).

Source

pub fn predict_batch(&self, batch: &BatchProvider) -> Result<BatchPrediction>

Run batch prediction for multiple input sets at once.

More efficient than calling predict() in a loop.

Trait Implementations§

Source§

impl Debug for Model

Available on Apple only.
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Send for Model

Available on Apple only.
Source§

impl Sync for Model

Available on Apple only.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> AutoreleaseSafe for T
where T: ?Sized,