介紹
- MLX 是 Apple 專為 Apple 芯片設計的機器學習框架。
- MLX Swift 將 MLX 擴展到了 Swift,可以直接在 iOS 項目中使用而無需借助 Python。
- MLX 中的 MLXLLM 模塊提供了一種簡單的方法來在本地設備(iPhone/iPad/Mac)使用預訓練的大語言模型 (LLMs) 進行推理。
使用步驟
- 添加 MLXLLM Package。
- 選擇某個預訓練模型。
- 加載選擇的預訓練模型。
- 創建輸入(Prompt)。
- 進行推理。
案例
- 代碼。
import MLXLLM
import MLXLMCommon
import SwiftUI
import SwiftUI
struct ContentView: View {
@State private var prompt: String = "什么是SwiftUI?"
@State private var response: String = ""
@State private var isLoading: Bool = false
var body: some View {
VStack(spacing: 16) {
// 頂部輸入區域
HStack {
TextField("輸入提示詞...", text: $prompt)
.textFieldStyle(.roundedBorder)
.font(.system(size: 16))
Button {
response = ""
Task {
do {
try await generate()
} catch {
debugPrint(error)
}
}
} label: {
Text("生成")
.foregroundStyle(.white)
.padding(.horizontal, 16)
.padding(.vertical, 8)
.background(prompt.isEmpty ? Color.gray : Color.blue)
.cornerRadius(8)
}
.buttonStyle(.borderless)
.disabled(prompt.isEmpty || isLoading)
}
.padding(.horizontal)
.padding(.top)
// 分隔線
Rectangle()
.fill(Color.gray.opacity(0.2))
.frame(height: 1)
// 響應展示區域
if response != "" {
ScrollView {
ResponseBubble(text: response)
}
.padding(.horizontal)
}
Spacer()
}
if isLoading {
ProgressView()
.progressViewStyle(.circular)
.padding()
}
}
}
extension ContentView {
func generate() async throws {
isLoading = true
// 加載模型(第一次使用會下載)
let modelConfiguration = ModelRegistry.llama3_2_1B_4bit
let modelContainer = try await LLMModelFactory.shared.loadContainer(configuration: modelConfiguration) { progress in
debugPrint("Downloading \(modelConfiguration.name): \(Int(progress.fractionCompleted * 100))%")
}
// 推理
let _ = try await modelContainer.perform { [prompt] context in
let input = try await context.processor.prepare(input: .init(prompt: prompt))
// 生成結果
let result = try MLXLMCommon.generate(input: input, parameters: .init(), context: context) { tokens in
let text = context.tokenizer.decode(tokens: tokens)
Task { @MainActor in
self.response = text
self.isLoading = false
}
return .more
}
return result
}
}
}
struct ResponseBubble: View {
let text: String
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text("AI")
.font(.system(size: 16))
.foregroundColor(.gray)
Text(text)
.font(.system(size: 16))
.lineSpacing(4)
.padding()
.background(Color.blue.opacity(0.1))
.cornerRadius(12)
}
}
}
注意:需要在真機運行測試。
- 效果。
效果.gif