Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .github/workflows/apple-inference.yml
Original file line number Diff line number Diff line change
@@ -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
39 changes: 38 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -86,6 +99,7 @@ configure_file(
set(TINYML_CORE_SOURCES
src/NN.cpp
src/Network.cpp
src/Inference.cpp
)

set(TINYML_CORE_HEADERS
Expand All @@ -105,6 +119,21 @@ set_target_properties(
SOVERSION ${PROJECT_VERSION_MAJOR}
)
tinyml_configure_target(TinyMLCore)
target_compile_definitions(TinyMLCore PRIVATE
TINYML_ENABLE_MPS=$<BOOL:${TINYML_ENABLE_MPS}>
TINYML_ENABLE_NPU=$<BOOL:${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 $<$<COMPILE_LANGUAGE:OBJCXX>:-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
Expand Down Expand Up @@ -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})
Expand Down Expand Up @@ -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(
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
55 changes: 55 additions & 0 deletions docs/APPLE_INFERENCE.md
Original file line number Diff line number Diff line change
@@ -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 <tinyml/core.hpp>
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.
2 changes: 2 additions & 0 deletions include/tinyml/core.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@
#include <Model.h>
#include <Network.h>
#include <NN.h>

#include <tinyml/inference.hpp>
38 changes: 38 additions & 0 deletions include/tinyml/inference.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: MIT
#pragma once

#include <Model.h>
#include <functional>
#include <string>
#include <vector>

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<double> predict (const std::vector<double>& input);

private:
using Runner = std::function<std::vector<double> (const std::vector<double>&)>;
InferenceSession (Backend backend, Runner runner);
Backend selectedBackend;
Runner run;
};
}
59 changes: 59 additions & 0 deletions scripts/export_coreml.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#!/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

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,
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))


if __name__ == "__main__":
main()
Loading
Loading