0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Core ML基礎解説 - アプリに知性を宿す

Last updated at Posted at 2025-11-27

シリーズ: Apple Silicon AI技術スタック 完全解説
難易度: ★★☆☆☆(初級〜中級)
想定読者: iOS/macOSアプリにML機能を追加したい人、全てのApple開発者

TL;DR

  • Core MLはAppleの機械学習推論フレームワーク
  • モデル変換→Xcode統合→APIコールの3ステップでML機能を実装
  • CPU/GPU/Neural Engineを自動的に最適活用
  • WWDC24で大幅アップデート(MLTensor、ステート管理等)

すべての道はCore MLに通ず

ここまで、MPS、MLX、MPSGraph、Metal、vDSPと見てきた。でも、一般的なiOS/macOSアプリ開発者にとって最も馴染み深いのは、やはりCore MLだろう。

Apple公式サイトには:

"Core ML delivers blazingly fast performance on Apple devices with easy integration of machine learning and AI models into your apps and games."

(Core MLは、機械学習とAIモデルをアプリやゲームに簡単に統合し、Appleデバイス上で驚異的な高速パフォーマンスを実現します)

出典:Apple Developer - Machine Learning & AI


Core MLの立ち位置

これまで見てきた技術スタックを整理すると:

[Core ML] ← 開発者が通常触るのはここ
    ↓
[MPSGraph / BNNS Graph]
    ↓
[MPS] + [Neural Engine API]
    ↓
[Metal]
    ↓
[GPU] + [Neural Engine] + [CPU]

Core MLは「賢い司令塔」だ。モデルを受け取り、最適なハードウェア(GPU、Neural Engine、CPU)に処理を振り分ける。

WWDC24のセッションでは:

"Models are executed using Apple silicon's powerful compute capabilities, dispatching work across the CPU, GPU, and Neural Engine. It does this with the help of MPS Graph and BNNS Graph, two other machine learning frameworks which can also use Core ML models."

(モデルはApple Siliconの強力な計算能力を使用して実行され、CPU、GPU、Neural Engineに処理を振り分けます。これはMPS GraphとBNNS Graphという2つの機械学習フレームワークの助けを借りて行われます)

出典:WWDC24 - Deploy machine learning and AI models on-device with Core ML


Core MLの基本ワークフロー

Core MLを使うには3つのステップがある:

1. モデルの取得・変換
   PyTorch/TensorFlow → .mlmodel/.mlpackage

2. Xcodeへの統合
   ドラッグ&ドロップ → 自動コード生成

3. アプリから呼び出し
   数行のSwiftコードで推論実行

順番に見ていこう。


Step 1: モデルの取得・変換

coremltools でモデル変換

PyTorchやTensorFlowで学習したモデルをCore ML形式に変換する:

import coremltools as ct
import torch

# PyTorchモデルをロード
pytorch_model = torch.load('model.pt')
pytorch_model.eval()

# トレース用の入力サンプル
example_input = torch.rand(1, 3, 224, 224)

# TorchScriptに変換
traced_model = torch.jit.trace(pytorch_model, example_input)

# Core MLに変換
mlmodel = ct.convert(
    traced_model,
    inputs=[ct.ImageType(name="input", shape=(1, 3, 224, 224))],
)

# メタデータを設定
mlmodel.author = "Your Name"
mlmodel.short_description = "Image classifier model"

# 保存
mlmodel.save("MyModel.mlpackage")

公式ドキュメントによると:

"The coremltools Python package is the primary way to convert third-party models to Core ML."

(coremltoolsパッケージは、サードパーティのモデルをCore MLに変換する主要な方法です)

出典:Guide to Core ML Tools

TensorFlowからの変換

import coremltools as ct
from tensorflow.keras.models import load_model

# Kerasモデルをロード
keras_model = load_model('model.h5')

# Core MLに変換
mlmodel = ct.convert(keras_model)

# 保存
mlmodel.save('MyModel.mlmodel')

変換済みモデルの入手

自分で変換するのが面倒なら、Appleが提供する変換済みモデルもある:

出典:Apple Developer - Core ML Models

  • ResNet50(画像分類)
  • YOLO(物体検出)
  • DeepLab(セグメンテーション)
  • Depth Anything(深度推定)
  • etc.

Step 2: Xcodeへの統合

変換した.mlmodelまたは.mlpackageファイルをXcodeプロジェクトにドラッグ&ドロップするだけ。

XcodeがSwift/Objective-Cのインターフェースを自動生成してくれる:

MyModel.mlpackage
    ↓ Xcodeが自動生成
MyModel.swift
    - MyModel(モデルクラス)
    - MyModelInput(入力クラス)
    - MyModelOutput(出力クラス)

Xcodeでモデルファイルを選択すると、以下が確認できる:

  • General - モデルの基本情報
  • Preview - 入力を与えて結果をプレビュー
  • Performance - 実機でのパフォーマンス測定

Step 3: アプリから呼び出し

import CoreML

// モデルをロード
let configuration = MLModelConfiguration()
let model = try! MyModel(configuration: configuration)

// 入力を準備
let input = try! MyModelInput(imageWith: pixelBuffer)

// 推論実行
let output = try! model.prediction(input: input)

// 結果を取得
let classification = output.classLabel
let probabilities = output.classLabelProbs

たったこれだけ。モデルの最適化、ハードウェアの選択、メモリ管理、全部Core MLがやってくれる。


Neural Engineの自動活用

Core MLの大きな強みは、Neural Engine(ANE)を自動的に活用すること。

"To accelerate ML and AI algorithms, Core ML leverages not just ANE but also the CPU and GPU. This allows Core ML to run a model even if no ANE is available. But with an ANE present, Core ML will run much faster, and the battery won't be drained as quickly."

(MLとAIアルゴリズムを高速化するために、Core MLはANEだけでなくCPUとGPUも活用します。これにより、ANEがなくてもモデルを実行できます。ただし、ANEがあればCore MLはより高速に動作し、バッテリーの消耗も抑えられます)

出典:MakeUseOf - What Is Apple's Neural Engine and How Does It Work?

Neural Engineの性能

チップ Neural Engine性能
A11 (iPhone X) 0.6 TOPS
A14 (iPhone 12) 11 TOPS
A15 (iPhone 13) 15.8 TOPS
M1 11 TOPS
M4 38 TOPS
A19 Pro 更に向上

TOPS = Trillion Operations Per Second(1秒間に何兆回の演算ができるか)


Vision / Natural Languageとの統合

Core MLは単独で使うよりも、他のフレームワークと組み合わせることが多い。

Vision Frameworkで画像分類

import Vision
import CoreML

// Core MLモデルをVisionで使う
let model = try! VNCoreMLModel(for: MyImageClassifier().model)

let request = VNCoreMLRequest(model: model) { request, error in
    guard let results = request.results as? [VNClassificationObservation] else { return }
    
    let topResult = results.first!
    print("\(topResult.identifier): \(topResult.confidence * 100)%")
}

// 画像を処理
let handler = VNImageRequestHandler(cgImage: image, options: [:])
try! handler.perform([request])

物体検出

import Vision

let request = VNCoreMLRequest(model: objectDetector) { request, error in
    guard let results = request.results as? [VNRecognizedObjectObservation] else { return }
    
    for observation in results {
        let boundingBox = observation.boundingBox
        let label = observation.labels.first?.identifier ?? "Unknown"
        let confidence = observation.labels.first?.confidence ?? 0
        
        print("Found \(label) at \(boundingBox) with \(confidence * 100)% confidence")
    }
}

Natural Languageでテキスト分類

import NaturalLanguage

// テキスト分類にCore MLモデルを使う
let sentimentPredictor = try! NLModel(mlModel: MySentimentClassifier().model)

let sentiment = sentimentPredictor.predictedLabel(for: "This movie was amazing!")
print(sentiment)  // "positive"

WWDC24の新機能

2024年、Core MLに大きなアップデートがあった。

MLTensor:新しいデータ型

"The Core ML framework also adds a new MLTensor type which provides an efficient, simple and familiar API for expressing operations on multi-dimensional arrays."

(Core MLフレームワークには、多次元配列の操作を表現するための効率的でシンプルかつ馴染みのあるAPIを提供する新しいMLTensor型が追加されました)

出典:Apple Developer - Core ML Overview

import CoreML

// MLTensorの作成
let tensor1 = MLTensor([1.0, 2.0, 3.0])
let tensor2 = MLTensor([4.0, 5.0, 6.0])

// 演算
let result = tensor1 + tensor2
let mean = result.mean()

// 非同期実行のため、明示的に実体化
let shapedArray = await result.shapedArray(of: Float.self)
print(shapedArray)  // [5.0, 6.0, 7.0]

NumPyライクな操作が、Core ML上でネイティブにできるようになった。

ステート管理:LLM向け機能

LLMのKVキャッシュのようなステートフルな処理もサポート:

"Models can now hold multiple functions and efficiently manage state, enabling more flexible and efficient execution of large language models and adapters."

(モデルは複数の関数を保持し、状態を効率的に管理できるようになり、大規模言語モデルとアダプターのより柔軟で効率的な実行が可能になりました)

出典:Apple Developer - Core ML Overview


パフォーマンスレポート:Xcode統合

Core MLはXcodeと密に統合されている:

"Generate model performance reports measured on connected devices without having to write any code. Review a summary of load and prediction times along with a breakdown of compute unit usage of each operation."

(コードを書かずに、接続されたデバイスで測定されたモデルパフォーマンスレポートを生成します。ロードと予測時間の概要と、各演算の計算ユニット使用量の内訳を確認できます)

出典:Apple Developer - Core ML Overview

確認できる情報

  1. ロード時間 - モデルの初期化にかかる時間
  2. 予測時間 - 推論にかかる時間
  3. 計算ユニット - CPU/GPU/ANEの使用割合
  4. 演算ごとの内訳 - どの演算がボトルネックか

オンデバイス学習

Core MLはオンデバイス学習(転移学習)もサポートしている:

import CoreML

// 更新可能なモデルのURL
let modelURL = Bundle.main.url(forResource: "UpdatableModel", withExtension: "mlmodelc")!

// トレーニングデータを準備
let trainingData: MLBatchProvider = ... // ユーザーからの新しいサンプル

// 更新タスクを作成
let updateTask = try! MLUpdateTask(
    forModelAt: modelURL,
    trainingData: trainingData,
    configuration: nil,
    completionHandler: { context in
        // 更新されたモデルを保存
        let updatedModelURL = documentsDirectory.appendingPathComponent("UpdatedModel.mlmodelc")
        try! context.model.write(to: updatedModelURL)
        
        print("Model updated successfully!")
    }
)

// 進捗ハンドラ(オプション)
updateTask.progressHandlers.makeProgress = { context in
    print("Epoch \(context.epochIndex + 1)")
}

// 更新を開始
updateTask.resume()

ユーザーのデータをサーバーに送らずに、デバイス上でモデルをパーソナライズできる。プライバシー的にも大きなメリットだ。


Create ML:コードなしでモデル作成

Core MLモデルは自分で作ることもできる。Create MLアプリを使えば、コードを書かずに:

  • 画像分類
  • 物体検出
  • テキスト分類
  • 音声分類
  • 表形式データの回帰/分類
  • アクション分類

といったモデルを訓練できる。

Create MLの使い方

  1. アプリケーションからCreate MLを起動
  2. プロジェクトの種類を選択(Image Classifier等)
  3. トレーニングデータをドラッグ&ドロップ
  4. 「Train」ボタンをクリック
  5. 完成した.mlmodelをエクスポート

プログラミング不要でカスタムMLモデルが作れる。


ベストプラクティス

1. モデルのキャッシュ

// ❌ 毎回ロード(遅い)
func predict(input: MLFeatureProvider) -> MLFeatureProvider {
    let model = try! MyModel(configuration: MLModelConfiguration())
    return try! model.prediction(from: input)
}

// ✅ 一度ロードして再利用
class Predictor {
    private let model: MyModel
    
    init() {
        model = try! MyModel(configuration: MLModelConfiguration())
    }
    
    func predict(input: MLFeatureProvider) -> MLFeatureProvider {
        return try! model.prediction(from: input)
    }
}

2. バックグラウンドスレッドで実行

DispatchQueue.global(qos: .userInitiated).async {
    let output = try! model.prediction(input: input)
    
    DispatchQueue.main.async {
        // UIを更新
        self.updateUI(with: output)
    }
}

3. 計算ユニットの指定

let configuration = MLModelConfiguration()

// Neural Engineのみを使用(最速だが、全モデルが対応しているわけではない)
configuration.computeUnits = .cpuAndNeuralEngine

// GPUも使用
configuration.computeUnits = .all

// CPUのみ(デバッグ用)
configuration.computeUnits = .cpuOnly

let model = try! MyModel(configuration: configuration)

まとめ:Core MLは「出口」であり「入口」

機械学習エンジニアにとって、Core MLは技術スタックの「出口」だ。学習したモデルをデプロイする最終地点。

アプリ開発者にとっては「入口」でもある。機械学習の複雑さを隠蔽し、数行のコードでAI機能を実装できる。

そして裏では、MPS、MPSGraph、Metal、Neural Engineが協調して働いている。Core MLはその全てを統合し、最適なパフォーマンスを引き出す司令塔なのだ。


次に読む


参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?