llama
251 строка · 7.2 Кб
1import Foundation
2import llama
3
4let arguments = CommandLine.arguments
5
6// Check that we have at least one argument (the model path)
7guard arguments.count > 1 else {
8print("Usage: swift MODEL_PATH [PROMPT] [PARALLEL]")
9exit(1)
10}
11
12let modelPath: String = arguments[1]
13let prompt: String = arguments.count > 2 ? arguments[2] : "Hello my name is"
14let n_parallel: Int = arguments.count > 3 && Int(arguments[3]) != nil ? Int(arguments[3])! : 1
15
16// total length of the sequences including the prompt
17let n_len: Int = 32
18
19// init LLM
20llama_backend_init()
21defer {
22llama_backend_free()
23}
24
25let model_params = llama_model_default_params()
26guard let model = llama_load_model_from_file(modelPath.cString(using: .utf8), model_params) else {
27print("Failed to load model")
28exit(1)
29}
30defer {
31llama_free_model(model)
32}
33
34var tokens = tokenize(text: prompt, add_bos: true)
35
36let n_kv_req = UInt32(tokens.count) + UInt32((n_len - Int(tokens.count)) * n_parallel)
37
38var context_params = llama_context_default_params()
39context_params.n_ctx = n_kv_req
40context_params.n_batch = UInt32(max(n_len, n_parallel))
41context_params.n_threads = 8
42context_params.n_threads_batch = 8
43
44let context = llama_new_context_with_model(model, context_params)
45guard context != nil else {
46print("Failed to initialize context")
47exit(1)
48}
49defer {
50llama_free(context)
51}
52
53var sparams = llama_sampler_chain_default_params()
54
55let smpl = llama_sampler_chain_init(sparams)
56guard smpl != nil else {
57print("Failed to initialize sampling")
58exit(1)
59}
60defer {
61llama_sampler_free(smpl)
62}
63
64llama_sampler_chain_add(smpl, llama_sampler_init_top_k(40));
65llama_sampler_chain_add(smpl, llama_sampler_init_top_p(0.9, 1));
66llama_sampler_chain_add(smpl, llama_sampler_init_temp (0.4));
67llama_sampler_chain_add(smpl, llama_sampler_init_dist (1234));
68
69let n_ctx = llama_n_ctx(context)
70
71print("\nn_len = \(n_len), n_ctx = \(n_ctx), n_batch = \(context_params.n_batch), n_parallel = \(n_parallel), n_kv_req = \(n_kv_req)\n")
72
73if n_kv_req > n_ctx {
74print("error: n_kv_req (%d) > n_ctx, the required KV cache size is not big enough\n", n_kv_req)
75exit(1)
76}
77
78var buffer: [CChar] = []
79for id: llama_token in tokens {
80print(token_to_piece(token: id, buffer: &buffer) ?? "", terminator: "")
81}
82
83print("\n")
84
85var batch = llama_batch_init(max(Int32(tokens.count), Int32(n_parallel)), 0, 1)
86defer {
87llama_batch_free(batch)
88}
89
90// evaluate the initial prompt
91batch.n_tokens = Int32(tokens.count)
92
93for (i, token) in tokens.enumerated() {
94batch.token[i] = token
95batch.pos[i] = Int32(i)
96batch.n_seq_id[i] = 1
97// batch.seq_id[i][0] = 0
98// TODO: is this the proper way to do this?
99if let seq_id = batch.seq_id[i] {
100seq_id[0] = 0
101}
102batch.logits[i] = 0
103}
104
105// llama_decode will output logits only for the last token of the prompt
106batch.logits[Int(batch.n_tokens) - 1] = 1
107
108if llama_decode(context, batch) != 0 {
109print("llama_decode() failed")
110exit(1)
111}
112
113for i in 1 ..< n_parallel {
114llama_kv_cache_seq_cp(context, 0, Int32(i), 0, batch.n_tokens)
115}
116
117if n_parallel > 1 {
118print("generating \(n_parallel) sequences ...\n")
119}
120
121var streams: [String] = .init(repeating: "", count: n_parallel)
122var streamBuffers: [[CChar]] = .init(repeating: [], count: n_parallel)
123var i_batch = [Int32](repeating: batch.n_tokens - 1, count: n_parallel)
124
125var n_cur = batch.n_tokens
126var n_decode = 0
127
128let t_main_start = ggml_time_us()
129
130while n_cur <= n_len {
131// prepare the next batch
132batch.n_tokens = 0
133
134// sample the next token for each parallel sequence / stream
135for i in 0 ..< n_parallel {
136if i_batch[i] < 0 {
137// the stream has already finished
138continue
139}
140
141let new_token_id = llama_sampler_sample(smpl, context, i_batch[i])
142
143// is it an end of stream? -> mark the stream as finished
144if llama_token_is_eog(model, new_token_id) || n_cur == n_len {
145i_batch[i] = -1
146// print("")
147if n_parallel > 1 {
148print("stream \(i) finished at n_cur = \(n_cur)")
149}
150
151continue
152}
153
154let nextStringPiece = token_to_piece(token: new_token_id, buffer: &streamBuffers[i]) ?? ""
155
156// if there is only one stream, we print immediately to stdout
157if n_parallel == 1 {
158print(nextStringPiece, terminator: "")
159}
160streams[i] += nextStringPiece
161
162// push this new token for next evaluation
163batch.token[Int(batch.n_tokens)] = new_token_id
164batch.pos[Int(batch.n_tokens)] = n_cur
165batch.n_seq_id[Int(batch.n_tokens)] = 1
166if let seq_id = batch.seq_id[Int(batch.n_tokens)] {
167seq_id[0] = Int32(i)
168}
169batch.logits[Int(batch.n_tokens)] = 1
170
171i_batch[i] = batch.n_tokens
172
173batch.n_tokens += 1
174
175n_decode += 1
176}
177
178// all streams are finished
179if batch.n_tokens == 0 {
180break
181}
182
183n_cur += 1
184
185// evaluate the current batch with the transformer model
186if llama_decode(context, batch) != 0 {
187print("llama_decode() failed")
188exit(1)
189}
190}
191
192if n_parallel > 1 {
193print("\n")
194for (i, stream) in streams.enumerated() {
195print("sequence \(i):\n\n\(prompt)\(stream)\n")
196}
197}
198
199let t_main_end = ggml_time_us()
200
201print("decoded \(n_decode) tokens in \(String(format: "%.2f", Double(t_main_end - t_main_start) / 1_000_000.0)) s, speed: \(String(format: "%.2f", Double(n_decode) / (Double(t_main_end - t_main_start) / 1_000_000.0))) t/s\n\n")
202
203llama_perf_sampler_print(smpl)
204llama_perf_context_print(context)
205
206private func tokenize(text: String, add_bos: Bool) -> [llama_token] {
207let utf8Count = text.utf8.count
208let n_tokens = utf8Count + (add_bos ? 1 : 0)
209let tokens = UnsafeMutablePointer<llama_token>.allocate(capacity: n_tokens)
210let tokenCount = llama_tokenize(model, text, Int32(utf8Count), tokens, Int32(n_tokens), add_bos, /*special tokens*/ false)
211var swiftTokens: [llama_token] = []
212for i in 0 ..< tokenCount {
213swiftTokens.append(tokens[Int(i)])
214}
215tokens.deallocate()
216return swiftTokens
217}
218
219private func token_to_piece(token: llama_token, buffer: inout [CChar]) -> String? {
220var result = [CChar](repeating: 0, count: 8)
221let nTokens = llama_token_to_piece(model, token, &result, Int32(result.count), 0, false)
222if nTokens < 0 {
223let actualTokensCount = -Int(nTokens)
224result = .init(repeating: 0, count: actualTokensCount)
225let check = llama_token_to_piece(
226model,
227token,
228&result,
229Int32(result.count),
2300,
231false
232)
233assert(check == actualTokensCount)
234} else {
235result.removeLast(result.count - Int(nTokens))
236}
237if buffer.isEmpty, let utfString = String(cString: result + [0], encoding: .utf8) {
238return utfString
239} else {
240buffer.append(contentsOf: result)
241let data = Data(buffer.map { UInt8(bitPattern: $0) })
242if buffer.count >= 4 { // 4 bytes is the max length of a utf8 character so if we're here we need to reset the buffer
243buffer = []
244}
245guard let bufferString = String(data: data, encoding: .utf8) else {
246return nil
247}
248buffer = []
249return bufferString
250}
251}
252