From a3429e9b6a1911f3fb82de142de67956bace652b Mon Sep 17 00:00:00 2001 From: Abhishek Shivakumar Date: Thu, 26 Nov 2026 00:47:49 +0000 Subject: [PATCH 1/2] Add opt-in Apple MPSGraph and Core ML inference SDK --- .github/workflows/apple-inference.yml | 38 +++++ CMakeLists.txt | 39 ++++- README.md | 4 + docs/APPLE_INFERENCE.md | 55 +++++++ include/tinyml/core.hpp | 2 + include/tinyml/inference.hpp | 38 +++++ scripts/export_coreml.py | 49 ++++++ src/AppleInference.mm | 220 ++++++++++++++++++++++++++ src/Inference.cpp | 91 +++++++++++ tests/inference_smoke.cpp | 61 +++++++ 10 files changed, 596 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/apple-inference.yml create mode 100644 docs/APPLE_INFERENCE.md create mode 100644 include/tinyml/inference.hpp create mode 100644 scripts/export_coreml.py create mode 100644 src/AppleInference.mm create mode 100644 src/Inference.cpp create mode 100644 tests/inference_smoke.cpp diff --git a/.github/workflows/apple-inference.yml b/.github/workflows/apple-inference.yml new file mode 100644 index 0000000..4774c0a --- /dev/null +++ b/.github/workflows/apple-inference.yml @@ -0,0 +1,38 @@ +name: Apple inference +on: + pull_request: + branches: [main] + push: + branches: [main] + workflow_dispatch: +permissions: + contents: read +jobs: + apple: + runs-on: macos-15 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: '3.11' + - name: Configure + run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_DEPLOYMENT_TARGET=13.0 -DTINYML_BUILD_EXTENDED=OFF -DTINYML_BUILD_TESTS=ON -DTINYML_ENABLE_MPS=ON -DTINYML_ENABLE_NPU=ON + - name: Build + run: cmake --build build --parallel 2 + - name: CPU and MPS parity + run: ctest --test-dir build --output-on-failure + - name: Export and run Core ML fixture + run: | + python -m pip install 'coremltools>=8,<10' numpy + ./build/TinyMLInferenceSmoke --export-fixture + python scripts/export_coreml.py --topology 2 3 2 --weights apple-fixture.txt --output fixture.mlpackage + mkdir -p compiled + xcrun coremlcompiler compile fixture.mlpackage compiled + ./build/TinyMLInferenceSmoke --npu compiled/fixture.mlmodelc + - name: Install package + run: cmake --install build --prefix "$PWD/install" + - name: Installed consumer + run: | + cmake -S tests/install_consumer -B consumer-build -DCMAKE_PREFIX_PATH="$PWD/install" + cmake --build consumer-build --parallel 2 + ./consumer-build/tinyml_install_consumer diff --git a/CMakeLists.txt b/CMakeLists.txt index 1df1447..987b90f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,6 +27,19 @@ option(TINYML_BUILD_EXAMPLES "Build example executables" OFF) option(TINYML_BUILD_PLAYGROUND "Build the interactive playground server" OFF) option(TINYML_FETCH_DEPENDENCIES "Fetch missing third-party build dependencies" ${TINYML_TOP_LEVEL}) option(TINYML_ENABLE_WARNINGS "Enable compiler warnings for TinyML targets" ${TINYML_TOP_LEVEL}) +option(TINYML_ENABLE_MPS "Enable Apple MPSGraph inference" OFF) +option(TINYML_ENABLE_NPU "Enable Apple Core ML CPU/Neural Engine inference" OFF) + +if(TINYML_ENABLE_MPS OR TINYML_ENABLE_NPU) + if(NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin") + message(FATAL_ERROR "TinyML Apple inference requires macOS") + endif() + if(CMAKE_OSX_DEPLOYMENT_TARGET AND CMAKE_OSX_DEPLOYMENT_TARGET VERSION_LESS 13.0) + message(FATAL_ERROR "TinyML Apple inference requires macOS 13 or later") + endif() + enable_language(OBJCXX) +endif() + option(TINYML_ENABLE_LTO "Enable interprocedural optimization when supported" OFF) if(TINYML_BUILD_BENCHMARKS AND NOT TINYML_BUILD_EXTENDED) @@ -86,6 +99,7 @@ configure_file( set(TINYML_CORE_SOURCES src/NN.cpp src/Network.cpp + src/Inference.cpp ) set(TINYML_CORE_HEADERS @@ -105,6 +119,21 @@ set_target_properties( SOVERSION ${PROJECT_VERSION_MAJOR} ) tinyml_configure_target(TinyMLCore) +target_compile_definitions(TinyMLCore PRIVATE + TINYML_ENABLE_MPS=$ + TINYML_ENABLE_NPU=$) +if(TINYML_ENABLE_MPS OR TINYML_ENABLE_NPU) + target_sources(TinyMLCore PRIVATE src/AppleInference.mm) + set_target_properties(TinyMLCore PROPERTIES OBJCXX_STANDARD 17 OBJCXX_STANDARD_REQUIRED ON) + target_compile_options(TinyMLCore PRIVATE $<$:-fobjc-arc>) + target_link_libraries(TinyMLCore PRIVATE "-framework Foundation") + if(TINYML_ENABLE_MPS) + target_link_libraries(TinyMLCore PRIVATE "-framework Metal" "-framework MetalPerformanceShaders" "-framework MetalPerformanceShadersGraph") + endif() + if(TINYML_ENABLE_NPU) + target_link_libraries(TinyMLCore PRIVATE "-framework CoreML") + endif() +endif() set(TINYML_EXTENDED_HEADERS include/AdvancedAttention.h @@ -228,6 +257,14 @@ if(TINYML_BUILD_TESTS) target_compile_features(TinyMLCoreSmoke PRIVATE cxx_std_17) add_test(NAME TinyMLCoreSmoke COMMAND TinyMLCoreSmoke) + add_executable(TinyMLInferenceSmoke tests/inference_smoke.cpp) + target_link_libraries(TinyMLInferenceSmoke PRIVATE TinyMLCore) + add_test(NAME TinyMLInferenceCPU COMMAND TinyMLInferenceSmoke) + if(TINYML_ENABLE_MPS) + add_test(NAME TinyMLInferenceMPS COMMAND TinyMLInferenceSmoke --mps) + set_tests_properties(TinyMLInferenceMPS PROPERTIES SKIP_RETURN_CODE 77) + endif() + if(TINYML_BUILD_EXTENDED) function(tinyml_add_gtest target) add_executable(${target} ${ARGN}) @@ -327,7 +364,7 @@ install( DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) install( - FILES include/tinyml/core.hpp + FILES include/tinyml/core.hpp include/tinyml/inference.hpp DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/tinyml ) install( diff --git a/README.md b/README.md index 15dfe45..b6525ac 100644 --- a/README.md +++ b/README.md @@ -254,3 +254,7 @@ For a school project this means you can use any part of tinyML, as long as you a - [xsimd](https://github.com/xtensor-stack/xsimd) (BSD 3-Clause) for SIMD in the extended build. - [GoogleTest](https://github.com/google/googletest) for the test suites. - [cpp-httplib](https://github.com/yhirose/cpp-httplib) by Yuji Hirose and [JSON for Modern C++](https://github.com/nlohmann/json) by Niels Lohmann, both MIT, for the playground server. + +### Apple inference SDK (experimental) + +Opt in with `-DTINYML_ENABLE_MPS=ON` and/or `-DTINYML_ENABLE_NPU=ON` on macOS. See [Apple inference SDK](docs/APPLE_INFERENCE.md) for backend selection, Core ML export, and Neural Engine fallback limitations. diff --git a/docs/APPLE_INFERENCE.md b/docs/APPLE_INFERENCE.md new file mode 100644 index 0000000..aed37cb --- /dev/null +++ b/docs/APPLE_INFERENCE.md @@ -0,0 +1,55 @@ +# Apple inference SDK (experimental) + +Build on macOS 13+: + +```sh +cmake -S . -B build -DTINYML_BUILD_EXTENDED=OFF -DTINYML_ENABLE_MPS=ON -DTINYML_ENABLE_NPU=ON +cmake --build build +ctest --test-dir build --output-on-failure +``` + +Both options default to OFF; non-macOS builds remain dependency-free. Link TinyML::Core. +The SDK is an inference-only snapshot of the existing dense tanh network, not a global +switch for training or extended attention/transformer/physics operators. + +```cpp +#include +ML::Model model ({2, 3, 1}); +// Train or load weights before preparing the session. +ML::InferenceSession cpu (model); +ML::InferenceSession gpu (model, ML::Backend::MPS); +auto result = gpu.predict ({0.25, -0.5}); +model.saveWeightsToFile ("weights.txt"); +``` + +MPSGraph uses the entire dense graph with float32 constants and an explicit Metal command +queue. It retains graph and weights across calls, but first-use compilation, input allocation, +synchronization and readback are not hard-real-time safe. No automatic TinyML CPU fallback. +Use `InferenceSession::available(Backend::MPS)` to check for a Metal device. + +The public Core ML SDK has no ANE-only compute-unit selection. NPU selects CPU + Neural +Engine, excludes GPU, and may execute any or all operations on CPU. Availability means the +runtime SDK is available, not that an ANE was used. Profile with Xcode Core ML Instruments +or inspect the Core ML compute plan on supported macOS versions. + +Export the same topology and text weights offline (no PyTorch dependency): + +```sh +python3 -m venv .venv +source .venv/bin/activate +pip install 'coremltools>=8,<10' numpy +python scripts/export_coreml.py --topology 2 3 1 --weights weights.txt --output model.mlpackage +mkdir -p compiled +xcrun coremlcompiler compile model.mlpackage compiled +``` + +```cpp +auto npu = ML::InferenceSession::loadNPU ("compiled/model.mlmodelc"); +auto result = npu.predict ({0.25, -0.5}); +``` + +The compiled artifact contains independent weights; export again after training. The exporter +uses float16 internal computation and float32 feature I/O, not bitwise CPU parity. Sessions +are synchronous, fixed batch size one, and not safe to call concurrently. CPU remains the +default and is preferred for very small networks until measured otherwise. GPU/ANE hardware +execution and latency must be verified on a physical Apple Silicon Mac. diff --git a/include/tinyml/core.hpp b/include/tinyml/core.hpp index 6243c31..bc71046 100644 --- a/include/tinyml/core.hpp +++ b/include/tinyml/core.hpp @@ -4,3 +4,5 @@ #include #include #include + +#include diff --git a/include/tinyml/inference.hpp b/include/tinyml/inference.hpp new file mode 100644 index 0000000..22beafe --- /dev/null +++ b/include/tinyml/inference.hpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MIT +#pragma once + +#include +#include +#include +#include + +namespace ML +{ + enum class Backend { CPU, MPS, NPU }; + + // Inference-only snapshot. Recreate after training or changing weights. + // Sessions are synchronous and not safe for concurrent calls. + class InferenceSession + { + public: + explicit InferenceSession (const Model& model, Backend backend = Backend::CPU); + InferenceSession (InferenceSession&&) noexcept = default; + InferenceSession& operator= (InferenceSession&&) noexcept = default; + InferenceSession (const InferenceSession&) = delete; + InferenceSession& operator= (const InferenceSession&) = delete; + // Loads an independently exported Core ML artifact; NPU permits CPU execution. + static InferenceSession loadNPU (const std::string& compiledModelPath); + // CPU/MPS availability; for NPU indicates SDK support, not physical ANE use. + static bool available (Backend backend) noexcept; + + Backend backend() const noexcept { return selectedBackend; } + bool mayUseCPU() const noexcept { return selectedBackend != Backend::MPS; } + std::vector predict (const std::vector& input); + + private: + using Runner = std::function (const std::vector&)>; + InferenceSession (Backend backend, Runner runner); + Backend selectedBackend; + Runner run; + }; +} diff --git a/scripts/export_coreml.py b/scripts/export_coreml.py new file mode 100644 index 0000000..bb04916 --- /dev/null +++ b/scripts/export_coreml.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Export ML::Model text weights to a fixed-shape Core ML inference program.""" +import argparse +from pathlib import Path + +import coremltools as ct +import numpy as np +from coremltools.converters.mil.mil import Builder as mb + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--topology", type=int, nargs="+", required=True) + parser.add_argument("--weights", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if len(args.topology) < 2 or any(n <= 0 for n in args.topology): + parser.error("topology must contain at least two positive widths") + if args.output.suffix != ".mlpackage": + parser.error("output must end in .mlpackage") + weights = np.array([float(x) for x in args.weights.read_text().split()], dtype=np.float32) + expected = sum((a + 1) * b for a, b in zip(args.topology, args.topology[1:])) + if weights.size != expected or not np.isfinite(weights).all(): + parser.error(f"expected {expected} finite float32 weights") + layers = [] + offset = 0 + for a, b in zip(args.topology, args.topology[1:]): + block = weights[offset:offset + (a + 1) * b].reshape(a + 1, b) + layers.append((block[:-1].T.copy(), block[-1].copy())) + offset += (a + 1) * b + + @mb.program(input_specs=[mb.TensorSpec(shape=(1, args.topology[0]))], + opset_version=ct.target.iOS16) + def program(input): + value = input + for index, (matrix, bias) in enumerate(layers): + value = mb.linear(x=value, weight=matrix, bias=bias) + value = mb.tanh(x=value, name="output" if index == len(layers) - 1 else f"tanh_{index}") + return value + + model = ct.convert(program, convert_to="mlprogram", + minimum_deployment_target=ct.target.macOS13, + compute_precision=ct.precision.FLOAT16, + outputs=[ct.TensorType(name="output", dtype=np.float32)]) + model.save(str(args.output)) + + +if __name__ == "__main__": + main() diff --git a/src/AppleInference.mm b/src/AppleInference.mm new file mode 100644 index 0000000..81a8f58 --- /dev/null +++ b/src/AppleInference.mm @@ -0,0 +1,220 @@ +// SPDX-License-Identifier: MIT +#include +#include +#include +#include +#include +#include + +#import +#if TINYML_ENABLE_MPS +#import +#import +#import +#endif +#if TINYML_ENABLE_NPU +#import +#endif + +namespace ML::detail +{ + using Runner = std::function (const std::vector&)>; + +#if TINYML_ENABLE_MPS + namespace + { + struct MPSState + { + id device; + id queue; + MPSGraph* graph; + MPSGraphTensor* input; + MPSGraphTensor* output; + unsigned inputWidth = 0; + unsigned outputWidth = 0; + }; + + float checkedFloat (double value) + { + const auto result = static_cast (value); + if (!std::isfinite (result)) + throw std::invalid_argument ("TinyML MPS requires finite float32 values"); + return result; + } + + NSData* dataFor (const std::vector& values) + { + return [NSData dataWithBytes:values.data() length:values.size() * sizeof(float)]; + } + } + + bool mpsAvailable() noexcept + { + @autoreleasepool + { + if (@available(macOS 13.0, *)) + return MTLCreateSystemDefaultDevice() != nil; + return false; + } + } + + Runner makeMPS (const Model& model) + { + @autoreleasepool + { + if (!mpsAvailable()) + throw std::runtime_error ("TinyML MPS requires a Metal device and macOS 13+"); + + auto state = std::make_shared(); + state->device = MTLCreateSystemDefaultDevice(); + state->queue = [state->device newCommandQueue]; + if (!state->queue) + throw std::runtime_error ("Unable to create Metal command queue"); + + state->graph = [[MPSGraph alloc] init]; + state->graph.options = MPSGraphOptionsSynchronizeResults; + const auto& topology = model.getTopology(); + const auto weights = model.getWeights(); + state->inputWidth = topology.front(); + state->outputWidth = topology.back(); + state->input = [state->graph placeholderWithShape:@[@1, @(state->inputWidth)] + dataType:MPSDataTypeFloat32 name:@"input"]; + MPSGraphTensor* value = state->input; + std::size_t offset = 0; + for (std::size_t layer = 1; layer < topology.size(); ++layer) + { + const auto in = topology[layer - 1]; + const auto out = topology[layer]; + std::vector matrix (static_cast (in) * out); + std::vector bias (out); + for (auto& weight : matrix) + weight = checkedFloat (weights.at (offset++)); + for (auto& weight : bias) + weight = checkedFloat (weights.at (offset++)); + auto* w = [state->graph constantWithData:dataFor (matrix) + shape:@[@(in), @(out)] dataType:MPSDataTypeFloat32]; + auto* b = [state->graph constantWithData:dataFor (bias) + shape:@[@1, @(out)] dataType:MPSDataTypeFloat32]; + value = [state->graph matrixMultiplicationWithPrimaryTensor:value secondaryTensor:w name:nil]; + value = [state->graph additionWithPrimaryTensor:value secondaryTensor:b name:nil]; + value = [state->graph tanhWithTensor:value name:nil]; + } + state->output = value; + + return [state] (const std::vector& input) + { + @autoreleasepool + { + if (input.size() != state->inputWidth) + throw std::invalid_argument ("TinyML input vector size mismatch"); + std::vector values; + values.reserve (input.size()); + for (double x : input) + values.push_back (checkedFloat (x)); + id buffer = [state->device newBufferWithBytes:values.data() + length:values.size() * sizeof(float) options:MTLResourceStorageModeShared]; + if (!buffer) + throw std::runtime_error ("Unable to allocate MPS input buffer"); + auto* tensor = [[MPSGraphTensorData alloc] initWithMTLBuffer:buffer + shape:@[@1, @(state->inputWidth)] dataType:MPSDataTypeFloat32]; + auto* results = [state->graph runWithMTLCommandQueue:state->queue + feeds:@{state->input: tensor} targetTensors:@[state->output] targetOperations:nil]; + auto* result = results[state->output]; + if (!result) + throw std::runtime_error ("MPSGraph produced no output"); + std::vector output (state->outputWidth); + [result.mpsndarray readBytes:output.data() strideBytes:nullptr]; + return std::vector (output.begin(), output.end()); + } + }; + } + } +#endif + +#if TINYML_ENABLE_NPU + namespace + { + std::runtime_error coreMLError (const char* message, NSError* error) + { + const char* description = error.localizedDescription.UTF8String; + return std::runtime_error (std::string (message) + (description ? description : "")); + } + + std::size_t featureWidth (MLFeatureDescription* feature) + { + auto* constraint = feature.multiArrayConstraint; + if (!constraint || constraint.dataType != MLMultiArrayDataTypeFloat32 || + constraint.shape.count != 2 || constraint.shape[0].integerValue != 1 || + constraint.shape[1].integerValue <= 0) + throw std::invalid_argument ("Expected a float32 Core ML multiarray of shape [1, width]"); + return static_cast (constraint.shape[1].integerValue); + } + } + + bool coreMLAvailable() noexcept + { + if (@available(macOS 13.0, *)) + return true; + return false; + } + + Runner makeNPU (const std::string& path) + { + @autoreleasepool + { + if (@available(macOS 13.0, *)) + { + auto* filename = [NSString stringWithUTF8String:path.c_str()]; + if (!filename || ![filename.pathExtension isEqualToString:@"mlmodelc"]) + throw std::invalid_argument ("Expected a compiled .mlmodelc path"); + NSError* error = nil; + auto* config = [[MLModelConfiguration alloc] init]; + config.computeUnits = MLComputeUnitsCPUAndNeuralEngine; + auto* model = [MLModel modelWithContentsOfURL:[NSURL fileURLWithPath:filename] + configuration:config error:&error]; + if (!model) + throw coreMLError ("Core ML load failed: ", error); + const auto inputWidth = featureWidth (model.modelDescription.inputDescriptionsByName[@"input"]); + const auto outputWidth = featureWidth (model.modelDescription.outputDescriptionsByName[@"output"]); + + return [model, inputWidth, outputWidth] (const std::vector& input) + { + @autoreleasepool + { + if (input.size() != inputWidth) + throw std::invalid_argument ("TinyML input vector size mismatch"); + NSError* error = nil; + auto* array = [[MLMultiArray alloc] initWithShape:@[@1, @(inputWidth)] + dataType:MLMultiArrayDataTypeFloat32 error:&error]; + if (!array) + throw coreMLError ("Core ML input allocation failed: ", error); + for (std::size_t i = 0; i < inputWidth; ++i) + { + if (!std::isfinite (static_cast (input[i]))) + throw std::invalid_argument ("TinyML NPU requires finite float32 input"); + array[@[@0, @(i)]] = @(static_cast (input[i])); + } + auto* provider = [[MLDictionaryFeatureProvider alloc] + initWithDictionary:@{@"input": array} error:&error]; + if (!provider) + throw coreMLError ("Core ML feature creation failed: ", error); + id prediction = [model predictionFromFeatures:provider error:&error]; + if (!prediction) + throw coreMLError ("Core ML prediction failed: ", error); + auto* result = [prediction featureValueForName:@"output"].multiArrayValue; + if (!result || result.shape.count != 2 || + result.shape[0].integerValue != 1 || + result.shape[1].unsignedLongLongValue != outputWidth) + throw std::runtime_error ("Unexpected Core ML output shape"); + std::vector output (outputWidth); + for (std::size_t i = 0; i < outputWidth; ++i) + output[i] = [result[@[@0, @(i)]] doubleValue]; + return output; + } + }; + } + throw std::runtime_error ("TinyML NPU requires macOS 13+"); + } + } +#endif +} diff --git a/src/Inference.cpp b/src/Inference.cpp new file mode 100644 index 0000000..a7713db --- /dev/null +++ b/src/Inference.cpp @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: MIT +#include +#include +#include +#include + +namespace ML +{ + namespace detail + { +#if TINYML_ENABLE_MPS + bool mpsAvailable() noexcept; + std::function (const std::vector&)> makeMPS (const Model&); +#endif +#if TINYML_ENABLE_NPU + bool coreMLAvailable() noexcept; + std::function (const std::vector&)> makeNPU (const std::string&); +#endif + } + + InferenceSession::InferenceSession (Backend backend, Runner runner) + : selectedBackend (backend), run (std::move (runner)) + { + } + + InferenceSession::InferenceSession (const Model& model, Backend backend) + : selectedBackend (backend) + { + switch (backend) + { + case Backend::CPU: + { + auto snapshot = std::make_shared (model.getTopology()); + snapshot->setWeights (model.getWeights()); + run = [snapshot] (const std::vector& input) + { + snapshot->feedForward (input); + return snapshot->getResult(); + }; + break; + } + case Backend::MPS: +#if TINYML_ENABLE_MPS + run = detail::makeMPS (model); + break; +#else + throw std::runtime_error ("TinyML MPS backend was not enabled at build time"); +#endif + case Backend::NPU: + throw std::invalid_argument ("Use InferenceSession::loadNPU with an exported .mlmodelc"); + default: + throw std::invalid_argument ("Unknown TinyML backend"); + } + } + + InferenceSession InferenceSession::loadNPU (const std::string& compiledModelPath) + { +#if TINYML_ENABLE_NPU + return InferenceSession (Backend::NPU, detail::makeNPU (compiledModelPath)); +#else + (void) compiledModelPath; + throw std::runtime_error ("TinyML NPU backend was not enabled at build time"); +#endif + } + + bool InferenceSession::available (Backend backend) noexcept + { + switch (backend) + { + case Backend::CPU: return true; + case Backend::MPS: +#if TINYML_ENABLE_MPS + return detail::mpsAvailable(); +#else + return false; +#endif + case Backend::NPU: +#if TINYML_ENABLE_NPU + return detail::coreMLAvailable(); +#else + return false; +#endif + default: return false; + } + } + + std::vector InferenceSession::predict (const std::vector& input) + { + return run (input); + } +} diff --git a/tests/inference_smoke.cpp b/tests/inference_smoke.cpp new file mode 100644 index 0000000..ae79242 --- /dev/null +++ b/tests/inference_smoke.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include +#include + +int main (int argc, char** argv) +{ + ML::Model model ({2, 3, 2}); + model.setWeights ({0.1, -0.2, 0.3, -0.4, 0.5, -0.6, 0.07, -0.08, 0.09, + 0.2, -0.3, 0.4, 0.5, -0.6, 0.7, -0.15, 0.12}); + if (argc == 2 && std::string(argv[1]) == "--export-fixture") + { + model.saveWeightsToFile ("apple-fixture.txt"); + return 0; + } + ML::InferenceSession cpu (model); + const std::vector input {0.25, -0.5}; + model.feedForward (input); + const auto reference = model.getResult(); + auto check = [&] (ML::InferenceSession& session, double tolerance) + { + for (const auto& sample : std::vector> {input, {-0.4, 0.8}, {0.0, 0.0}}) + { + model.feedForward (sample); + const auto expected = model.getResult(); + const auto actual = session.predict (sample); + if (actual.size() != expected.size()) return false; + for (std::size_t i = 0; i < actual.size(); ++i) + if (!std::isfinite(actual[i]) || std::abs(actual[i] - expected[i]) > tolerance) + return false; + } + try { session.predict ({1.0}); } + catch (const std::invalid_argument&) { return true; } + return false; + }; + if (!check(cpu, 1e-12) || cpu.backend() != ML::Backend::CPU) return 1; + if (argc == 2 && std::string(argv[1]) == "--mps") + { + if (!ML::InferenceSession::available (ML::Backend::MPS)) + { + std::cout << "No Metal device available\n"; + return 77; + } + ML::InferenceSession gpu (model, ML::Backend::MPS); + return check(gpu, 2e-5) && !gpu.mayUseCPU() ? 0 : 1; + } + if (argc == 3 && std::string(argv[1]) == "--npu") + { + auto npu = ML::InferenceSession::loadNPU (argv[2]); + return check(npu, 3e-3) && npu.mayUseCPU() ? 0 : 1; + } + if (!ML::InferenceSession::available (ML::Backend::MPS)) + { + try { ML::InferenceSession unsupported (model, ML::Backend::MPS); return 1; } + catch (const std::runtime_error&) {} + } + model.setWeights (std::vector (model.getWeights().size(), 0.0)); + return cpu.predict(input) == reference ? 0 : 1; +} From 1e8bb31f181042ffd00c3049cb297de9f3cdbf6c Mon Sep 17 00:00:00 2001 From: Abhishek Shivakumar Date: Thu, 26 Nov 2026 00:48:28 +0000 Subject: [PATCH 2/2] Enforce Core ML feature ABI and exercise installed inference API --- scripts/export_coreml.py | 14 ++++++++++++-- tests/install_consumer/main.cpp | 5 ++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/scripts/export_coreml.py b/scripts/export_coreml.py index bb04916..eb03667 100644 --- a/scripts/export_coreml.py +++ b/scripts/export_coreml.py @@ -38,10 +38,20 @@ def program(input): value = mb.tanh(x=value, name="output" if index == len(layers) - 1 else f"tanh_{index}") return value - model = ct.convert(program, convert_to="mlprogram", + program.functions["main"].set_output_types([ct.TensorType(name="output", dtype=np.float32)]) + model = ct.convert(program, source="milinternal", convert_to="mlprogram", minimum_deployment_target=ct.target.macOS13, compute_precision=ct.precision.FLOAT16, - outputs=[ct.TensorType(name="output", dtype=np.float32)]) + inputs=[ct.TensorType(name="input", shape=(1, args.topology[0]), dtype=np.float32)], + skip_model_load=True) + spec = model.get_spec() + for features, name, width in ((spec.description.input, "input", args.topology[0]), + (spec.description.output, "output", args.topology[-1])): + if len(features) != 1 or features[0].name != name: + raise RuntimeError(f"Unexpected Core ML feature name: expected {name}") + array = features[0].type.multiArrayType + if list(array.shape) != [1, width] or array.dataType != ct.proto.FeatureTypes_pb2.ArrayFeatureType.FLOAT32: + raise RuntimeError(f"Unexpected Core ML feature shape or type: {name}") model.save(str(args.output)) diff --git a/tests/install_consumer/main.cpp b/tests/install_consumer/main.cpp index 195eac2..165c51f 100644 --- a/tests/install_consumer/main.cpp +++ b/tests/install_consumer/main.cpp @@ -7,5 +7,8 @@ int main() network.feedForward ({ 0.0, 1.0 }); std::vector result; network.getResults (result); - return result.size() == 1 ? EXIT_SUCCESS : EXIT_FAILURE; + ML::Model model ({2, 2, 1}); + ML::InferenceSession session (model); + return result.size() == 1 && session.predict ({0.0, 1.0}).size() == 1 + ? EXIT_SUCCESS : EXIT_FAILURE; }