-
Notifications
You must be signed in to change notification settings - Fork 199
/
Copy pathContentView.swift
296 lines (256 loc) · 9.57 KB
/
ContentView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// Copyright © 2024 Apple Inc.
import AsyncAlgorithms
import MLX
import MLXLLM
import MLXLMCommon
import MLXRandom
import MarkdownUI
import Metal
import SwiftUI
import Tokenizers
struct ContentView: View {
@Environment(DeviceStat.self) private var deviceStat
@State var llm = LLMEvaluator()
enum displayStyle: String, CaseIterable, Identifiable {
case plain, markdown
var id: Self { self }
}
@State private var selectedDisplayStyle = displayStyle.markdown
var body: some View {
VStack(alignment: .leading) {
VStack {
HStack {
Text(llm.modelInfo)
.textFieldStyle(.roundedBorder)
Spacer()
Text(llm.stat)
}
HStack {
Toggle(isOn: $llm.includeWeatherTool) {
Text("Include \"get current weather\" tool")
}
.frame(maxWidth: 350, alignment: .leading)
Spacer()
if llm.running {
ProgressView()
.frame(maxHeight: 20)
Spacer()
}
Picker("", selection: $selectedDisplayStyle) {
ForEach(displayStyle.allCases, id: \.self) { option in
Text(option.rawValue.capitalized)
.tag(option)
}
}
.pickerStyle(.segmented)
#if os(visionOS)
.frame(maxWidth: 250)
#else
.frame(maxWidth: 150)
#endif
}
}
// show the model output
ScrollView(.vertical) {
ScrollViewReader { sp in
Group {
if selectedDisplayStyle == .plain {
Text(llm.output)
.textSelection(.enabled)
} else {
Markdown(llm.output)
.textSelection(.enabled)
}
}
.onChange(of: llm.output) { _, _ in
sp.scrollTo("bottom")
}
Spacer()
.frame(width: 1, height: 1)
.id("bottom")
}
}
HStack {
TextField("prompt", text: Bindable(llm).prompt)
.onSubmit(generate)
.disabled(llm.running)
#if os(visionOS)
.textFieldStyle(.roundedBorder)
#endif
Button(llm.running ? "stop" : "generate", action: llm.running ? cancel : generate)
}
}
#if os(visionOS)
.padding(40)
#else
.padding()
#endif
.toolbar {
ToolbarItem {
Label(
"Memory Usage: \(deviceStat.gpuUsage.activeMemory.formatted(.byteCount(style: .memory)))",
systemImage: "info.circle.fill"
)
.labelStyle(.titleAndIcon)
.padding(.horizontal)
.help(
Text(
"""
Active Memory: \(deviceStat.gpuUsage.activeMemory.formatted(.byteCount(style: .memory)))/\(GPU.memoryLimit.formatted(.byteCount(style: .memory)))
Cache Memory: \(deviceStat.gpuUsage.cacheMemory.formatted(.byteCount(style: .memory)))/\(GPU.cacheLimit.formatted(.byteCount(style: .memory)))
Peak Memory: \(deviceStat.gpuUsage.peakMemory.formatted(.byteCount(style: .memory)))
"""
)
)
}
ToolbarItem(placement: .primaryAction) {
Button {
Task {
copyToClipboard(llm.output)
}
} label: {
Label("Copy Output", systemImage: "doc.on.doc.fill")
}
.disabled(llm.output == "")
.labelStyle(.titleAndIcon)
}
}
.task {
// pre-load the weights on launch to speed up the first generation
_ = try? await llm.load()
}
}
private func generate() {
llm.generate()
}
private func cancel() {
llm.cancelGeneration()
}
private func copyToClipboard(_ string: String) {
#if os(macOS)
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(string, forType: .string)
#else
UIPasteboard.general.string = string
#endif
}
}
@Observable
@MainActor
class LLMEvaluator {
var running = false
var includeWeatherTool = false
var prompt = ""
var output = ""
var modelInfo = ""
var stat = ""
/// This controls which model loads. `qwen2_5_1_5b` is one of the smaller ones, so this will fit on
/// more devices.
let modelConfiguration = LLMRegistry.qwen2_5_1_5b
/// parameters controlling the output
let generateParameters = GenerateParameters(maxTokens: 240, temperature: 0.6)
let updateInterval = Duration.seconds(0.25)
/// A task responsible for handling the generation process.
var generationTask: Task<Void, Error>?
enum LoadState {
case idle
case loaded(ModelContainer)
}
var loadState = LoadState.idle
let currentWeatherToolSpec: [String: any Sendable] =
[
"type": "function",
"function": [
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": [
"type": "object",
"properties": [
"location": [
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
] as [String: String],
"unit": [
"type": "string",
"enum": ["celsius", "fahrenheit"],
] as [String: any Sendable],
] as [String: [String: any Sendable]],
"required": ["location"],
] as [String: any Sendable],
] as [String: any Sendable],
] as [String: any Sendable]
/// load and return the model -- can be called multiple times, subsequent calls will
/// just return the loaded model
func load() async throws -> ModelContainer {
switch loadState {
case .idle:
// limit the buffer cache
MLX.GPU.set(cacheLimit: 20 * 1024 * 1024)
let modelContainer = try await LLMModelFactory.shared.loadContainer(
configuration: modelConfiguration
) {
[modelConfiguration] progress in
Task { @MainActor in
self.modelInfo =
"Downloading \(modelConfiguration.name): \(Int(progress.fractionCompleted * 100))%"
}
}
let numParams = await modelContainer.perform { context in
context.model.numParameters()
}
self.prompt = modelConfiguration.defaultPrompt
self.modelInfo =
"Loaded \(modelConfiguration.id). Weights: \(numParams / (1024*1024))M"
loadState = .loaded(modelContainer)
return modelContainer
case .loaded(let modelContainer):
return modelContainer
}
}
private func generate(prompt: String) async {
self.output = ""
let userInput = UserInput(prompt: prompt)
do {
let modelContainer = try await load()
// each time you generate you will get something new
MLXRandom.seed(UInt64(Date.timeIntervalSinceReferenceDate * 1000))
try await modelContainer.perform { (context: ModelContext) -> Void in
let lmInput = try await context.processor.prepare(input: userInput)
let stream = try MLXLMCommon.generate(
input: lmInput, parameters: generateParameters, context: context)
// generate and output in batches
for await batch in stream._throttle(
for: updateInterval, reducing: Generation.collect)
{
let output = batch.compactMap { $0.chunk }.joined(separator: "")
if !output.isEmpty {
Task { @MainActor [output] in
self.output += output
}
}
if let completion = batch.compactMap({ $0.info }).first {
Task { @MainActor in
self.stat = "\(completion.tokensPerSecond) tokens/s"
}
}
}
}
} catch {
output = "Failed: \(error)"
}
}
func generate() {
guard !running else { return }
let currentPrompt = prompt
prompt = ""
generationTask = Task {
running = true
await generate(prompt: currentPrompt)
running = false
}
}
func cancelGeneration() {
generationTask?.cancel()
running = false
}
}