LibLlama.swift 11 KB

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