-
Notifications
You must be signed in to change notification settings - Fork 377
Expand file tree
/
Copy pathLLMEvaluator.swift
More file actions
368 lines (305 loc) · 12.4 KB
/
LLMEvaluator.swift
File metadata and controls
368 lines (305 loc) · 12.4 KB
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// Copyright © 2025 Apple Inc.
import MLX
import MLXLMHuggingFace
import MLXLLM
import MLXLMCommon
import MLXLMTransformers
import Metal
import SwiftUI
@Observable
@MainActor
class LLMEvaluator {
var running = false
var includeWeatherTool = false
var enableThinking = false
var maxTokens = 2048
var prompt = ""
var output = ""
var modelInfo = ""
// Download progress tracking
var downloadProgress: Double?
var totalSize: String?
// Performance metrics
var tokensPerSecond: Double = 0.0
var timeToFirstToken: Double = 0.0
var promptLength: Int = 0
var totalTokens: Int = 0
var totalTime: Double = 0.0
// Track if generation was truncated due to hitting max tokens
var wasTruncated: Bool = false
// Timer for tracking TTFT in real-time
private var ttftTimer: Timer?
private var generationStartTime: TimeInterval = 0
// Timer for tracking tokens/sec and total time in real-time
private var generationTimer: Timer?
private var firstTokenTime: TimeInterval = 0
/// This controls which model loads.
var modelConfiguration = LLMRegistry.qwen3_8b_4bit
/// Parameters controlling the generation output (max tokens and temperature).
var generateParameters: GenerateParameters {
GenerateParameters(maxTokens: maxTokens, temperature: 0.6)
}
/// A task responsible for handling the generation process.
var generationTask: Task<Void, Error>?
/// Tool executor for function calling
private let toolExecutor = ToolExecutor()
enum LoadState {
case idle
case loading
case loaded(ModelContainer)
}
var loadState = LoadState.idle
var isLoading: Bool {
if case .loading = loadState {
return true
}
return false
}
/// Short model name extracted from the full model ID.
private var modelName: String {
modelConfiguration.name.components(separatedBy: "/").last ?? modelConfiguration.name
}
/// Load and return the model. Can be called multiple times; subsequent calls return the cached model.
func load() async throws -> ModelContainer {
while true {
switch loadState {
case .idle:
return try await performLoad()
case .loading:
// Already loading, wait and retry
try await Task.sleep(for: .milliseconds(100))
case .loaded(let modelContainer):
return modelContainer
}
}
}
private func performLoad() async throws -> ModelContainer {
loadState = .loading
modelInfo = "Downloading \(modelName)..."
downloadProgress = 0.0
Memory.cacheLimit = 20 * 1024 * 1024
let hub = HubClient.default
do {
let modelContainer = try await LLMModelFactory.shared.loadContainer(
from: hub,
configuration: modelConfiguration
) { [weak self] progress in
Task { @MainActor in
self?.updateDownloadProgress(progress)
}
}
modelInfo = "Loading \(modelName)..."
downloadProgress = nil
totalSize = nil
let numParams = await modelContainer.perform { $0.model.numParameters() }
self.prompt = PresetPrompts.all[0].prompt
self.modelInfo = formatModelInfo(name: modelConfiguration.name, parameters: numParams)
loadState = .loaded(modelContainer)
return modelContainer
} catch {
resetLoadingState()
throw error
}
}
private func updateDownloadProgress(_ progress: Progress) {
modelInfo = "Downloading \(modelName) (\(Int(progress.fractionCompleted * 100))%)"
downloadProgress = progress.fractionCompleted
// Get file count info
if progress.totalUnitCount > 0 && progress.totalUnitCount < 100 {
totalSize = "File \(progress.completedUnitCount + 1) of \(progress.totalUnitCount)"
} else if progress.totalUnitCount > 0 {
totalSize =
"\(formatBytes(progress.completedUnitCount)) of \(formatBytes(progress.totalUnitCount))"
} else {
totalSize = nil
}
}
private func resetLoadingState() {
loadState = .idle
downloadProgress = nil
totalSize = nil
}
private func formatModelInfo(name: String, parameters: Int) -> String {
// Extract model name from full ID (e.g., "mlx-community/Qwen3-8B-4bit" -> "Qwen3-8B-4bit")
let modelName = name.components(separatedBy: "/").last ?? name
// Format parameter count (convert millions to billions if appropriate)
let paramMillions = parameters / (1024 * 1024)
let paramString: String
if paramMillions >= 1000 {
let paramBillions = Double(paramMillions) / 1000.0
paramString = String(format: "%.1fB", paramBillions)
} else {
paramString = "\(paramMillions)M"
}
return "\(modelName) • \(paramString) parameters"
}
private func formatBytes(_ bytes: Int64) -> String {
let formatter = ByteCountFormatter()
formatter.allowedUnits = [.useMB, .useGB]
formatter.countStyle = .file
return formatter.string(fromByteCount: bytes)
}
private func generate(prompt: String, toolResult: String? = nil) async {
// Only clear output if this is a fresh generation (not a tool continuation)
if toolResult == nil {
self.output = ""
// Reset metrics at start
self.totalTokens = 0
self.tokensPerSecond = 0.0
self.promptLength = 0
self.timeToFirstToken = 0.0
self.totalTime = 0.0
self.wasTruncated = false
// Start the real-time TTFT timer
generationStartTime = Date.timeIntervalSinceReferenceDate
ttftTimer?.invalidate()
ttftTimer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) {
[weak self] _ in
guard let self = self else { return }
Task { @MainActor in
let elapsed = Date.timeIntervalSinceReferenceDate - self.generationStartTime
self.timeToFirstToken = elapsed * 1000 // Convert to ms
}
}
}
var chat: [Chat.Message] = [
.system("You are a helpful assistant"),
.user(prompt),
]
if let toolResult {
chat.append(.tool(toolResult))
}
let userInput = UserInput(
chat: chat,
tools: includeWeatherTool ? toolExecutor.allToolSchemas : nil,
additionalContext: ["enable_thinking": enableThinking]
)
do {
let modelContainer = try await load()
// Capture parameters on MainActor before entering perform block
let parameters = generateParameters
// Seed random generator to ensure varied output each generation
MLXRandom.seed(UInt64(Date.timeIntervalSinceReferenceDate * 1000))
let lmInput = try await modelContainer.prepare(input: userInput)
let promptTokenCount = lmInput.text.tokens.size
let start = Date.timeIntervalSinceReferenceDate
let stream = try await modelContainer.generate(input: lmInput, parameters: parameters)
var iterator = stream.makeAsyncIterator()
if let first = await iterator.next() {
let firstTick = Date.timeIntervalSinceReferenceDate
let promptTime = firstTick - start
// Update TTFT and prompt length
Task { @MainActor in
self.ttftTimer?.invalidate()
self.ttftTimer = nil
self.timeToFirstToken = promptTime * 1000 // Convert to ms
self.promptLength = promptTokenCount
// Start real-time generation metrics tracking
self.firstTokenTime = Date.timeIntervalSinceReferenceDate
self.generationTimer?.invalidate()
self.generationTimer = Timer.scheduledTimer(
withTimeInterval: 0.1, repeats: true
) { [weak self] _ in
guard let self = self else { return }
Task { @MainActor in
let elapsed =
Date.timeIntervalSinceReferenceDate - self.firstTokenTime
if elapsed > 0 && self.totalTokens > 0 {
self.tokensPerSecond = Double(self.totalTokens) / elapsed
self.totalTime = elapsed
}
}
}
}
var generateTokens: Double = 1
var pendingToolCall: ToolCall?
// Check if first token is a tool call
if let toolCall = first.toolCall {
pendingToolCall = toolCall
} else if let chunk = first.chunk {
if !chunk.isEmpty {
Task { @MainActor [chunk] in
self.output += chunk
self.totalTokens += 1
}
}
}
// Only continue iterating if we haven't hit a tool call
if pendingToolCall == nil {
while let next = await iterator.next() {
// Check for tool calls
if let toolCall = next.toolCall {
pendingToolCall = toolCall
break
}
// Handle text chunks
if let chunk = next.chunk {
if !chunk.isEmpty {
Task { @MainActor [chunk] in
self.output += chunk
self.totalTokens += 1
}
generateTokens += 1
}
}
}
}
let secondTick = Date.timeIntervalSinceReferenceDate
let generateTime = secondTick - firstTick
let generateTps = generateTokens / generateTime
Task { @MainActor in
self.generationTimer?.invalidate()
self.generationTimer = nil
self.tokensPerSecond = generateTps
self.totalTime = generateTime
// Check if generation was truncated due to max tokens
if self.totalTokens >= parameters.maxTokens ?? Int.max {
self.wasTruncated = true
}
}
// Handle tool call if one was made
if let toolCall = pendingToolCall {
await self.executeToolAndContinue(
toolCall: toolCall, originalPrompt: prompt)
}
}
} catch {
ttftTimer?.invalidate()
ttftTimer = nil
generationTimer?.invalidate()
generationTimer = nil
output = "Failed: \(error)"
}
}
private func executeToolAndContinue(toolCall: ToolCall, originalPrompt: String) async {
// Show tool execution in output
self.output += "\n\n[Executing tool: \(toolCall.function.name)...]\n\n"
let result: String
do {
result = try await toolExecutor.execute(toolCall)
} catch {
result = "Error executing tool: \(error.localizedDescription)"
}
// Continue generation with tool result
await generate(prompt: originalPrompt, toolResult: result)
}
func generate() {
guard !running else { return }
let currentPrompt = prompt
guard !currentPrompt.isEmpty else { return }
generationTask = Task {
running = true
await generate(prompt: currentPrompt)
prompt = ""
running = false
}
}
func cancelGeneration() {
generationTask?.cancel()
ttftTimer?.invalidate()
ttftTimer = nil
generationTimer?.invalidate()
generationTimer = nil
running = false
}
}