Skip to content

端侧 AI:Core ML 与 Vision ​

iOS 设备的 Neural Engine(ANE,iPhone X+)是少有的"用户手里有 AI 芯片"的硬件。Apple 提供:Vision(高层视觉任务)、Core ML(自定义模型推理)、MLX(Apple Silicon 上的 PyTorch-like 框架,主要 Mac)、Apple Intelligence(iOS 18.1+ 系统级 AI)、Foundation Model(iOS 19+ 端侧 LLM)。这一篇讲透端侧 AI 在 iOS 上的全景。

一句话先记住:端侧 AI 的核心承诺是"隐私 + 离线 + 低延迟"——数据不离设备,Neural Engine 加速,延迟毫秒级。Vision 是 Apple 调好的"高层 API"(文字识别、人脸检测、物体识别),Core ML 是"导入你的 .mlmodel 自定义推理",MLX / Apple Intelligence 是更新的层级。


一、Vision Framework:开箱即用的视觉任务 ​

Vision 是 Apple 自带的视觉 API,内置 30+ 种现成的图像 / 视频分析任务。文字识别、人脸检测、姿态识别、条码扫描、文档检测——不需要训练模型,直接调:

swift
import Vision

// 文字识别(OCR)
func recognizeText(from cgImage: CGImage) async throws -> [String] {
    let request = VNRecognizeTextRequest()
    request.recognitionLevel = .accurate          // .accurate / .fast
    request.recognitionLanguages = ["zh-Hans", "en-US"]
    request.usesLanguageCorrection = true
    
    let handler = VNImageRequestHandler(cgImage: cgImage)
    try handler.perform([request])
    
    return request.results?.compactMap { observation in
        observation.topCandidates(1).first?.string
    } ?? []
}

常用 Vision request:

Request用途
VNRecognizeTextRequestOCR,文字识别
VNDetectFaceRectanglesRequest人脸框
VNDetectFaceLandmarksRequest人脸特征点(眼睛 / 嘴 / 鼻子)
VNDetectBarcodesRequest条码 / 二维码
VNDetectRectanglesRequest矩形检测(扫描文档)
VNDetectHumanBodyPoseRequest人体姿态
VNDetectHumanHandPoseRequest手部姿态
VNGenerateImageFeaturePrintRequest图像 feature 向量(以图搜图)
VNClassifyImageRequest图像分类(动物 / 物体)
VNCoreMLRequest跑自定义 Core ML 模型

Vision 直接利用 Neural Engine,性能比自己写算法快几十倍。


二、Vision 在 SwiftUI 里:扫描文档 ​

swift
struct ScanDocView: View {
    @State private var recognizedText = ""
    
    var body: some View {
        VStack {
            ScannerView { image in
                Task {
                    recognizedText = await recognize(image: image)
                }
            }
            Text(recognizedText)
        }
    }
    
    private func recognize(image: UIImage) async -> String {
        guard let cgImage = image.cgImage else { return "" }
        let request = VNRecognizeTextRequest()
        request.recognitionLevel = .accurate
        request.recognitionLanguages = ["zh-Hans", "en-US"]
        
        do {
            let handler = VNImageRequestHandler(cgImage: cgImage)
            try handler.perform([request])
            return request.results?
                .compactMap { $0.topCandidates(1).first?.string }
                .joined(separator: "\n") ?? ""
        } catch {
            return "识别失败:\(error.localizedDescription)"
        }
    }
}

iOS 16+ 还有 VisionKit 的 DataScannerViewController,直接打开摄像头扫文字 / 条码:

swift
import VisionKit

let scanner = DataScannerViewController(
    recognizedDataTypes: [.text(), .barcode()],
    qualityLevel: .balanced,
    recognizesMultipleItems: true,
    isHighFrameRateTrackingEnabled: true,
    isPinchToZoomEnabled: true,
    isHighlightingEnabled: true
)
scanner.delegate = self
try scanner.startScanning()

这是 iPhone 12+ / iPad 上扫描文字 / 条码的最佳方式——直接 Apple 调好,不用自己组合相机 + Vision。


三、Core ML:导入自定义模型 ​

.mlmodel 是 Core ML 模型格式(老)、.mlpackage 是新格式(iOS 16+,支持更大模型)。从 PyTorch / TensorFlow 训练好后用 coremltools 转:

python
# Python 端
import coremltools as ct
import torch

torch_model = MyModel()
torch_model.eval()
example = torch.rand(1, 3, 224, 224)
traced = torch.jit.trace(torch_model, example)
ml_model = ct.convert(
    traced,
    inputs=[ct.ImageType(shape=example.shape)],
    compute_units=ct.ComputeUnit.ALL
)
ml_model.save("MyModel.mlpackage")

把 .mlpackage 拖进 Xcode 项目,Xcode 自动生成 Swift 类:

swift
let model = try MyModel(configuration: MLModelConfiguration())
let prediction = try model.prediction(input: MyModelInput(image: pixelBuffer))
let label = prediction.classLabel

四、Core ML 配置:CPU / GPU / ANE ​

swift
let config = MLModelConfiguration()
config.computeUnits = .all              // 自动选择最快
// .cpuOnly         — 强制 CPU(调试用)
// .cpuAndGPU       — CPU + GPU,不用 ANE
// .cpuAndNeuralEngine — CPU + ANE,不用 GPU
// .all             — 全部可用

let model = try MyModel(configuration: config)

ANE 比 GPU 慢一些(吞吐量),但功耗低 10 倍以上。一般任务用 .all 让 Core ML 自动决定;高吞吐用 .cpuAndGPU。

测试模型在 ANE 上跑没跑成功,用 Instruments 的 Core ML template,看 backend 调度。


五、Vision + Core ML 组合 ​

把自定义 Core ML 模型套上 Vision,享受其图像预处理(裁切 / 缩放 / 颜色空间转换):

swift
let mlModel = try MyCustomModel(configuration: MLModelConfiguration()).model
let visionModel = try VNCoreMLModel(for: mlModel)

let request = VNCoreMLRequest(model: visionModel) { request, error in
    guard let results = request.results as? [VNClassificationObservation] else { return }
    let top = results.prefix(3).map { "\($0.identifier): \($0.confidence)" }
    print(top)
}
request.imageCropAndScaleOption = .centerCrop

let handler = VNImageRequestHandler(cgImage: cgImage)
try handler.perform([request])

VNCoreMLRequest 让 Vision 帮你做图像处理 → 喂给模型 → 取出 observation,免去 PixelBuffer 转换的繁琐。


六、Image Playground / Genmoji(iOS 18.1+) ​

Apple Intelligence(iOS 18.1+,iPhone 15 Pro / 16 系列起)提供系统级 AI 能力:

  • Writing Tools:文本润色 / 摘要 / 重写,系统自动加在 TextField / TextEditor 的 menu
  • Image Playground:文字生图(卡通风格)
  • Genmoji:自定义 emoji
  • Notification Summary:多条推送自动汇总
  • Siri 进化:更强语义理解
swift
import ImagePlayground

// 启动图像生成 sheet
.imagePlaygroundSheet(
    isPresented: $showPlayground,
    concept: "a cat reading a book in a library",
    sourceImage: nil
) { url in
    // 用户生成的图片 URL
}

要在 Apple Intelligence 启用的设备上才工作,其他设备这个 sheet 直接不出现或显示错误。


七、Foundation Model(iOS 19+):端侧 LLM ​

iOS 19(2025 秋)起,Apple 提供端侧 Foundation Model(一个 3B 参数级别的 LLM),通过 FoundationModels framework 调用:

swift
// iOS 19+
import FoundationModels

if #available(iOS 19, *) {
    let session = LanguageModelSession()
    let response = try await session.respond(to: "请总结这段笔记:\(noteContent)")
    print(response.content)
}

完全端侧推理,数据不离设备。适用:文本摘要、问答、改写。模型能力远不如 GPT-4,但足够做"App 内辅助任务"。

主线 iOS 18 仍要给降级方案:

swift
func summarize(_ text: String) async throws -> String {
    if #available(iOS 19, *) {
        let session = LanguageModelSession()
        let response = try await session.respond(to: "总结:\n\(text)")
        return response.content
    } else {
        // 降级:云端 API
        return try await cloudSummarize(text)
    }
}

八、MLX:Apple Silicon 上的 PyTorch-like ​

MLX 是 Apple 2023 推出的开源框架,主要面向 Mac(M 系列芯片),iOS 上也能用但场景少。语法与 PyTorch 接近:

swift
import MLX

let a = MLXArray([1, 2, 3, 4])
let b = MLXArray([4, 3, 2, 1])
let c = a + b * 2

iOS 用 MLX 的场景极少——99% 端侧推理用 Core ML 就够,MLX 主要在做研究 / 训练时用。


九、典型场景:NotesIsland 的端侧 AI 接入 ​

场景 1:笔记照片自动提取文字成 tag

swift
func extractTags(from imageData: Data) async -> [String] {
    guard let image = UIImage(data: imageData),
          let cgImage = image.cgImage else { return [] }
    
    let request = VNRecognizeTextRequest()
    request.recognitionLevel = .accurate
    request.recognitionLanguages = ["zh-Hans", "en-US"]
    
    let handler = VNImageRequestHandler(cgImage: cgImage)
    try? handler.perform([request])
    
    let text = request.results?.compactMap { $0.topCandidates(1).first?.string }.joined(separator: " ") ?? ""
    return extractKeywords(from: text)    // 简单的关键词提取
}

场景 2:录音的关键词提取(使用 Speech framework)

swift
import Speech

let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "zh-CN"))!
let request = SFSpeechURLRecognitionRequest(url: audioFileURL)

let result = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<SFSpeechRecognitionResult, Error>) in
    recognizer.recognitionTask(with: request) { result, error in
        if let result, result.isFinal {
            continuation.resume(returning: result)
        } else if let error {
            continuation.resume(throwing: error)
        }
    }
}

let transcript = result.bestTranscription.formattedString

Speech framework 也是端侧 + 云端混合(iOS 13+ 起,默认端侧;长音频可能落到云端)。requiresOnDeviceRecognition = true 强制端侧。

场景 3:笔记摘要(iOS 19+ 用 Foundation Model,降级云端)

swift
func summarize(_ note: Note) async throws -> String {
    let prompt = "用一句话总结:\n\(note.body)"
    
    if #available(iOS 19, *) {
        let session = LanguageModelSession()
        return try await session.respond(to: prompt).content
    } else {
        return try await openAI.complete(prompt: prompt)
    }
}

十、端侧 AI 的限制与边界 ​

端侧 AI 在 iOS 上很强,但不是万能:

  • 模型大小:Core ML 模型超过 100MB 会让 App 包巨大,选模型时要权衡(quantize / pruning)
  • 推理速度:iPhone 16 Pro 大约能跑 10B 以下的 Transformer;15 Pro 跑 3-7B;iPhone 13 等旧机型大幅降级
  • 内存:LLM 推理占内存高,后台容易被系统 kill
  • 能力上限:端侧 LLM 仍不如 GPT-4 / Claude,复杂任务最终要混合云端
  • 隐私 vs 能力:端侧最大优势是隐私,牺牲的是能力上限

典型策略:简单任务端侧(OCR / 关键词 / 翻译短文),复杂任务云端(深度对话 / 创作)。


十一、踩坑 ​

  1. .mlpackage 没拖进 Xcode 自动生成类——通常因为放错位置或者文件名带空格。File → Add Files to Project。
  2. VNRecognizeTextRequest 不指定语言——中文识别率差。必填 recognitionLanguages。
  3. Core ML 模型在模拟器很慢——Apple Silicon Mac 模拟器还行,Intel Mac 模拟器没 Neural Engine,只有 CPU。真机才能测真实性能。
  4. Vision 处理大图导致 OOM——iOS 处理超大图(8000×6000)直接 OOM。在 Vision 之前先 resize。
  5. VNRequestHandler 一次塞 N 个 request——可以,但所有 request 共享同一次预处理,且都阻塞返回。复杂场景拆多次 handler。
  6. Core ML 模型版本兼容——.mlpackage 用了 iOS 18+ 的算子,在 iOS 17 上加载失败。导出时检查 minimum_deployment_target。
  7. Foundation Model 在 iOS 18 跑——只在 iOS 19+ 可用,if #available 包裹必备。
  8. Apple Intelligence 在不支持设备上没反应——只 iPhone 15 Pro / 16 系列起支持,App 要做能力检测。
  9. 端侧 LLM 占内存大,App 进后台被 kill——长对话不要存内存,用流式 + 持久化。
  10. SFSpeechRecognizer 没设 requiresOnDeviceRecognition——可能默认走云端,你以为是端侧。隐私敏感场景必设 true。

下一篇 23-Accessibility与本地化.md,讲 accessibilityLabel / accessibilityHint / accessibilityValue / accessibilityElement(children:)、Dynamic Type 缩放、VoiceOver 自检清单、Reduce Motion / High Contrast 适配、Xcode 15+ String Catalog (.xcstrings)、复数 / 设备变体、String(localized:) 与 LocalizedStringResource。