main.swift 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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(false)
  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)
  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.seq_id[i] = 0
  64. batch.logits[i] = 0
  65. }
  66. // llama_decode will output logits only for the last token of the prompt
  67. batch.logits[Int(batch.n_tokens) - 1] = 1
  68. if llama_decode(context, batch) != 0 {
  69. print("llama_decode() failed")
  70. exit(1)
  71. }
  72. for i in 1 ..< n_parallel {
  73. llama_kv_cache_seq_cp(context, 0, Int32(i), 0, batch.n_tokens)
  74. }
  75. if n_parallel > 1 {
  76. print("generating \(n_parallel) sequences ...\n")
  77. }
  78. var streams: [String] = .init(repeating: "", count: n_parallel)
  79. var streamBuffers: [[CChar]] = .init(repeating: [], count: n_parallel)
  80. var i_batch = [Int32](repeating: batch.n_tokens - 1, count: n_parallel)
  81. var n_cur = batch.n_tokens
  82. var n_decode = 0
  83. let t_main_start = ggml_time_us()
  84. while n_cur <= n_len {
  85. // prepare the next batch
  86. batch.n_tokens = 0
  87. // sample the next token for each parallel sequence / stream
  88. for i in 0 ..< n_parallel {
  89. if i_batch[i] < 0 {
  90. // the stream has already finished
  91. continue
  92. }
  93. var n_vocab = llama_n_vocab(model)
  94. var logits = llama_get_logits_ith(context, i_batch[i])
  95. var candidates: [llama_token_data] = .init(repeating: llama_token_data(), count: Int(n_vocab))
  96. for token_id in 0 ..< n_vocab {
  97. candidates.append(llama_token_data(id: token_id, logit: logits![Int(token_id)], p: 0.0))
  98. }
  99. var candidates_p: llama_token_data_array = .init(
  100. data: &candidates,
  101. size: candidates.count,
  102. sorted: false
  103. )
  104. let top_k: Int32 = 40
  105. let top_p: Float = 0.9
  106. let temp: Float = 0.4
  107. llama_sample_top_k(context, &candidates_p, top_k, 1)
  108. llama_sample_top_p(context, &candidates_p, top_p, 1)
  109. llama_sample_temp(context, &candidates_p, temp)
  110. let new_token_id = llama_sample_token(context, &candidates_p)
  111. // const llama_token new_token_id = llama_sample_token_greedy(ctx, &candidates_p);
  112. // is it an end of stream? -> mark the stream as finished
  113. if new_token_id == llama_token_eos(context) || n_cur == n_len {
  114. i_batch[i] = -1
  115. // print("")
  116. if n_parallel > 1 {
  117. print("stream \(i) finished at n_cur = \(n_cur)")
  118. }
  119. continue
  120. }
  121. let nextStringPiece = token_to_piece(token: new_token_id, buffer: &streamBuffers[i]) ?? ""
  122. // if there is only one stream, we print immediately to stdout
  123. if n_parallel == 1 {
  124. print(nextStringPiece, terminator: "")
  125. }
  126. streams[i] += nextStringPiece
  127. // push this new token for next evaluation
  128. batch.token[Int(batch.n_tokens)] = new_token_id
  129. batch.pos[Int(batch.n_tokens)] = n_cur
  130. batch.seq_id[Int(batch.n_tokens)] = Int32(i)
  131. batch.logits[Int(batch.n_tokens)] = 1
  132. i_batch[i] = batch.n_tokens
  133. batch.n_tokens += 1
  134. n_decode += 1
  135. }
  136. // all streams are finished
  137. if batch.n_tokens == 0 {
  138. break
  139. }
  140. n_cur += 1
  141. // evaluate the current batch with the transformer model
  142. if llama_decode(context, batch) != 0 {
  143. print("llama_decode() failed")
  144. exit(1)
  145. }
  146. }
  147. if n_parallel > 1 {
  148. print("\n")
  149. for (i, stream) in streams.enumerated() {
  150. print("sequence \(i):\n\n\(prompt)\(stream)\n")
  151. }
  152. }
  153. let t_main_end = ggml_time_us()
  154. 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")
  155. llama_print_timings(context)
  156. private func tokenize(text: String, add_bos: Bool) -> [llama_token] {
  157. let n_tokens = text.count + (add_bos ? 1 : 0)
  158. let tokens = UnsafeMutablePointer<llama_token>.allocate(capacity: n_tokens)
  159. let tokenCount = llama_tokenize(model, text, Int32(text.count), tokens, Int32(n_tokens), add_bos, /*special tokens*/ false)
  160. var swiftTokens: [llama_token] = []
  161. for i in 0 ..< tokenCount {
  162. swiftTokens.append(tokens[Int(i)])
  163. }
  164. tokens.deallocate()
  165. return swiftTokens
  166. }
  167. private func token_to_piece(token: llama_token, buffer: inout [CChar]) -> String? {
  168. var result = [CChar](repeating: 0, count: 8)
  169. let nTokens = llama_token_to_piece(model, token, &result, Int32(result.count))
  170. if nTokens < 0 {
  171. if result.count >= -Int(nTokens) {
  172. result.removeLast(-Int(nTokens))
  173. } else {
  174. result.removeAll()
  175. }
  176. let check = llama_token_to_piece(
  177. model,
  178. token,
  179. &result,
  180. Int32(result.count)
  181. )
  182. assert(check == nTokens)
  183. } else {
  184. result.removeLast(result.count - Int(nTokens))
  185. }
  186. if buffer.isEmpty, let utfString = String(cString: result + [0], encoding: .utf8) {
  187. return utfString
  188. } else {
  189. buffer.append(contentsOf: result)
  190. let data = Data(buffer.map { UInt8(bitPattern: $0) })
  191. 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
  192. buffer = []
  193. }
  194. guard let bufferString = String(data: data, encoding: .utf8) else {
  195. return nil
  196. }
  197. buffer = []
  198. return bufferString
  199. }
  200. return nil
  201. }