SwiftUI-MLX本地大模型开发(二)

介绍

SwiftUI-MLX本地大模型开发一文中,我们已经详细讲了如何利用 MLX 进行本地大模型的开发。但是通过案例可以发现 2 个问题:

  1. MLX 内置的大模型数量有限。
  2. 每次大模型都需要从 HuggingFace 下载。

如何解决这 2 个问题,方案是:定制大模型与使用离线大模型。

定制大模型

swift 复制代码
// MARK: - 注册自定义模型,模型必须为MLX格式
extension MLXLLM.ModelRegistry {
    public static let llama3_2_3B_4bit = ModelConfiguration(
        id: "mlx-community/Llama-3.2-3B-Instruct-4bit", // Hugging Face上模型的仓库路径
        overrideTokenizer: "PreTrainedTokenizer" // 分词器
    )
}

使用离线大模型

  • 每次都从 HuggingFace 在线下载模型非常麻烦,如果已经离线下载了模型到本地,可以通过指定路径的方式加载模型。
  • 可以在 Model Scope 模型搜索地址 中搜索并下载需要的 MLX 大模型。
swift 复制代码
extension MLXLLM.ModelRegistry {
    public static let localModel = ModelConfiguration(
        directory: URL(fileURLWithPath: "/Users/yangfan/Documents/modelscope/Llama-3.2-3B-Instruct"),  // 本地模型的路径
        overrideTokenizer: "PreTrainedTokenizer"
    )
}

使用

swift 复制代码
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 != "" {
                ResponseBubble(text: response)
            }

            Spacer()
        }

        if isLoading {
            ProgressView()
                .progressViewStyle(.circular)
                .padding()
        }
    }
}

extension ContentView {
    // MARK: 文本生成
    func generate() async throws {
        isLoading = true
        // 加载模型
        //  let modelConfiguration = ModelRegistry.llama3_2_3B_4bit
        let modelConfiguration = ModelRegistry.localModel
        let modelContainer = try await LLMModelFactory.shared.loadContainer(configuration: modelConfiguration) { progress in
            print("正在下载 \(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 {
        ScrollView {
            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)
            }
        }
        .padding(.horizontal)
    }
}

效果

  • 定制大模型。
  • 使用离线大模型。
相关推荐
知其然亦知其所以然9 分钟前
全网最详细!手把手教你用 LangChain4j 打造 RAG 智能问答系统
后端·langchain·llm
东坡肘子2 小时前
Arc、Dia、TCA 与 SwiftUI | 肘子的 Swift 周报 #086
swiftui·swift·wwdc
小狮子安度因11 小时前
关于ffplay在macos上运行奔溃的问题
macos·ffmpeg
Mac技巧大咖12 小时前
恶意软件清理工具,让Mac电脑安全更简单
安全·macos·恶意软件清理工具
泯泷17 小时前
Claude 4 重磅来袭:你需要了解的一切
人工智能·算法·llm
非鱼feiyu18 小时前
从入门到实践:构建你的第一个 MCP Server
llm·aigc·mcp
Q同学18 小时前
仅用一条无标签数据,如何让大模型推理能力飙升?——One-shot Entropy Minimization 论文分享
人工智能·深度学习·llm
一丝晨光21 小时前
Windows搭建Swift语言编译环境?如何构建ObjC语言编译环境?Swift如何引入ObjC框架?Interface Builder的历史?
linux·windows·macos·ios·objective-c·xcode·swift
面壁者LOGIC21 小时前
xcode 编译运行错误 Sandbox: rsync(29343) deny(1) file-write-create
macos·xcode
面壁者LOGIC21 小时前
xcode卡死问题,无论打开什么程序xcode总是在转菊花,重启电脑,卸载重装都不行
macos·xcode