main.swift 7.6 KB

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