-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathViewModel.swift
220 lines (183 loc) · 6.97 KB
/
ViewModel.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
//
// Copyright 2024 Picovoice Inc.
// You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE"
// file accompanying this source.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//
import PicoLLM
import Combine
import Foundation
class ViewModel: ObservableObject {
private let ACCESS_KEY = "${YOUR_ACCESS_KEY_HERE}"
private var picollm: PicoLLM?
private var timerTick = CFAbsoluteTimeGetCurrent()
private var timerTock = CFAbsoluteTimeGetCurrent()
private var numTokens = 0
static let modelLoadStatusTextDefault = """
Start by loading a `.pllm` model file.
You can download directly to your device or airdrop from a Mac.
"""
@Published var modelLoadStatusText = modelLoadStatusTextDefault
@Published var enableLoadModelButton = true
@Published var showFileImporter = false
@Published var selectedModelUrl: URL?
@Published var picoLLMLoaded = false
@Published var promptText = ""
@Published var generateTemperature = 0.0
@Published var generateCompletionTokenLimit = 128.0
@Published var stopPhrasesText = ""
@Published var generateTopP = 1.0
@Published var generatePresencePenalty = 0.0
@Published var generateFrequencyPenalty = 0.0
@Published var generateNumTopChoices = 0.0
@Published var isGenerating = false
@Published var completionPromptText = ""
@Published var completionText = ""
@Published var tpsText = ""
@Published var statsText = ""
@Published var errorMessage = ""
deinit {
if picollm != nil {
picollm!.delete()
}
}
public func extractModelFile() {
showFileImporter = true
}
public func loadPicollm() {
errorMessage = ""
modelLoadStatusText = "Loading picoLLM..."
enableLoadModelButton = false
let modelAccess = selectedModelUrl!.startAccessingSecurityScopedResource()
if !modelAccess {
errorMessage = "Can't get permissions to access model file"
enableLoadModelButton = true
return
}
DispatchQueue.global(qos: .userInitiated).async { [self] in
do {
picollm = try PicoLLM(accessKey: ACCESS_KEY, modelPath: selectedModelUrl!.path)
DispatchQueue.main.async { [self] in
picoLLMLoaded = true
}
} catch {
DispatchQueue.main.async { [self] in
errorMessage = "\(error.localizedDescription)"
}
}
DispatchQueue.main.async { [self] in
selectedModelUrl!.stopAccessingSecurityScopedResource()
modelLoadStatusText = ViewModel.modelLoadStatusTextDefault
enableLoadModelButton = true
}
}
}
public func unloadPicollm() {
if picollm != nil {
picollm!.delete()
}
picollm = nil
errorMessage = ""
promptText = ""
completionPromptText = ""
completionText = ""
tpsText = ""
statsText = ""
picoLLMLoaded = false
}
private func streamCallback(completion: String) {
DispatchQueue.main.async { [self] in
completionText += completion
if numTokens == 0 {
timerTick = CFAbsoluteTimeGetCurrent()
}
timerTock = CFAbsoluteTimeGetCurrent()
numTokens += 1
}
}
public func generate() {
if promptText.isEmpty {
return
}
errorMessage = ""
let stopPhrases = stopPhrasesText.isEmpty ? nil : stopPhrasesText
.split(separator: ",")
.map({(phrase) in phrase.trimmingCharacters(in: .whitespacesAndNewlines)})
if stopPhrases != nil && stopPhrases!.isEmpty {
errorMessage = "Empty or all whitespace stop phrases is invalid"
return
}
for phrase in stopPhrases ?? [] where phrase.isEmpty {
errorMessage = "Empty or all whitespace stop phrase is invalid"
return
}
isGenerating = true
completionPromptText = promptText
completionText = ""
tpsText = ""
statsText = ""
numTokens = 0
DispatchQueue.global(qos: .userInitiated).async { [self] in
do {
let result = try picollm!.generate(
prompt: promptText,
completionTokenLimit: Int32(generateCompletionTokenLimit),
stopPhrases: stopPhrases,
presencePenalty: Float(generatePresencePenalty),
frequencyPenalty: Float(generateFrequencyPenalty),
temperature: Float(generateTemperature),
topP: Float(generateTopP),
numTopChoices: Int32(generateNumTopChoices),
streamCallback: streamCallback)
DispatchQueue.main.async { [self] in
updateStats(result: result)
}
} catch {
DispatchQueue.main.async { [self] in
errorMessage = "\(error.localizedDescription)"
enableLoadModelButton = true
}
}
DispatchQueue.main.async { [self] in
promptText = ""
isGenerating = false
}
}
}
public func interrupt() {
do {
try picollm?.interrupt()
} catch {
DispatchQueue.main.async { [self] in
errorMessage = "\(error.localizedDescription)"
enableLoadModelButton = true
}
}
}
private struct TpsStats: Codable {
public let tokensPerSecond: Double
public init(tokensPerSecond: Double) {
self.tokensPerSecond = tokensPerSecond
}
}
public func updateStats(result: PicoLLMCompletion) {
let secondsElapsed: Double = (timerTock - timerTick)
let tokensPerSecond: Double = Double(numTokens) / secondsElapsed
tpsText = String(format: "%0.2f tokens per second", tokensPerSecond)
do {
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
var jsonData = try jsonEncoder.encode(result)
statsText = String(data: jsonData, encoding: String.Encoding.utf8) ?? ""
let tpsResult = TpsStats(tokensPerSecond: tokensPerSecond)
jsonData = try jsonEncoder.encode(tpsResult)
statsText += String(data: jsonData, encoding: String.Encoding.utf8) ?? ""
} catch {
DispatchQueue.main.async { [self] in
errorMessage = "\(error.localizedDescription)"
}
}
}
}