diff --git a/JetlinkKit/Sources/JetlinkORT/CoreMLSession.swift b/JetlinkKit/Sources/JetlinkORT/CoreMLSession.swift new file mode 100644 index 00000000..016e584c --- /dev/null +++ b/JetlinkKit/Sources/JetlinkORT/CoreMLSession.swift @@ -0,0 +1,261 @@ +import Foundation +import JetlinkServer + +#if canImport(CoreML) + import CoreML + import JetlinkONNX + + /// Executes a single-subgraph compiled `.mlmodelc` session directly via Core ML, + /// bypassing ONNX Runtime's C API wrapper and duplicate runtime memory while + /// preserving full FP16/FP32 precision (`allowLowPrecisionAccumulationOnGPU = false`). + final class CoreMLSession: EngineSession, @unchecked Sendable { + let inputs: [TensorSpec] + let outputs: [TensorSpec] + let label: String + private let model: MLModel + + private init(model: MLModel, inputs: [TensorSpec], outputs: [TensorSpec], label: String) { + self.model = model + self.inputs = inputs + self.outputs = outputs + self.label = label + } + + /// Returns whether a compiled Core ML session cache can be loaded natively: + /// a single `.mlmodelc` whose input/output names, static shapes, and types + /// match `onnxURL` 1:1. + static func canRunNatively(model onnxURL: URL, cache cacheDirectory: URL, computeUnits: String, fastPrediction: Bool) -> Bool { + loadValidated(onnxURL: onnxURL, cacheDirectory: cacheDirectory, computeUnits: computeUnits, fastPrediction: fastPrediction) != nil + } + + /// Loads a compiled Core ML session directly when `plan.provider == "CoreML"`, + /// `plan.native != false`, and the cache passes validation. Returns nil so + /// `OrtEngine` falls back transparently to `OrtSession`. + static func make(plan: SessionPlan) -> CoreMLSession? { + guard plan.provider == "CoreML", + plan.native != false, + let cachePath = plan.options["ModelCacheDirectory"], + let computeUnits = plan.options["MLComputeUnits"] + else { return nil } + + let fastPrediction = plan.options["SpecializationStrategy"] == "FastPrediction" + guard + let loaded = loadValidated( + onnxURL: plan.model, cacheDirectory: URL(fileURLWithPath: cachePath), computeUnits: computeUnits, fastPrediction: fastPrediction) + else { return nil } + + return CoreMLSession(model: loaded.model, inputs: loaded.inputs, outputs: loaded.outputs, label: "CoreML-Native(\(computeUnits))") + } + + func bind( + inputs: [(TensorSpec, UnsafeMutableRawPointer)], + outputs: [(TensorSpec, UnsafeMutableRawPointer)] + ) throws -> any EngineBinding { + try CoreMLBinding(model: model, inputs: inputs, outputs: outputs) + } + + private static func configuration(computeUnits: String, fastPrediction: Bool) -> MLModelConfiguration { + let configuration = MLModelConfiguration() + switch computeUnits { + case "CPUAndNeuralEngine": configuration.computeUnits = .cpuAndNeuralEngine + case "CPUAndGPU": configuration.computeUnits = .cpuAndGPU + case "CPUOnly": configuration.computeUnits = .cpuOnly + default: configuration.computeUnits = .all + } + // Strictly preserve full precision (never quantize or downgrade accumulation). + configuration.allowLowPrecisionAccumulationOnGPU = false + if fastPrediction { + configuration.optimizationHints.specializationStrategy = .fastPrediction + } + return configuration + } + + private static func loadValidated( + onnxURL: URL, cacheDirectory: URL, computeUnits: String, fastPrediction: Bool + ) -> (model: MLModel, inputs: [TensorSpec], outputs: [TensorSpec])? { + let models = CoreMLPlacement.compiledModels(under: cacheDirectory) + guard models.count == 1, let compiledURL = models.first else { return nil } + guard let onnxMeta = try? OnnxMeta.read(contentsOf: onnxURL) else { return nil } + let config = configuration(computeUnits: computeUnits, fastPrediction: fastPrediction) + guard let model = try? MLModel(contentsOf: compiledURL, configuration: config) else { return nil } + let description = model.modelDescription + guard let inputSpecs = matchSpecs(onnxMeta.inputs, with: description.inputDescriptionsByName), + let outputSpecs = matchSpecs(onnxMeta.outputs, with: description.outputDescriptionsByName) + else { return nil } + return (model, inputSpecs, outputSpecs) + } + + private static func matchSpecs( + _ expected: [OnnxMeta.Tensor], with descriptions: [String: MLFeatureDescription] + ) -> [TensorSpec]? { + guard !expected.isEmpty, expected.count == descriptions.count else { return nil } + var specs: [TensorSpec] = [] + specs.reserveCapacity(expected.count) + for tensor in expected { + guard let feature = descriptions[tensor.name], + feature.type == .multiArray, + let constraint = feature.multiArrayConstraint, + let elementType = ElementType(rawValue: tensor.elemType), + let expectedMLType = mlDataType(for: elementType), + constraint.dataType == expectedMLType + else { return nil } + + let onnxShape = tensor.dims.map { Int($0) } + guard !onnxShape.isEmpty, onnxShape.allSatisfy({ $0 > 0 }) else { return nil } + guard constraint.shape.map(\.intValue) == onnxShape else { return nil } + + specs.append(TensorSpec(name: tensor.name, type: elementType, shape: onnxShape)) + } + return specs + } + + static func mlDataType(for elementType: ElementType) -> MLMultiArrayDataType? { + switch elementType { + case .float16: .float16 + case .float: .float32 + case .int32: .int32 + default: nil + } + } + } + + /// Zero-copy `MLMultiArray` inputs and `outputBackings` over `EngineCore`-owned buffers. + final class CoreMLBinding: EngineBinding, @unchecked Sendable { + private struct OutputTarget { + let name: String + let pointer: UnsafeMutableRawPointer + let spec: TensorSpec + let expectedStrides: [Int] + } + + private let model: MLModel + private let inputProvider: MLDictionaryFeatureProvider + private let options: MLPredictionOptions + private let outputTargets: [OutputTarget] + + init( + model: MLModel, + inputs: [(TensorSpec, UnsafeMutableRawPointer)], + outputs: [(TensorSpec, UnsafeMutableRawPointer)] + ) throws { + self.model = model + + var inputFeatures: [String: MLFeatureValue] = [:] + inputFeatures.reserveCapacity(inputs.count) + for (spec, pointer) in inputs { + guard let dataType = CoreMLSession.mlDataType(for: spec.type) else { + throw OrtError("CoreML-Native does not support input type \(spec.type.name) for \(spec.name)") + } + let shape = spec.shape.map { NSNumber(value: $0) } + let strides = CoreMLBinding.rowMajorStrides(for: spec.shape).map { NSNumber(value: $0) } + let array = try MLMultiArray(dataPointer: pointer, shape: shape, dataType: dataType, strides: strides, deallocator: nil) + inputFeatures[spec.name] = MLFeatureValue(multiArray: array) + } + self.inputProvider = try MLDictionaryFeatureProvider(dictionary: inputFeatures) + + var backings: [String: MLMultiArray] = [:] + backings.reserveCapacity(outputs.count) + var targets: [OutputTarget] = [] + targets.reserveCapacity(outputs.count) + for (spec, pointer) in outputs { + guard let dataType = CoreMLSession.mlDataType(for: spec.type) else { + throw OrtError("CoreML-Native does not support output type \(spec.type.name) for \(spec.name)") + } + let shape = spec.shape.map { NSNumber(value: $0) } + let intStrides = CoreMLBinding.rowMajorStrides(for: spec.shape) + let strides = intStrides.map { NSNumber(value: $0) } + let array = try MLMultiArray(dataPointer: pointer, shape: shape, dataType: dataType, strides: strides, deallocator: nil) + backings[spec.name] = array + targets.append(OutputTarget(name: spec.name, pointer: pointer, spec: spec, expectedStrides: intStrides)) + } + let options = MLPredictionOptions() + options.outputBackings = backings + self.options = options + self.outputTargets = targets + } + + func run() throws { + try autoreleasepool { + let prediction = try model.prediction(from: inputProvider, options: options) + for target in outputTargets { + guard let array = prediction.featureValue(for: target.name)?.multiArrayValue else { + throw OrtError("CoreML-Native returned no multiArray output for \(target.name)") + } + // Fast path: Core ML wrote directly into our outputBacking pointer. + if UnsafeRawPointer(array.dataPointer) == UnsafeRawPointer(target.pointer) { + continue + } + let actualStrides = array.strides.map(\.intValue) + if actualStrides == target.expectedStrides { + target.pointer.copyMemory(from: array.dataPointer, byteCount: target.spec.byteCount) + } else { + CoreMLBinding.copyStrided( + from: UnsafeRawPointer(array.dataPointer), + srcStrides: actualStrides, + to: target.pointer, + shape: target.spec.shape, + elementSize: target.spec.type.size + ) + } + } + } + } + + private static func rowMajorStrides(for shape: [Int]) -> [Int] { + guard !shape.isEmpty else { return [1] } + var strides = [Int](repeating: 1, count: shape.count) + var running = 1 + for i in stride(from: shape.count - 1, through: 0, by: -1) { + strides[i] = running + running *= max(shape[i], 1) + } + return strides + } + + private static func copyStrided( + from src: UnsafeRawPointer, + srcStrides: [Int], + to dst: UnsafeMutableRawPointer, + shape: [Int], + elementSize: Int + ) { + let rank = shape.count + if rank == 0 { + dst.copyMemory(from: src, byteCount: elementSize) + return + } + let innerCount = shape[rank - 1] + let innerSrcStride = srcStrides[rank - 1] + var indices = [Int](repeating: 0, count: rank) + var dstOffset = 0 + while true { + var srcOffset = 0 + for dim in 0..<(rank - 1) { + srcOffset += indices[dim] * srcStrides[dim] + } + if innerSrcStride == 1 { + (dst + dstOffset * elementSize).copyMemory(from: src + srcOffset * elementSize, byteCount: innerCount * elementSize) + } else { + for j in 0..= 0 { + indices[d] += 1 + if indices[d] < shape[d] { break } + indices[d] = 0 + d -= 1 + } + if d < 0 { break } + } + } + } +#else + enum CoreMLSession { + static func canRunNatively(model: URL, cache: URL, computeUnits: String, fastPrediction: Bool) -> Bool { false } + static func make(plan: SessionPlan) -> (any EngineSession)? { nil } + } +#endif diff --git a/JetlinkKit/Sources/JetlinkORT/Ort.swift b/JetlinkKit/Sources/JetlinkORT/Ort.swift index 3a6830ad..6b871553 100644 --- a/JetlinkKit/Sources/JetlinkORT/Ort.swift +++ b/JetlinkKit/Sources/JetlinkORT/Ort.swift @@ -54,16 +54,37 @@ final class OrtEnvironment: @unchecked Sendable { } } +/// One loaded execution session (either onnxruntime or native Core ML). +protocol EngineSession: AnyObject, Sendable { + var inputs: [TensorSpec] { get } + var outputs: [TensorSpec] { get } + var label: String { get } + func bind( + inputs: [(TensorSpec, UnsafeMutableRawPointer)], + outputs: [(TensorSpec, UnsafeMutableRawPointer)] + ) throws -> any EngineBinding +} + +/// Caller-owned buffers bound to one session's inputs and outputs. +protocol EngineBinding: AnyObject, Sendable { + func run() throws +} + /// One onnxruntime session: a model file, an execution provider with its /// options, and the inputs and outputs it declares. -final class OrtSession: @unchecked Sendable { +final class OrtSession: EngineSession, @unchecked Sendable { let pointer: OpaquePointer let inputs: [TensorSpec] let outputs: [TensorSpec] + let label: String /// `provider` nil runs the session on the CPU alone. `config` is session /// config entries on top of jetlink's own; `threads` the intra-op pool. - init(model: URL, provider: String?, options: [String: String] = [:], config: [String: String] = [:], threads: Int = 1) throws { + init( + model: URL, provider: String?, options: [String: String] = [:], config: [String: String] = [:], threads: Int = 1, + label: String = "ORT" + ) throws { + self.label = label let env = try OrtEnvironment.shared() var session: OpaquePointer? var strings: [UnsafeMutablePointer?] = [] @@ -106,6 +127,13 @@ final class OrtSession: @unchecked Sendable { jl_session_release(pointer) } + func bind( + inputs: [(TensorSpec, UnsafeMutableRawPointer)], + outputs: [(TensorSpec, UnsafeMutableRawPointer)] + ) throws -> any EngineBinding { + try OrtBinding(session: self, inputs: inputs, outputs: outputs) + } + private static func describe(_ session: OpaquePointer, output: Bool) throws -> [TensorSpec] { try TensorSpec.described(count: jl_session_io_count(session, output ? 1 : 0)) { index, name, type, dims, rank in try OrtError.check(jl_session_io_info(session, output ? 1 : 0, index, &name, name.count, &type, &dims, dims.count, &rank)) @@ -114,7 +142,7 @@ final class OrtSession: @unchecked Sendable { } /// Caller-owned buffers bound to one session's inputs and outputs. -final class OrtBinding { +final class OrtBinding: EngineBinding, @unchecked Sendable { private let pointer: OpaquePointer init(session: OrtSession, inputs: [(TensorSpec, UnsafeMutableRawPointer)], outputs: [(TensorSpec, UnsafeMutableRawPointer)]) throws { diff --git a/JetlinkKit/Sources/JetlinkORT/OrtBackend.swift b/JetlinkKit/Sources/JetlinkORT/OrtBackend.swift index 4299b942..b5d1c392 100644 --- a/JetlinkKit/Sources/JetlinkORT/OrtBackend.swift +++ b/JetlinkKit/Sources/JetlinkORT/OrtBackend.swift @@ -180,6 +180,8 @@ public final class OrtBackend: EngineBackend { public let keepAlive: Bool /// Keep the CPU warm between the frames the Neural Engine or the NPU runs. public let keepCPUWarm: Bool + /// Load validated single-subgraph Core ML sessions directly through Apple's Core ML framework. + public let nativeCoreML: Bool private let preparer: any ModelPreparer private let chip: String private let log = ServerLog(category: "ort") @@ -187,11 +189,14 @@ public final class OrtBackend: EngineBackend { /// `chip` names what the artifacts are valid for: on Android the SoC's /// model, "SM8650" (Build.SOC_MODEL), which a QNN context is compiled for. /// Nil is the Apple chip on Apple platforms and "cpu" elsewhere. - public init(profile: OrtProfile, preparer: any ModelPreparer, keepAlive: Bool = true, keepCPUWarm: Bool = true, chip: String? = nil) { + public init( + profile: OrtProfile, preparer: any ModelPreparer, keepAlive: Bool = true, keepCPUWarm: Bool = true, nativeCoreML: Bool = true, chip: String? = nil + ) { self.profile = profile self.preparer = preparer self.keepAlive = keepAlive self.keepCPUWarm = keepCPUWarm + self.nativeCoreML = nativeCoreML self.chip = HostChip.resolve(chip) } @@ -245,9 +250,9 @@ public final class OrtBackend: EngineBackend { /// A session of `unit` on `model`, with today's options: the performance /// mode is a setting, not part of the artifact. - func plan(_ unit: OrtUnit, model: URL, cache: URL?) -> SessionPlan { + func plan(_ unit: OrtUnit, model: URL, cache: URL?, native: Bool? = nil) -> SessionPlan { switch unit { - case .coreML(let units): SessionPlan(model: model, computeUnits: units, cacheDirectory: cache) + case .coreML(let units): SessionPlan(model: model, computeUnits: units, cacheDirectory: cache, native: native) case .htp: SessionPlan(model: model, provider: "QNN", options: providerOptions(unit), label: "QNN(htp)", usesNeuralEngine: true) case .qnnGPU: SessionPlan(model: model, provider: "QNN", options: providerOptions(unit), label: "QNN(gpu)", usesGPU: true) case .cpu: SessionPlan(model: model, provider: nil, threads: HostChip.cpuThreads, label: "CPU") @@ -258,7 +263,8 @@ public final class OrtBackend: EngineBackend { manifest.map { entry in plan( OrtUnit(entry: entry)!, model: artifact.appending(path: entry["model"] as! String), - cache: (entry["cache"] as? String).map { artifact.appending(path: $0, directoryHint: .isDirectory) }) + cache: (entry["cache"] as? String).map { artifact.appending(path: $0, directoryHint: .isDirectory) }, + native: entry["native"] as? Bool) } } @@ -358,7 +364,7 @@ public final class OrtBackend: EngineBackend { report(stage, frac, msg) } let engine = try Ticker.during(interval: 2, tick) { - try OrtEngine(plans: plans(staged, manifest), device: deviceTag(), keepAlive: false, keepCPUWarm: false) + try OrtEngine(plans: plans(staged, manifest), device: deviceTag(), keepAlive: false, keepCPUWarm: false, nativeCoreML: false) } defer { engine.close() } let (converted, compiled) = progress.measure() @@ -376,7 +382,23 @@ public final class OrtBackend: EngineBackend { if freed > 0 { log.info("removed \(formatBytes(freed)) of converted model the compiled one replaces") } - var meta = OrtArtifact.meta(self, manifest: manifest, providers: engine.providers, model: model, started: started) + // Decide native Core ML eligibility once at build time and record it in + // `sessions.json`, so loads do not probe `MLModel` speculatively. + var updatedManifest = manifest + for index in updatedManifest.indices { + guard case .coreML(let units) = OrtUnit(entry: updatedManifest[index]), + let modelFile = updatedManifest[index]["model"] as? String, + let cache = updatedManifest[index]["cache"] as? String + else { continue } + let fastPrediction = units == "CPUAndNeuralEngine" || units == "ALL" + updatedManifest[index]["native"] = CoreMLSession.canRunNatively( + model: staged.appending(path: modelFile), + cache: staged.appending(path: cache, directoryHint: .isDirectory), + computeUnits: units, + fastPrediction: fastPrediction) + } + try OrtArtifact.writeManifest(updatedManifest, in: staged) + var meta = OrtArtifact.meta(self, manifest: updatedManifest, providers: engine.providers, model: model, started: started) if let limit = profile.visionWeightLimit { meta["vision_weight_limit"] = limit } @@ -452,7 +474,7 @@ public final class OrtBackend: EngineBackend { } let what = profile.usesCoreML ? "the CoreML model" : "the model" let (engine, seconds) = try Artifact.load(artifact, meta: meta, what: what, report: report) { - try OrtEngine(plans: plans(artifact, manifest), device: deviceTag(), keepAlive: keepAlive, keepCPUWarm: keepCPUWarm) + try OrtEngine(plans: plans(artifact, manifest), device: deviceTag(), keepAlive: keepAlive, keepCPUWarm: keepCPUWarm, nativeCoreML: nativeCoreML) } log.info("onnxruntime sessions on \(profile.rawValue) in \(String(format: "%.1f", seconds)) s: \(engine.providers.joined(separator: " then "))") return engine diff --git a/JetlinkKit/Sources/JetlinkORT/OrtEngine.swift b/JetlinkKit/Sources/JetlinkORT/OrtEngine.swift index f2982c49..bf48031a 100644 --- a/JetlinkKit/Sources/JetlinkORT/OrtEngine.swift +++ b/JetlinkKit/Sources/JetlinkORT/OrtEngine.swift @@ -18,10 +18,13 @@ public struct SessionPlan: Sendable, Equatable { public let usesGPU: Bool /// Runs on the Neural Engine or an NPU, so the CPU keep-warm helps it. public let usesNeuralEngine: Bool + /// Whether this session can load natively through Core ML (decided at build + /// time in `sessions.json`; nil for legacy caches probes at load time). + public let native: Bool? public init( model: URL, provider: String?, options: [String: String] = [:], threads: Int = 1, label: String, - usesGPU: Bool = false, usesNeuralEngine: Bool = false + usesGPU: Bool = false, usesNeuralEngine: Bool = false, native: Bool? = nil ) { self.model = model self.provider = provider @@ -30,13 +33,14 @@ public struct SessionPlan: Sendable, Equatable { self.label = label self.usesGPU = usesGPU self.usesNeuralEngine = usesNeuralEngine + self.native = native } /// A CoreML session on `computeUnits` ("CPUAndNeuralEngine", "CPUAndGPU" /// or "ALL"), with CoreML's compiled model kept in `cacheDirectory` so a /// load does not compile again. The provider options are the ones the /// Python backend passes (backends/ort/__init__.py). - public init(model: URL, computeUnits: String, cacheDirectory: URL?) { + public init(model: URL, computeUnits: String, cacheDirectory: URL?, native: Bool? = nil) { let neuralEngine = computeUnits == "CPUAndNeuralEngine" || computeUnits == "ALL" var options = [ "ModelFormat": "MLProgram", @@ -52,7 +56,7 @@ public struct SessionPlan: Sendable, Equatable { } self.init( model: model, provider: "CoreML", options: options, label: "CoreML(\(computeUnits))", - usesGPU: computeUnits == "CPUAndGPU" || computeUnits == "ALL", usesNeuralEngine: neuralEngine) + usesGPU: computeUnits == "CPUAndGPU" || computeUnits == "ALL", usesNeuralEngine: neuralEngine, native: native) } } @@ -73,8 +77,8 @@ public final class OrtEngine: EngineCore, @unchecked Sendable { public override var notes: String { "CPU keep-warm \(keepsCPUWarm ? "on" : "off")" } public override var coolsWhenIdle: Bool { usesNeuralEngine } - private let chain: [OrtSession] - private var bindings: [[OrtBinding]] = [] // [parity][session] + private let chain: [any EngineSession] + private var bindings: [[any EngineBinding]] = [] // [parity][session] /// How many of the chain's first sessions read only the frame, the state /// the engine loops and what the sessions before them made: the vision /// trunk, which `runAhead()` runs as soon as the frame is staged. @@ -87,15 +91,21 @@ public final class OrtEngine: EngineCore, @unchecked Sendable { private let usesNeuralEngine: Bool /// `keepAlive` keeps the GPU clocked up between frames, `keepCPUWarm` the - /// CPU; each only where a plan runs on that unit. - public init(plans: [SessionPlan], device: String, keepAlive: Bool = true, keepCPUWarm: Bool = true) throws { + /// CPU; each only where a plan runs on that unit. When `nativeCoreML` is + /// true on Apple platforms, compiled single-subgraph Core ML sessions run + /// directly via Core ML instead of ONNX Runtime. + public init(plans: [SessionPlan], device: String, keepAlive: Bool = true, keepCPUWarm: Bool = true, nativeCoreML: Bool = true) throws { self.device = device - var chain: [OrtSession] = [] + var chain: [any EngineSession] = [] for plan in plans { - chain.append(try OrtSession(model: plan.model, provider: plan.provider, options: plan.options, threads: plan.threads)) + if nativeCoreML, plan.native != false, let native = CoreMLSession.make(plan: plan) { + chain.append(native) + } else { + chain.append(try OrtSession(model: plan.model, provider: plan.provider, options: plan.options, threads: plan.threads, label: plan.label)) + } } self.chain = chain - self.providers = plans.map(\.label) + self.providers = chain.map(\.label) // What the host stages: every session's inputs no earlier session // produces. What it can read: every session's outputs no later one reads. @@ -148,9 +158,9 @@ public final class OrtEngine: EngineCore, @unchecked Sendable { /// other way round. The next_state_ output has no buffer of its own. private func rebind(_ pairs: [(input: String, output: String)]) throws { let outputOf = Dictionary(uniqueKeysWithValues: pairs.map { ($0.output, $0.input) }) - var sets: [[OrtBinding]] = [] + var sets: [[any EngineBinding]] = [] for p in 0..<(pairs.isEmpty ? 1 : 2) { - var set: [OrtBinding] = [] + var set: [any EngineBinding] = [] for session in chain { let ins = session.inputs.map { ($0, buffer($0.name, parity: p)!) } let outs = session.outputs.map { spec -> (TensorSpec, UnsafeMutableRawPointer) in @@ -158,7 +168,7 @@ public final class OrtEngine: EngineCore, @unchecked Sendable { // writes the buffer the state_ input reads next run return (spec, buffer(input, parity: p ^ 1)!) } - set.append(try OrtBinding(session: session, inputs: ins, outputs: outs)) + set.append(try session.bind(inputs: ins, outputs: outs)) } sets.append(set) } diff --git a/JetlinkKit/Sources/jetlink-server/Backends.swift b/JetlinkKit/Sources/jetlink-server/Backends.swift index ce4e80e1..f82eb637 100644 --- a/JetlinkKit/Sources/jetlink-server/Backends.swift +++ b/JetlinkKit/Sources/jetlink-server/Backends.swift @@ -32,12 +32,16 @@ "TensorRT's libraries, a self-contained copy of libnvinfer, its ONNX parser and plugins. Default: lib/tensorrt beside bin/ when it is there, else the loader path (a Jetson's JetPack).", valueName: "dir")) var tensorrtLibs: String? + @Flag( + name: .customLong("no-native-coreml"), + help: "Apple platforms: run CoreML through ONNX Runtime instead of loading compiled CoreML models directly.") + var noNativeCoreML = false /// The options, with "auto" read as each backend's default device. func options(keepAlive: Bool = true, keepCPUWarm: Bool = true) -> BackendOptions { BackendOptions( - device: device == "auto" ? nil : device, keepAlive: keepAlive, keepCPUWarm: keepCPUWarm, gpuTiming: gpuTiming, - tensorrtLibs: tensorrtLibs ?? bundledTensorRT()) + device: device == "auto" ? nil : device, keepAlive: keepAlive, keepCPUWarm: keepCPUWarm, nativeCoreML: !noNativeCoreML, + gpuTiming: gpuTiming, tensorrtLibs: tensorrtLibs ?? bundledTensorRT()) } /// The backend asked for; with none, logs why and exits 1. `auto` logs @@ -67,6 +71,7 @@ var device: String? var keepAlive = true var keepCPUWarm = true + var nativeCoreML = true var gpuTiming = false /// Where TensorRT's libraries are; nil for the loader path. var tensorrtLibs: String? @@ -102,7 +107,7 @@ #if !canImport(Metal) try OrtRuntime.load() #endif - return OrtBackend(profile: profile, preparer: ONNXPreparer(), keepAlive: keepAlive, keepCPUWarm: keepCPUWarm) + return OrtBackend(profile: profile, preparer: ONNXPreparer(), keepAlive: keepAlive, keepCPUWarm: keepCPUWarm, nativeCoreML: nativeCoreML) } /// LiteRT on the GPU or the CPU, its libraries in $JETLINK_LITERT_DIR diff --git a/JetlinkKit/Tests/JetlinkServerTests/OrtBackendTests.swift b/JetlinkKit/Tests/JetlinkServerTests/OrtBackendTests.swift index afa6f696..9d050ce6 100644 --- a/JetlinkKit/Tests/JetlinkServerTests/OrtBackendTests.swift +++ b/JetlinkKit/Tests/JetlinkServerTests/OrtBackendTests.swift @@ -165,6 +165,10 @@ struct OrtBackendTests { #expect(coreML.provider == "CoreML" && coreML.label == "CoreML(ALL)" && coreML.usesGPU && coreML.usesNeuralEngine) #expect(coreML.options["ModelCacheDirectory"] == "/tmp/coreml-model") #expect(coreML.options["SpecializationStrategy"] == "FastPrediction") + #expect(coreML.options["RequireStaticInputShapes"] == nil) + #expect(coreML.native == nil) + #expect(backend.plan(.coreML("ALL"), model: model, cache: nil, native: true).native == true) + #expect(backend.plan(.coreML("ALL"), model: model, cache: nil, native: false).native == false) #expect(backend.plan(.coreML("CPUAndGPU"), model: model, cache: nil).options["SpecializationStrategy"] == nil) } @@ -212,4 +216,71 @@ struct OrtBackendTests { warm.workEnded() #expect(eventually { warm.looks > rested }) } + + #if canImport(CoreML) + @Test("CoreML sessions run natively on CPUOnly when validated and fall back when disabled") + func nativeCoreMLSessionAndManifestDecision() throws { + let tmp = try TemporaryDirectory() + + // Split tiny_queued leaves ReduceMean(keepdims=0) outside CoreML, so native validation rejects it. + let queued = try Golden("tiny_queued") + let queuedDir = tmp.url.appending(path: "queued", directoryHint: .isDirectory) + let queuedCache = tmp.url.appending(path: "queued-cache", directoryHint: .isDirectory) + try FileManager.default.createDirectory(at: queuedDir, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: queuedCache, withIntermediateDirectories: true) + let preparedQueued = try ONNXPreparer().prepare( + model: queued.model, into: queuedDir, layout: .whole, policyOnNeuralEngine: false, visionWeightLimit: nil, cacheKey: { $0 }) + let queuedModel = queuedDir.appending(path: preparedQueued.parts[0].file) + let queuedCompiled = try OrtEngine( + plans: [SessionPlan(model: queuedModel, computeUnits: "CPUOnly", cacheDirectory: queuedCache)], + device: "coreml-cpu", keepAlive: false, keepCPUWarm: false, nativeCoreML: false) + try queuedCompiled.run() + queuedCompiled.close() + #expect(!CoreMLSession.canRunNatively(model: queuedModel, cache: queuedCache, computeUnits: "CPUOnly", fastPrediction: false)) + + // tiny_stateful's policy part is pure Reshape/Slice/Concat/Gemm and compiles into a single CoreML subgraph. + let stateful = try Golden("tiny_stateful") + let splitDir = tmp.url.appending(path: "stateful", directoryHint: .isDirectory) + let policyCache = tmp.url.appending(path: "policy-cache", directoryHint: .isDirectory) + try FileManager.default.createDirectory(at: splitDir, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: policyCache, withIntermediateDirectories: true) + let preparedStateful = try ONNXPreparer().prepare( + model: stateful.model, into: splitDir, layout: .split, policyOnNeuralEngine: true, visionWeightLimit: nil, cacheKey: { $0 }) + let policyPart = try #require(preparedStateful.parts.first { $0.name == "policy" }) + let policyModel = splitDir.appending(path: policyPart.file) + + let compiled = try OrtEngine( + plans: [SessionPlan(model: policyModel, computeUnits: "CPUOnly", cacheDirectory: policyCache)], + device: "coreml-cpu", keepAlive: false, keepCPUWarm: false, nativeCoreML: false) + try compiled.run() + compiled.close() + + #expect(CoreMLSession.canRunNatively(model: policyModel, cache: policyCache, computeUnits: "CPUOnly", fastPrediction: false)) + + let nativeEngine = try OrtEngine( + plans: [SessionPlan(model: policyModel, computeUnits: "CPUOnly", cacheDirectory: policyCache, native: true)], + device: "coreml-cpu", keepAlive: false, keepCPUWarm: false, nativeCoreML: true) + defer { nativeEngine.close() } + #expect(nativeEngine.providers == ["CoreML-Native(CPUOnly)"]) + try nativeEngine.run() + + let legacyEngine = try OrtEngine( + plans: [SessionPlan(model: policyModel, computeUnits: "CPUOnly", cacheDirectory: policyCache, native: nil)], + device: "coreml-cpu", keepAlive: false, keepCPUWarm: false, nativeCoreML: true) + defer { legacyEngine.close() } + #expect(legacyEngine.providers == ["CoreML-Native(CPUOnly)"]) + + let skippedEngine = try OrtEngine( + plans: [SessionPlan(model: policyModel, computeUnits: "CPUOnly", cacheDirectory: policyCache, native: false)], + device: "coreml-cpu", keepAlive: false, keepCPUWarm: false, nativeCoreML: true) + defer { skippedEngine.close() } + #expect(skippedEngine.providers == ["CoreML(CPUOnly)"]) + + let flagOffEngine = try OrtEngine( + plans: [SessionPlan(model: policyModel, computeUnits: "CPUOnly", cacheDirectory: policyCache, native: true)], + device: "coreml-cpu", keepAlive: false, keepCPUWarm: false, nativeCoreML: false) + defer { flagOffEngine.close() } + #expect(flagOffEngine.providers == ["CoreML(CPUOnly)"]) + } + #endif }