main.swift 7.3 KB

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