Skip to content
Open
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
261 changes: 261 additions & 0 deletions JetlinkKit/Sources/JetlinkORT/CoreMLSession.swift
Original file line number Diff line number Diff line change
@@ -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..<innerCount {
(dst + (dstOffset + j) * elementSize).copyMemory(from: src + (srcOffset + j * innerSrcStride) * elementSize, byteCount: elementSize)
}
}
dstOffset += innerCount
if rank == 1 { break }
var d = rank - 2
while d >= 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
34 changes: 31 additions & 3 deletions JetlinkKit/Sources/JetlinkORT/Ort.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<CChar>?] = []
Expand Down Expand Up @@ -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))
Expand All @@ -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 {
Expand Down
Loading
Loading