LibLlama.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. if llama_token_is_eog(model, new_token_id) || n_cur == n_len {
  121. print("\n")
  122. is_done = true
  123. let new_token_str = String(cString: temporary_invalid_cchars + [0])
  124. temporary_invalid_cchars.removeAll()
  125. return new_token_str
  126. }
  127. let new_token_cchars = token_to_piece(token: new_token_id)
  128. temporary_invalid_cchars.append(contentsOf: new_token_cchars)
  129. let new_token_str: String
  130. if let string = String(validatingUTF8: temporary_invalid_cchars + [0]) {
  131. temporary_invalid_cchars.removeAll()
  132. new_token_str = string
  133. } else if (0 ..< temporary_invalid_cchars.count).contains(where: {$0 != 0 && String(validatingUTF8: Array(temporary_invalid_cchars.suffix($0)) + [0]) != nil}) {
  134. // in this case, at least the suffix of the temporary_invalid_cchars can be interpreted as UTF8 string
  135. let string = String(cString: temporary_invalid_cchars + [0])
  136. temporary_invalid_cchars.removeAll()
  137. new_token_str = string
  138. } else {
  139. new_token_str = ""
  140. }
  141. print(new_token_str)
  142. // tokens_list.append(new_token_id)
  143. llama_batch_clear(&batch)
  144. llama_batch_add(&batch, new_token_id, n_cur, [0], true)
  145. n_decode += 1
  146. n_cur += 1
  147. if llama_decode(context, batch) != 0 {
  148. print("failed to evaluate llama!")
  149. }
  150. return new_token_str
  151. }
  152. func bench(pp: Int, tg: Int, pl: Int, nr: Int = 1) -> String {
  153. var pp_avg: Double = 0
  154. var tg_avg: Double = 0
  155. var pp_std: Double = 0
  156. var tg_std: Double = 0
  157. for _ in 0..<nr {
  158. // bench prompt processing
  159. llama_batch_clear(&batch)
  160. let n_tokens = pp
  161. for i in 0..<n_tokens {
  162. llama_batch_add(&batch, 0, Int32(i), [0], false)
  163. }
  164. batch.logits[Int(batch.n_tokens) - 1] = 1 // true
  165. llama_kv_cache_clear(context)
  166. let t_pp_start = ggml_time_us()
  167. if llama_decode(context, batch) != 0 {
  168. print("llama_decode() failed during prompt")
  169. }
  170. llama_synchronize(context)
  171. let t_pp_end = ggml_time_us()
  172. // bench text generation
  173. llama_kv_cache_clear(context)
  174. let t_tg_start = ggml_time_us()
  175. for i in 0..<tg {
  176. llama_batch_clear(&batch)
  177. for j in 0..<pl {
  178. llama_batch_add(&batch, 0, Int32(i), [Int32(j)], true)
  179. }
  180. if llama_decode(context, batch) != 0 {
  181. print("llama_decode() failed during text generation")
  182. }
  183. llama_synchronize(context)
  184. }
  185. let t_tg_end = ggml_time_us()
  186. llama_kv_cache_clear(context)
  187. let t_pp = Double(t_pp_end - t_pp_start) / 1000000.0
  188. let t_tg = Double(t_tg_end - t_tg_start) / 1000000.0
  189. let speed_pp = Double(pp) / t_pp
  190. let speed_tg = Double(pl*tg) / t_tg
  191. pp_avg += speed_pp
  192. tg_avg += speed_tg
  193. pp_std += speed_pp * speed_pp
  194. tg_std += speed_tg * speed_tg
  195. print("pp \(speed_pp) t/s, tg \(speed_tg) t/s")
  196. }
  197. pp_avg /= Double(nr)
  198. tg_avg /= Double(nr)
  199. if nr > 1 {
  200. pp_std = sqrt(pp_std / Double(nr - 1) - pp_avg * pp_avg * Double(nr) / Double(nr - 1))
  201. tg_std = sqrt(tg_std / Double(nr - 1) - tg_avg * tg_avg * Double(nr) / Double(nr - 1))
  202. } else {
  203. pp_std = 0
  204. tg_std = 0
  205. }
  206. let model_desc = model_info();
  207. let model_size = String(format: "%.2f GiB", Double(llama_model_size(model)) / 1024.0 / 1024.0 / 1024.0);
  208. let model_n_params = String(format: "%.2f B", Double(llama_model_n_params(model)) / 1e9);
  209. let backend = "Metal";
  210. let pp_avg_str = String(format: "%.2f", pp_avg);
  211. let tg_avg_str = String(format: "%.2f", tg_avg);
  212. let pp_std_str = String(format: "%.2f", pp_std);
  213. let tg_std_str = String(format: "%.2f", tg_std);
  214. var result = ""
  215. result += String("| model | size | params | backend | test | t/s |\n")
  216. result += String("| --- | --- | --- | --- | --- | --- |\n")
  217. result += String("| \(model_desc) | \(model_size) | \(model_n_params) | \(backend) | pp \(pp) | \(pp_avg_str) ± \(pp_std_str) |\n")
  218. result += String("| \(model_desc) | \(model_size) | \(model_n_params) | \(backend) | tg \(tg) | \(tg_avg_str) ± \(tg_std_str) |\n")
  219. return result;
  220. }
  221. func clear() {
  222. tokens_list.removeAll()
  223. temporary_invalid_cchars.removeAll()
  224. llama_kv_cache_clear(context)
  225. }
  226. private func tokenize(text: String, add_bos: Bool) -> [llama_token] {
  227. let utf8Count = text.utf8.count
  228. let n_tokens = utf8Count + (add_bos ? 1 : 0) + 1
  229. let tokens = UnsafeMutablePointer<llama_token>.allocate(capacity: n_tokens)
  230. let tokenCount = llama_tokenize(model, text, Int32(utf8Count), tokens, Int32(n_tokens), add_bos, false)
  231. var swiftTokens: [llama_token] = []
  232. for i in 0..<tokenCount {
  233. swiftTokens.append(tokens[Int(i)])
  234. }
  235. tokens.deallocate()
  236. return swiftTokens
  237. }
  238. /// - note: The result does not contain null-terminator
  239. private func token_to_piece(token: llama_token) -> [CChar] {
  240. let result = UnsafeMutablePointer<Int8>.allocate(capacity: 8)
  241. result.initialize(repeating: Int8(0), count: 8)
  242. defer {
  243. result.deallocate()
  244. }
  245. let nTokens = llama_token_to_piece(model, token, result, 8, 0, false)
  246. if nTokens < 0 {
  247. let newResult = UnsafeMutablePointer<Int8>.allocate(capacity: Int(-nTokens))
  248. newResult.initialize(repeating: Int8(0), count: Int(-nTokens))
  249. defer {
  250. newResult.deallocate()
  251. }
  252. let nNewTokens = llama_token_to_piece(model, token, newResult, -nTokens, 0, false)
  253. let bufferPointer = UnsafeBufferPointer(start: newResult, count: Int(nNewTokens))
  254. return Array(bufferPointer)
  255. } else {
  256. let bufferPointer = UnsafeBufferPointer(start: result, count: Int(nTokens))
  257. return Array(bufferPointer)
  258. }
  259. }
  260. }