LibLlama.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import Foundation
  2. import llama
  3. enum LlamaError: Error {
  4. case couldNotInitializeContext
  5. }
  6. func llama_batch_clear(_ batch: inout llama_batch) {
  7. batch.n_tokens = 0
  8. }
  9. func llama_batch_add(_ batch: inout llama_batch, _ id: llama_token, _ pos: llama_pos, _ seq_ids: [llama_seq_id], _ logits: Bool) {
  10. batch.token [Int(batch.n_tokens)] = id
  11. batch.pos [Int(batch.n_tokens)] = pos
  12. batch.n_seq_id[Int(batch.n_tokens)] = Int32(seq_ids.count)
  13. for i in 0..<seq_ids.count {
  14. batch.seq_id[Int(batch.n_tokens)]![Int(i)] = seq_ids[i]
  15. }
  16. batch.logits [Int(batch.n_tokens)] = logits ? 1 : 0
  17. batch.n_tokens += 1
  18. }
  19. actor LlamaContext {
  20. private var model: OpaquePointer
  21. private var context: OpaquePointer
  22. private var batch: llama_batch
  23. private var tokens_list: [llama_token]
  24. /// This variable is used to store temporarily invalid cchars
  25. private var temporary_invalid_cchars: [CChar]
  26. var n_len: Int32 = 64
  27. var n_cur: Int32 = 0
  28. var n_decode: Int32 = 0
  29. init(model: OpaquePointer, context: OpaquePointer) {
  30. self.model = model
  31. self.context = context
  32. self.tokens_list = []
  33. self.batch = llama_batch_init(512, 0, 1)
  34. self.temporary_invalid_cchars = []
  35. }
  36. deinit {
  37. llama_batch_free(batch)
  38. llama_free(context)
  39. llama_free_model(model)
  40. llama_backend_free()
  41. }
  42. static func create_context(path: String) throws -> LlamaContext {
  43. llama_backend_init()
  44. var model_params = llama_model_default_params()
  45. #if targetEnvironment(simulator)
  46. model_params.n_gpu_layers = 0
  47. print("Running on simulator, force use n_gpu_layers = 0")
  48. #endif
  49. let model = llama_load_model_from_file(path, model_params)
  50. guard let model else {
  51. print("Could not load model at \(path)")
  52. throw LlamaError.couldNotInitializeContext
  53. }
  54. let n_threads = max(1, min(8, ProcessInfo.processInfo.processorCount - 2))
  55. print("Using \(n_threads) threads")
  56. var ctx_params = llama_context_default_params()
  57. ctx_params.seed = 1234
  58. ctx_params.n_ctx = 2048
  59. ctx_params.n_threads = UInt32(n_threads)
  60. ctx_params.n_threads_batch = UInt32(n_threads)
  61. let context = llama_new_context_with_model(model, ctx_params)
  62. guard let context else {
  63. print("Could not load context!")
  64. throw LlamaError.couldNotInitializeContext
  65. }
  66. return LlamaContext(model: model, context: context)
  67. }
  68. func model_info() -> String {
  69. let result = UnsafeMutablePointer<Int8>.allocate(capacity: 256)
  70. result.initialize(repeating: Int8(0), count: 256)
  71. defer {
  72. result.deallocate()
  73. }
  74. // TODO: this is probably very stupid way to get the string from C
  75. let nChars = llama_model_desc(model, result, 256)
  76. let bufferPointer = UnsafeBufferPointer(start: result, count: Int(nChars))
  77. var SwiftString = ""
  78. for char in bufferPointer {
  79. SwiftString.append(Character(UnicodeScalar(UInt8(char))))
  80. }
  81. return SwiftString
  82. }
  83. func get_n_tokens() -> Int32 {
  84. return batch.n_tokens;
  85. }
  86. func completion_init(text: String) {
  87. print("attempting to complete \"\(text)\"")
  88. tokens_list = tokenize(text: text, add_bos: true)
  89. temporary_invalid_cchars = []
  90. let n_ctx = llama_n_ctx(context)
  91. let n_kv_req = tokens_list.count + (Int(n_len) - tokens_list.count)
  92. print("\n n_len = \(n_len), n_ctx = \(n_ctx), n_kv_req = \(n_kv_req)")
  93. if n_kv_req > n_ctx {
  94. print("error: n_kv_req > n_ctx, the required KV cache size is not big enough")
  95. }
  96. for id in tokens_list {
  97. print(String(cString: token_to_piece(token: id) + [0]))
  98. }
  99. llama_batch_clear(&batch)
  100. for i1 in 0..<tokens_list.count {
  101. let i = Int(i1)
  102. llama_batch_add(&batch, tokens_list[i], Int32(i), [0], false)
  103. }
  104. batch.logits[Int(batch.n_tokens) - 1] = 1 // true
  105. if llama_decode(context, batch) != 0 {
  106. print("llama_decode() failed")
  107. }
  108. n_cur = batch.n_tokens
  109. }
  110. func completion_loop() -> String {
  111. var new_token_id: llama_token = 0
  112. let n_vocab = llama_n_vocab(model)
  113. let logits = llama_get_logits_ith(context, batch.n_tokens - 1)
  114. var candidates = Array<llama_token_data>()
  115. candidates.reserveCapacity(Int(n_vocab))
  116. for token_id in 0..<n_vocab {
  117. candidates.append(llama_token_data(id: token_id, logit: logits![Int(token_id)], p: 0.0))
  118. }
  119. candidates.withUnsafeMutableBufferPointer() { buffer in
  120. var candidates_p = llama_token_data_array(data: buffer.baseAddress, size: buffer.count, sorted: false)
  121. new_token_id = llama_sample_token_greedy(context, &candidates_p)
  122. }
  123. if llama_token_is_eog(model, new_token_id) || n_cur == n_len {
  124. print("\n")
  125. let new_token_str = String(cString: temporary_invalid_cchars + [0])
  126. temporary_invalid_cchars.removeAll()
  127. return new_token_str
  128. }
  129. let new_token_cchars = token_to_piece(token: new_token_id)
  130. temporary_invalid_cchars.append(contentsOf: new_token_cchars)
  131. let new_token_str: String
  132. if let string = String(validatingUTF8: temporary_invalid_cchars + [0]) {
  133. temporary_invalid_cchars.removeAll()
  134. new_token_str = string
  135. } else if (0 ..< temporary_invalid_cchars.count).contains(where: {$0 != 0 && String(validatingUTF8: Array(temporary_invalid_cchars.suffix($0)) + [0]) != nil}) {
  136. // in this case, at least the suffix of the temporary_invalid_cchars can be interpreted as UTF8 string
  137. let string = String(cString: temporary_invalid_cchars + [0])
  138. temporary_invalid_cchars.removeAll()
  139. new_token_str = string
  140. } else {
  141. new_token_str = ""
  142. }
  143. print(new_token_str)
  144. // tokens_list.append(new_token_id)
  145. llama_batch_clear(&batch)
  146. llama_batch_add(&batch, new_token_id, n_cur, [0], true)
  147. n_decode += 1
  148. n_cur += 1
  149. if llama_decode(context, batch) != 0 {
  150. print("failed to evaluate llama!")
  151. }
  152. return new_token_str
  153. }
  154. func bench(pp: Int, tg: Int, pl: Int, nr: Int = 1) -> String {
  155. var pp_avg: Double = 0
  156. var tg_avg: Double = 0
  157. var pp_std: Double = 0
  158. var tg_std: Double = 0
  159. for _ in 0..<nr {
  160. // bench prompt processing
  161. llama_batch_clear(&batch)
  162. let n_tokens = pp
  163. for i in 0..<n_tokens {
  164. llama_batch_add(&batch, 0, Int32(i), [0], false)
  165. }
  166. batch.logits[Int(batch.n_tokens) - 1] = 1 // true
  167. llama_kv_cache_clear(context)
  168. let t_pp_start = ggml_time_us()
  169. if llama_decode(context, batch) != 0 {
  170. print("llama_decode() failed during prompt")
  171. }
  172. llama_synchronize(context)
  173. let t_pp_end = ggml_time_us()
  174. // bench text generation
  175. llama_kv_cache_clear(context)
  176. let t_tg_start = ggml_time_us()
  177. for i in 0..<tg {
  178. llama_batch_clear(&batch)
  179. for j in 0..<pl {
  180. llama_batch_add(&batch, 0, Int32(i), [Int32(j)], true)
  181. }
  182. if llama_decode(context, batch) != 0 {
  183. print("llama_decode() failed during text generation")
  184. }
  185. llama_synchronize(context)
  186. }
  187. let t_tg_end = ggml_time_us()
  188. llama_kv_cache_clear(context)
  189. let t_pp = Double(t_pp_end - t_pp_start) / 1000000.0
  190. let t_tg = Double(t_tg_end - t_tg_start) / 1000000.0
  191. let speed_pp = Double(pp) / t_pp
  192. let speed_tg = Double(pl*tg) / t_tg
  193. pp_avg += speed_pp
  194. tg_avg += speed_tg
  195. pp_std += speed_pp * speed_pp
  196. tg_std += speed_tg * speed_tg
  197. print("pp \(speed_pp) t/s, tg \(speed_tg) t/s")
  198. }
  199. pp_avg /= Double(nr)
  200. tg_avg /= Double(nr)
  201. if nr > 1 {
  202. pp_std = sqrt(pp_std / Double(nr - 1) - pp_avg * pp_avg * Double(nr) / Double(nr - 1))
  203. tg_std = sqrt(tg_std / Double(nr - 1) - tg_avg * tg_avg * Double(nr) / Double(nr - 1))
  204. } else {
  205. pp_std = 0
  206. tg_std = 0
  207. }
  208. let model_desc = model_info();
  209. let model_size = String(format: "%.2f GiB", Double(llama_model_size(model)) / 1024.0 / 1024.0 / 1024.0);
  210. let model_n_params = String(format: "%.2f B", Double(llama_model_n_params(model)) / 1e9);
  211. let backend = "Metal";
  212. let pp_avg_str = String(format: "%.2f", pp_avg);
  213. let tg_avg_str = String(format: "%.2f", tg_avg);
  214. let pp_std_str = String(format: "%.2f", pp_std);
  215. let tg_std_str = String(format: "%.2f", tg_std);
  216. var result = ""
  217. result += String("| model | size | params | backend | test | t/s |\n")
  218. result += String("| --- | --- | --- | --- | --- | --- |\n")
  219. result += String("| \(model_desc) | \(model_size) | \(model_n_params) | \(backend) | pp \(pp) | \(pp_avg_str) ± \(pp_std_str) |\n")
  220. result += String("| \(model_desc) | \(model_size) | \(model_n_params) | \(backend) | tg \(tg) | \(tg_avg_str) ± \(tg_std_str) |\n")
  221. return result;
  222. }
  223. func clear() {
  224. tokens_list.removeAll()
  225. temporary_invalid_cchars.removeAll()
  226. llama_kv_cache_clear(context)
  227. }
  228. private func tokenize(text: String, add_bos: Bool) -> [llama_token] {
  229. let utf8Count = text.utf8.count
  230. let n_tokens = utf8Count + (add_bos ? 1 : 0) + 1
  231. let tokens = UnsafeMutablePointer<llama_token>.allocate(capacity: n_tokens)
  232. let tokenCount = llama_tokenize(model, text, Int32(utf8Count), tokens, Int32(n_tokens), add_bos, false)
  233. var swiftTokens: [llama_token] = []
  234. for i in 0..<tokenCount {
  235. swiftTokens.append(tokens[Int(i)])
  236. }
  237. tokens.deallocate()
  238. return swiftTokens
  239. }
  240. /// - note: The result does not contain null-terminator
  241. private func token_to_piece(token: llama_token) -> [CChar] {
  242. let result = UnsafeMutablePointer<Int8>.allocate(capacity: 8)
  243. result.initialize(repeating: Int8(0), count: 8)
  244. defer {
  245. result.deallocate()
  246. }
  247. let nTokens = llama_token_to_piece(model, token, result, 8, 0, false)
  248. if nTokens < 0 {
  249. let newResult = UnsafeMutablePointer<Int8>.allocate(capacity: Int(-nTokens))
  250. newResult.initialize(repeating: Int8(0), count: Int(-nTokens))
  251. defer {
  252. newResult.deallocate()
  253. }
  254. let nNewTokens = llama_token_to_piece(model, token, newResult, -nTokens, 0, false)
  255. let bufferPointer = UnsafeBufferPointer(start: newResult, count: Int(nNewTokens))
  256. return Array(bufferPointer)
  257. } else {
  258. let bufferPointer = UnsafeBufferPointer(start: result, count: Int(nTokens))
  259. return Array(bufferPointer)
  260. }
  261. }
  262. }