main.swift 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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_model_load_from_file(modelPath.cString(using: .utf8), model_params) else {
  21. print("Failed to load model")
  22. exit(1)
  23. }
  24. defer {
  25. llama_model_free(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.n_ctx = n_kv_req
  31. context_params.n_batch = UInt32(max(n_len, n_parallel))
  32. context_params.n_threads = 8
  33. context_params.n_threads_batch = 8
  34. let context = llama_new_context_with_model(model, context_params)
  35. guard context != nil else {
  36. print("Failed to initialize context")
  37. exit(1)
  38. }
  39. defer {
  40. llama_free(context)
  41. }
  42. var sparams = llama_sampler_chain_default_params()
  43. let smpl = llama_sampler_chain_init(sparams)
  44. guard smpl != nil else {
  45. print("Failed to initialize sampling")
  46. exit(1)
  47. }
  48. defer {
  49. llama_sampler_free(smpl)
  50. }
  51. llama_sampler_chain_add(smpl, llama_sampler_init_top_k(40));
  52. llama_sampler_chain_add(smpl, llama_sampler_init_top_p(0.9, 1));
  53. llama_sampler_chain_add(smpl, llama_sampler_init_temp (0.4));
  54. llama_sampler_chain_add(smpl, llama_sampler_init_dist (1234));
  55. let n_ctx = llama_n_ctx(context)
  56. 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")
  57. if n_kv_req > n_ctx {
  58. print("error: n_kv_req (%d) > n_ctx, the required KV cache size is not big enough\n", n_kv_req)
  59. exit(1)
  60. }
  61. var buffer: [CChar] = []
  62. for id: llama_token in tokens {
  63. print(token_to_piece(token: id, buffer: &buffer) ?? "", terminator: "")
  64. }
  65. print("\n")
  66. var batch = llama_batch_init(max(Int32(tokens.count), Int32(n_parallel)), 0, 1)
  67. defer {
  68. llama_batch_free(batch)
  69. }
  70. // evaluate the initial prompt
  71. batch.n_tokens = Int32(tokens.count)
  72. for (i, token) in tokens.enumerated() {
  73. batch.token[i] = token
  74. batch.pos[i] = Int32(i)
  75. batch.n_seq_id[i] = 1
  76. // batch.seq_id[i][0] = 0
  77. // TODO: is this the proper way to do this?
  78. if let seq_id = batch.seq_id[i] {
  79. seq_id[0] = 0
  80. }
  81. batch.logits[i] = 0
  82. }
  83. // llama_decode will output logits only for the last token of the prompt
  84. batch.logits[Int(batch.n_tokens) - 1] = 1
  85. if llama_decode(context, batch) != 0 {
  86. print("llama_decode() failed")
  87. exit(1)
  88. }
  89. for i in 1 ..< n_parallel {
  90. llama_kv_cache_seq_cp(context, 0, Int32(i), 0, batch.n_tokens)
  91. }
  92. if n_parallel > 1 {
  93. print("generating \(n_parallel) sequences ...\n")
  94. }
  95. var streams: [String] = .init(repeating: "", count: n_parallel)
  96. var streamBuffers: [[CChar]] = .init(repeating: [], count: n_parallel)
  97. var i_batch = [Int32](repeating: batch.n_tokens - 1, count: n_parallel)
  98. var n_cur = batch.n_tokens
  99. var n_decode = 0
  100. let t_main_start = ggml_time_us()
  101. while n_cur <= n_len {
  102. // prepare the next batch
  103. batch.n_tokens = 0
  104. // sample the next token for each parallel sequence / stream
  105. for i in 0 ..< n_parallel {
  106. if i_batch[i] < 0 {
  107. // the stream has already finished
  108. continue
  109. }
  110. let new_token_id = llama_sampler_sample(smpl, context, i_batch[i])
  111. // is it an end of stream? -> mark the stream as finished
  112. if llama_vocab_is_eog(model, new_token_id) || n_cur == n_len {
  113. i_batch[i] = -1
  114. // print("")
  115. if n_parallel > 1 {
  116. print("stream \(i) finished at n_cur = \(n_cur)")
  117. }
  118. continue
  119. }
  120. let nextStringPiece = token_to_piece(token: new_token_id, buffer: &streamBuffers[i]) ?? ""
  121. // if there is only one stream, we print immediately to stdout
  122. if n_parallel == 1 {
  123. print(nextStringPiece, terminator: "")
  124. }
  125. streams[i] += nextStringPiece
  126. // push this new token for next evaluation
  127. batch.token[Int(batch.n_tokens)] = new_token_id
  128. batch.pos[Int(batch.n_tokens)] = n_cur
  129. batch.n_seq_id[Int(batch.n_tokens)] = 1
  130. if let seq_id = batch.seq_id[Int(batch.n_tokens)] {
  131. seq_id[0] = Int32(i)
  132. }
  133. batch.logits[Int(batch.n_tokens)] = 1
  134. i_batch[i] = batch.n_tokens
  135. batch.n_tokens += 1
  136. n_decode += 1
  137. }
  138. // all streams are finished
  139. if batch.n_tokens == 0 {
  140. break
  141. }
  142. n_cur += 1
  143. // evaluate the current batch with the transformer model
  144. if llama_decode(context, batch) != 0 {
  145. print("llama_decode() failed")
  146. exit(1)
  147. }
  148. }
  149. if n_parallel > 1 {
  150. print("\n")
  151. for (i, stream) in streams.enumerated() {
  152. print("sequence \(i):\n\n\(prompt)\(stream)\n")
  153. }
  154. }
  155. let t_main_end = ggml_time_us()
  156. 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\n")
  157. llama_perf_sampler_print(smpl)
  158. llama_perf_context_print(context)
  159. private func tokenize(text: String, add_bos: Bool) -> [llama_token] {
  160. let utf8Count = text.utf8.count
  161. let n_tokens = utf8Count + (add_bos ? 1 : 0)
  162. let tokens = UnsafeMutablePointer<llama_token>.allocate(capacity: n_tokens)
  163. let tokenCount = llama_tokenize(model, text, Int32(utf8Count), tokens, Int32(n_tokens), add_bos, /*special tokens*/ false)
  164. var swiftTokens: [llama_token] = []
  165. for i in 0 ..< tokenCount {
  166. swiftTokens.append(tokens[Int(i)])
  167. }
  168. tokens.deallocate()
  169. return swiftTokens
  170. }
  171. private func token_to_piece(token: llama_token, buffer: inout [CChar]) -> String? {
  172. var result = [CChar](repeating: 0, count: 8)
  173. let nTokens = llama_token_to_piece(model, token, &result, Int32(result.count), 0, false)
  174. if nTokens < 0 {
  175. let actualTokensCount = -Int(nTokens)
  176. result = .init(repeating: 0, count: actualTokensCount)
  177. let check = llama_token_to_piece(
  178. model,
  179. token,
  180. &result,
  181. Int32(result.count),
  182. 0,
  183. false
  184. )
  185. assert(check == actualTokensCount)
  186. } else {
  187. result.removeLast(result.count - Int(nTokens))
  188. }
  189. if buffer.isEmpty, let utfString = String(cString: result + [0], encoding: .utf8) {
  190. return utfString
  191. } else {
  192. buffer.append(contentsOf: result)
  193. let data = Data(buffer.map { UInt8(bitPattern: $0) })
  194. 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
  195. buffer = []
  196. }
  197. guard let bufferString = String(data: data, encoding: .utf8) else {
  198. return nil
  199. }
  200. buffer = []
  201. return bufferString
  202. }
  203. }