LibLlama.swift 11 KB

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