starcoder-mmap.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. #include "ggml/ggml.h"
  2. #include "common.h"
  3. #include "common-ggml.h"
  4. #include <cassert>
  5. #include <cmath>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <fstream>
  9. #include <map>
  10. #include <string>
  11. #include <vector>
  12. #if !defined(_WIN32)
  13. // mmap
  14. #include <sys/types.h>
  15. #include <sys/mman.h>
  16. #include <unistd.h>
  17. #include <fcntl.h>
  18. #else
  19. #define NOMINMAX
  20. #include <Windows.h>
  21. #endif
  22. #ifdef GGML_USE_CUBLAS
  23. #include "ggml-cuda.h"
  24. #endif
  25. #ifdef GGML_USE_CLBLAST
  26. #include "ggml-opencl.h"
  27. #endif
  28. // default hparams (GPT-2 117M)
  29. // https://huggingface.co/bigcode/gpt_bigcode-santacoder/blob/main/config.json
  30. struct starcoder_hparams {
  31. int32_t n_vocab = 49280;
  32. int32_t n_ctx = 2048;
  33. int32_t n_embd = 2048;
  34. int32_t n_head = 16;
  35. int32_t n_layer = 24;
  36. int32_t ftype = 1;
  37. float eps = 1e-5f;
  38. };
  39. struct starcoder_layer {
  40. // normalization
  41. struct ggml_tensor * ln_1_g;
  42. struct ggml_tensor * ln_1_b;
  43. struct ggml_tensor * ln_2_g;
  44. struct ggml_tensor * ln_2_b;
  45. // attention
  46. struct ggml_tensor * c_attn_attn_w;
  47. struct ggml_tensor * c_attn_attn_b;
  48. struct ggml_tensor * c_attn_proj_w;
  49. struct ggml_tensor * c_attn_proj_b;
  50. // mlp
  51. struct ggml_tensor * c_mlp_fc_w;
  52. struct ggml_tensor * c_mlp_fc_b;
  53. struct ggml_tensor * c_mlp_proj_w;
  54. struct ggml_tensor * c_mlp_proj_b;
  55. };
  56. struct llama_buffer {
  57. uint8_t * addr = NULL;
  58. size_t size = 0;
  59. llama_buffer() = default;
  60. void resize(size_t len) {
  61. #ifdef GGML_USE_METAL
  62. free(addr);
  63. int result = posix_memalign((void **) &addr, getpagesize(), len);
  64. if (result == 0) {
  65. memset(addr, 0, len);
  66. }
  67. else {
  68. addr = NULL;
  69. }
  70. #else
  71. delete[] addr;
  72. addr = new uint8_t[len];
  73. #endif
  74. size = len;
  75. }
  76. ~llama_buffer() {
  77. #ifdef GGML_USE_METAL
  78. free(addr);
  79. #else
  80. delete[] addr;
  81. #endif
  82. addr = NULL;
  83. }
  84. // disable copy and move
  85. llama_buffer(const llama_buffer&) = delete;
  86. llama_buffer(llama_buffer&&) = delete;
  87. llama_buffer& operator=(const llama_buffer&) = delete;
  88. llama_buffer& operator=(llama_buffer&&) = delete;
  89. };
  90. struct kv_cache {
  91. struct ggml_tensor * k;
  92. struct ggml_tensor * v;
  93. struct ggml_context * ctx = NULL;
  94. //std::vector<uint8_t> buf;
  95. llama_buffer buf;
  96. int n;
  97. };
  98. struct starcoder_model {
  99. starcoder_hparams hparams;
  100. // normalization
  101. struct ggml_tensor * ln_f_g;
  102. struct ggml_tensor * ln_f_b;
  103. struct ggml_tensor * wte; // position embedding
  104. struct ggml_tensor * wpe; // token embedding
  105. struct ggml_tensor * lm_head; // language model head
  106. std::vector<starcoder_layer> layers;
  107. // key + value memory
  108. //struct ggml_tensor * memory_k;
  109. //struct ggml_tensor * memory_v;
  110. struct kv_cache cache;
  111. // model memory mapped file
  112. void * mm_addr = NULL;
  113. uint64_t mm_length = 0;
  114. //
  115. struct ggml_context * ctx;
  116. std::map<std::string, struct ggml_tensor *> tensors;
  117. };
  118. // From PR #613 (https://github.com/ggerganov/llama.cpp/pull/613)
  119. static void *mmap_file(const char *fname, uint64_t *mm_length) {
  120. #if defined(_WIN32) && !defined(_POSIX_MAPPED_FILES)
  121. HANDLE hFile = CreateFileA(fname,
  122. GENERIC_READ,
  123. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  124. NULL,
  125. OPEN_EXISTING,
  126. FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,
  127. NULL);
  128. if (hFile == INVALID_HANDLE_VALUE) return 0;
  129. LARGE_INTEGER fileSize;
  130. fileSize.QuadPart = -1;
  131. GetFileSizeEx(hFile, &fileSize);
  132. int64_t length = fileSize.QuadPart;
  133. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  134. CloseHandle(hFile);
  135. if (!hMapping) return 0;
  136. void *addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  137. CloseHandle(hMapping);
  138. if (!addr) return 0;
  139. #else
  140. int fd = open(fname, O_RDONLY);
  141. if (fd == -1) return 0;
  142. int64_t length = lseek(fd, 0, SEEK_END);
  143. void *addr = mmap(NULL, length, PROT_READ, MAP_SHARED, fd, 0);
  144. close(fd);
  145. if (addr == MAP_FAILED) return 0;
  146. #endif
  147. *mm_length = length;
  148. return addr;
  149. }
  150. static void munmap_file(void * addr, size_t length) {
  151. #if defined(_WIN32) && !defined(_POSIX_MAPPED_FILES)
  152. UnmapViewOfFile(addr);
  153. #else
  154. munmap(addr, length);
  155. #endif
  156. }
  157. // load the model's weights from a file
  158. bool starcoder_model_load(const std::string & fname, starcoder_model & model, gpt_vocab & vocab, int32_t n_gpu_layers) {
  159. printf("%s: loading model from '%s'\n", __func__, fname.c_str());
  160. auto fin = std::ifstream(fname, std::ios::binary);
  161. if (!fin) {
  162. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
  163. return false;
  164. }
  165. std::vector<char> f_buf(1024*1024);
  166. fin.rdbuf()->pubsetbuf(f_buf.data(), f_buf.size());
  167. // verify magic
  168. {
  169. uint32_t magic;
  170. fin.read((char *) &magic, sizeof(magic));
  171. //if (magic != 0x67676a74) {
  172. if (magic != 0x67676d6c) {
  173. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
  174. return false;
  175. }
  176. }
  177. // load hparams
  178. {
  179. auto & hparams = model.hparams;
  180. fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
  181. fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
  182. fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
  183. fin.read((char *) &hparams.n_head, sizeof(hparams.n_head));
  184. fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
  185. fin.read((char *) &hparams.ftype, sizeof(hparams.ftype));
  186. const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR;
  187. printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
  188. printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
  189. printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
  190. printf("%s: n_head = %d\n", __func__, hparams.n_head);
  191. printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
  192. printf("%s: ftype = %d\n", __func__, hparams.ftype);
  193. printf("%s: qntvr = %d\n", __func__, qntvr);
  194. hparams.ftype %= GGML_QNT_VERSION_FACTOR;
  195. }
  196. // load vocab
  197. {
  198. int32_t n_vocab = 0;
  199. fin.read((char *) &n_vocab, sizeof(n_vocab));
  200. if (n_vocab != model.hparams.n_vocab) {
  201. fprintf(stderr, "%s: invalid model file '%s' (bad vocab size %d != %d)\n",
  202. __func__, fname.c_str(), n_vocab, model.hparams.n_vocab);
  203. return false;
  204. }
  205. std::string word;
  206. std::vector<char> buf(128);
  207. for (int i = 0; i < n_vocab; i++) {
  208. uint32_t len;
  209. fin.read((char *) &len, sizeof(len));
  210. buf.resize(len);
  211. fin.read((char *) buf.data(), len);
  212. word.assign(buf.data(), len);
  213. vocab.token_to_id[word] = i;
  214. vocab.id_to_token[i] = word;
  215. // if (i < 10) fprintf(stderr, "%.s: vocab[%d] = '%s'\n", __func__, i, word.c_str());
  216. }
  217. // Add StarChat special tokens.
  218. for (std::string token : {
  219. "<|system|>",
  220. "<|user|>",
  221. "<|assistant|>",
  222. "<|end|>",
  223. }) {
  224. if (vocab.token_to_id.find(token) != vocab.token_to_id.end()) {
  225. vocab.add_special_token(token);
  226. }
  227. }
  228. }
  229. char *mm_addr = NULL;
  230. model.mm_addr = mmap_file(fname.c_str(), &model.mm_length);
  231. if (model.mm_addr == NULL) {
  232. fprintf(stderr, "%s: failed to mmap '%s'\n", __func__, fname.c_str());
  233. return false;
  234. }
  235. mm_addr = (char *)model.mm_addr;
  236. fprintf(stderr, "%s: ggml map size = %6.2f MB\n", __func__, model.mm_length/(1024.0*1024.0));
  237. // for the big tensors, we have the option to store the data in 16-bit floats or quantized
  238. // in order to save memory and also to speed up the computation
  239. ggml_type wtype = ggml_ftype_to_ggml_type((ggml_ftype) (model.hparams.ftype));
  240. if (wtype == GGML_TYPE_COUNT) {
  241. fprintf(stderr, "%s: invalid model file '%s' (bad ftype value %d)\n",
  242. __func__, fname.c_str(), model.hparams.ftype);
  243. return false;
  244. }
  245. auto & ctx = model.ctx;
  246. size_t ctx_size = 0;
  247. {
  248. const auto & hparams = model.hparams;
  249. const int n_layer = hparams.n_layer;
  250. /*
  251. const int n_embd = hparams.n_embd;
  252. const int n_layer = hparams.n_layer;
  253. const int n_ctx = hparams.n_ctx;
  254. const int n_vocab = hparams.n_vocab;
  255. const int head_dim = n_embd / hparams.n_head;
  256. const int kv_heads = hparams.n_head; // 1 if MQA else hparams.n_head
  257. const int kv_dim = kv_heads * head_dim;
  258. ctx_size += n_embd*ggml_type_sizef(GGML_TYPE_F32); // ln_f_g
  259. ctx_size += n_embd*ggml_type_sizef(GGML_TYPE_F32); // ln_f_b
  260. ctx_size += n_vocab*n_embd*ggml_type_sizef(wtype); // wte
  261. ctx_size += n_ctx*n_embd*ggml_type_sizef(GGML_TYPE_F32); // wpe
  262. ctx_size += n_vocab*n_embd*ggml_type_sizef(wtype); // lm_head
  263. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ln_1_g
  264. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ln_1_b
  265. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ln_2_g
  266. ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ln_2_b
  267. ctx_size += n_layer*((n_embd + 2*kv_dim)*n_embd*ggml_type_sizef(wtype)); // c_attn_attn_w // TODO:
  268. ctx_size += n_layer*( (n_embd + 2*kv_dim)*ggml_type_sizef(GGML_TYPE_F32)); // c_attn_attn_b
  269. ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // c_attn_proj_w
  270. ctx_size += n_layer*( n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_attn_proj_b
  271. ctx_size += n_layer*(4*n_embd*n_embd*ggml_type_sizef(wtype)); // c_mlp_fc_w
  272. ctx_size += n_layer*( 4*n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_mlp_fc_b
  273. ctx_size += n_layer*(4*n_embd*n_embd*ggml_type_sizef(wtype)); // c_mlp_proj_w
  274. ctx_size += n_layer*( n_embd*ggml_type_sizef(GGML_TYPE_F32)); // c_mlp_proj_b
  275. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(GGML_TYPE_F32); // memory_k
  276. ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(GGML_TYPE_F32); // memory_v
  277. */
  278. ctx_size += (6 + 12*n_layer)*512; // object overhead
  279. printf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  280. }
  281. // create the ggml context
  282. {
  283. struct ggml_init_params params = {
  284. /*.mem_size =*/ ctx_size,
  285. /*.mem_buffer =*/ NULL,
  286. /*.no_alloc =*/ true,
  287. };
  288. model.ctx = ggml_init(params);
  289. if (!model.ctx) {
  290. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  291. return false;
  292. }
  293. }
  294. // prepare memory for the weights
  295. {
  296. const auto & hparams = model.hparams;
  297. const int n_embd = hparams.n_embd;
  298. const int n_layer = hparams.n_layer;
  299. const int n_ctx = hparams.n_ctx;
  300. const int n_vocab = hparams.n_vocab;
  301. const int head_dim = n_embd / hparams.n_head;
  302. const int kv_heads = hparams.n_head; // 1 if MQA else hparams.n_head
  303. const int kv_dim = kv_heads * head_dim;
  304. model.layers.resize(n_layer);
  305. model.ln_f_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  306. model.ln_f_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  307. model.wte = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  308. model.wpe = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ctx);
  309. model.lm_head = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
  310. // map by name
  311. model.tensors["model/ln_f/g"] = model.ln_f_g;
  312. model.tensors["model/ln_f/b"] = model.ln_f_b;
  313. model.tensors["model/wte"] = model.wte;
  314. model.tensors["model/wpe"] = model.wpe;
  315. model.tensors["model/lm_head"] = model.lm_head;
  316. for (int i = 0; i < n_layer; ++i) {
  317. auto & layer = model.layers[i];
  318. layer.ln_1_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  319. layer.ln_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  320. layer.ln_2_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  321. layer.ln_2_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  322. layer.c_attn_attn_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd + 2*kv_dim);
  323. layer.c_attn_attn_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd + 2*kv_dim);
  324. layer.c_attn_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
  325. layer.c_attn_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  326. layer.c_mlp_fc_w = ggml_new_tensor_2d(ctx, wtype, n_embd, 4*n_embd); //TODO: 4*n_embd = config.n_inner
  327. layer.c_mlp_fc_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_embd);
  328. layer.c_mlp_proj_w = ggml_new_tensor_2d(ctx, wtype, 4*n_embd, n_embd);
  329. layer.c_mlp_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
  330. // map by name
  331. model.tensors["model/h" + std::to_string(i) + "/ln_1/g"] = layer.ln_1_g;
  332. model.tensors["model/h" + std::to_string(i) + "/ln_1/b"] = layer.ln_1_b;
  333. model.tensors["model/h" + std::to_string(i) + "/ln_2/g"] = layer.ln_2_g;
  334. model.tensors["model/h" + std::to_string(i) + "/ln_2/b"] = layer.ln_2_b;
  335. model.tensors["model/h" + std::to_string(i) + "/attn/c_attn/w"] = layer.c_attn_attn_w;
  336. model.tensors["model/h" + std::to_string(i) + "/attn/c_attn/b"] = layer.c_attn_attn_b;
  337. model.tensors["model/h" + std::to_string(i) + "/attn/c_proj/w"] = layer.c_attn_proj_w;
  338. model.tensors["model/h" + std::to_string(i) + "/attn/c_proj/b"] = layer.c_attn_proj_b;
  339. model.tensors["model/h" + std::to_string(i) + "/mlp/c_fc/w"] = layer.c_mlp_fc_w;
  340. model.tensors["model/h" + std::to_string(i) + "/mlp/c_fc/b"] = layer.c_mlp_fc_b;
  341. model.tensors["model/h" + std::to_string(i) + "/mlp/c_proj/w"] = layer.c_mlp_proj_w;
  342. model.tensors["model/h" + std::to_string(i) + "/mlp/c_proj/b"] = layer.c_mlp_proj_b;
  343. }
  344. }
  345. // key + value memory
  346. {
  347. const auto & hparams = model.hparams;
  348. const int n_embd = hparams.n_embd;
  349. const int n_layer = hparams.n_layer;
  350. const int n_ctx = hparams.n_ctx;
  351. const int n_mem = n_layer*n_ctx;
  352. const int n_elements = n_embd*n_mem;
  353. model.cache.buf.resize(2u*n_elements*ggml_type_size(GGML_TYPE_F16) + 2u*1024*1024);
  354. struct ggml_init_params c_params;
  355. c_params.mem_size = model.cache.buf.size;
  356. c_params.mem_buffer = model.cache.buf.addr;
  357. c_params.no_alloc = false;
  358. model.cache.ctx = ggml_init(c_params);
  359. if (!model.cache.ctx) {
  360. fprintf(stderr, "%s: failed to allocate memory for kv cache\n", __func__);
  361. return false;
  362. }
  363. model.cache.k = ggml_new_tensor_1d(model.cache.ctx, GGML_TYPE_F16, n_elements);
  364. model.cache.v = ggml_new_tensor_1d(model.cache.ctx, GGML_TYPE_F16, n_elements);
  365. const size_t memory_size = ggml_nbytes(model.cache.k) + ggml_nbytes(model.cache.v);
  366. printf("%s: kv_cache memory size = %8.2f MB, n_mem = %d\n", __func__, memory_size/1024.0/1024.0, n_mem);
  367. }
  368. // load weights
  369. {
  370. size_t total_size = 0;
  371. bool has_lm_head = false;
  372. while (true) {
  373. int32_t n_dims;
  374. int32_t length;
  375. int32_t ttype;
  376. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  377. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  378. fin.read(reinterpret_cast<char *>(&ttype), sizeof(ttype));
  379. if (fin.eof()) {
  380. break;
  381. }
  382. int32_t nelements = 1;
  383. int32_t ne[2] = { 1, 1 };
  384. for (int i = 0; i < n_dims; ++i) {
  385. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  386. nelements *= ne[i];
  387. }
  388. std::string name(length, 0);
  389. fin.read(&name[0], length);
  390. if (model.tensors.find(name.data()) == model.tensors.end()) {
  391. fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.data());
  392. return false;
  393. }
  394. auto tensor = model.tensors[name.data()];
  395. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
  396. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  397. __func__, name.data(), (int) tensor->ne[0], (int) tensor->ne[1], ne[0], ne[1]);
  398. return false;
  399. }
  400. if (ggml_nelements(tensor) != nelements) {
  401. fprintf(stderr, "%s: tensor '%s' has wrong size in model file. got %d, expected %d\n",
  402. __func__, name.data(), (int) ggml_nelements(tensor), nelements);
  403. return false;
  404. }
  405. // for debugging
  406. if (0) {
  407. printf("%24s - [%5d, %5d], type = %6s, %6.2f MB, %9zu bytes\n", name.data(), ne[0], ne[1], ggml_type_name(ggml_type(ttype)), ggml_nbytes(tensor)/1024.0/1024.0, ggml_nbytes(tensor));
  408. }
  409. const size_t bpe = ggml_type_size(ggml_type(ttype));
  410. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  411. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  412. __func__, name.data(), ggml_nbytes(tensor), nelements*bpe);
  413. return false;
  414. }
  415. // mmap
  416. size_t offset = fin.tellg();
  417. size_t tensor_data_size = ggml_nbytes(tensor);
  418. //offset = (offset + 31) & -32;
  419. tensor->data = mm_addr + offset;
  420. fin.seekg(offset + tensor_data_size);
  421. total_size += tensor_data_size;
  422. // GPT-2 models share the WTE tensor as the LM head
  423. if (name == "model/wte" && has_lm_head == false) {
  424. // Dont know if this is required, test models have an lm_head
  425. model.lm_head->data = tensor->data;
  426. }
  427. if (name == "model/lm_head") {
  428. has_lm_head = true;
  429. }
  430. }
  431. printf("%s: model size = %8.2f MB\n", __func__, total_size/1024.0/1024.0);
  432. }
  433. fin.close();
  434. #ifdef GGML_USE_CUBLAS
  435. {
  436. const auto & hparams = model.hparams;
  437. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  438. fprintf(stderr, "%s: [cublas] offloading %d layers to GPU\n", __func__, n_gpu);
  439. size_t vram_total = 0;
  440. for (int i = 0; i < n_gpu; ++i) {
  441. const auto & layer = model.layers[i];
  442. layer.c_attn_attn_w->backend = GGML_BACKEND_GPU;
  443. ggml_cuda_transform_tensor((uint8_t *)layer.c_attn_attn_w->data, layer.c_attn_attn_w); vram_total += ggml_nbytes(layer.c_attn_attn_w);
  444. layer.c_attn_proj_w->backend = GGML_BACKEND_GPU;
  445. ggml_cuda_transform_tensor((uint8_t *)layer.c_attn_proj_w->data, layer.c_attn_proj_w); vram_total += ggml_nbytes(layer.c_attn_proj_w);
  446. layer.c_mlp_fc_w->backend = GGML_BACKEND_GPU;
  447. ggml_cuda_transform_tensor((uint8_t *)layer.c_mlp_fc_w->data, layer.c_mlp_fc_w); vram_total += ggml_nbytes(layer.c_mlp_fc_w);
  448. layer.c_mlp_proj_w->backend = GGML_BACKEND_GPU;
  449. ggml_cuda_transform_tensor((uint8_t *)layer.c_mlp_proj_w->data, layer.c_mlp_proj_w); vram_total += ggml_nbytes(layer.c_mlp_proj_w);
  450. }
  451. ggml_cuda_set_scratch_size(0); // disable scratch
  452. //if (n_gpu_layers > (int) hparams.n_layer) {
  453. // fprintf(stderr, "%s: [cublas] offloading output layer to GPU\n", __func__);
  454. // ggml_cuda_transform_tensor(model.output); vram_total += ggml_nbytes(model.output);
  455. //}
  456. fprintf(stderr, "%s: [cublas] total VRAM used: %zu MB\n", __func__, vram_total / 1024 / 1024);
  457. }
  458. #elif defined(GGML_USE_CLBLAST)
  459. //From koboldcpp
  460. {
  461. const auto & hparams = model.hparams;
  462. size_t vram_total = 0;
  463. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  464. fprintf(stderr, "%s: [opencl] offloading %d layers to GPU\n", __func__, n_gpu);
  465. for (int i = 0; i < n_gpu; ++i) {
  466. const auto & layer = model.layers[i];
  467. layer.c_attn_attn_w->backend = GGML_BACKEND_GPU;
  468. layer.c_attn_proj_w->backend = GGML_BACKEND_GPU;
  469. layer.c_mlp_fc_w->backend = GGML_BACKEND_GPU;
  470. layer.c_mlp_proj_w->backend = GGML_BACKEND_GPU;
  471. ggml_cl_transform_tensor(layer.c_attn_attn_w->data,layer.c_attn_attn_w); vram_total += ggml_nbytes(layer.c_attn_attn_w);
  472. ggml_cl_transform_tensor(layer.c_attn_proj_w->data,layer.c_attn_proj_w); vram_total += ggml_nbytes(layer.c_attn_proj_w);
  473. ggml_cl_transform_tensor(layer.c_mlp_fc_w->data,layer.c_mlp_fc_w); vram_total += ggml_nbytes(layer.c_mlp_fc_w);
  474. ggml_cl_transform_tensor(layer.c_mlp_proj_w->data,layer.c_mlp_proj_w); vram_total += ggml_nbytes(layer.c_mlp_proj_w);
  475. }
  476. fprintf(stderr, "%s: [opencl] total VRAM used: %zu MB\n", __func__, vram_total / 1024 / 1024);
  477. }
  478. #endif
  479. return true;
  480. }
  481. // evaluate the transformer
  482. //
  483. // - model: the model
  484. // - n_threads: number of threads to use
  485. // - n_past: the context size so far
  486. // - embd_inp: the embeddings of the tokens in the context
  487. // - embd_w: the predicted logits for the next token
  488. //
  489. bool starcoder_eval(
  490. const starcoder_model & model,
  491. const int n_threads,
  492. const int n_past,
  493. const std::vector<gpt_vocab::id> & embd_inp,
  494. std::vector<float> & embd_w,
  495. size_t & mem_per_token) {
  496. const int N = int(embd_inp.size());
  497. const auto & hparams = model.hparams;
  498. auto & cache = model.cache;
  499. const int n_embd = hparams.n_embd;
  500. const int n_layer = hparams.n_layer;
  501. const int n_ctx = hparams.n_ctx;
  502. const int n_head = hparams.n_head;
  503. const int n_vocab = hparams.n_vocab;
  504. // Scratch is too small for large n_batch (256)
  505. //static size_t buf_size = 256u*1024*1024;
  506. static size_t buf_size = 256u*1024*1024*2;
  507. static void * buf = malloc(buf_size);
  508. // use 2 scratch buffers
  509. // TODO: very hacky solution - reimplement in a more elegant way
  510. static size_t scratch0_size = 256u*1024*1024*2;
  511. static void * scratch0 = malloc(scratch0_size);
  512. static size_t scratch1_size = 256u*1024*1024*2;
  513. static void * scratch1 = malloc(scratch1_size);
  514. if (mem_per_token > 0 && mem_per_token*N > buf_size) {
  515. const size_t buf_size_new = size_t(1.1*(mem_per_token*N)); // add 10% to account for ggml object overhead
  516. printf("\n%s: reallocating buffer from %zu to %zu bytes\n", __func__, buf_size, buf_size_new);
  517. // reallocate
  518. buf_size = buf_size_new;
  519. buf = realloc(buf, buf_size);
  520. if (buf == nullptr) {
  521. fprintf(stderr, "%s: failed to allocate %zu bytes\n", __func__, buf_size);
  522. return false;
  523. }
  524. }
  525. struct ggml_init_params params = {
  526. /*.mem_size =*/ buf_size,
  527. /*.mem_buffer =*/ buf,
  528. /*.no_alloc =*/ false,
  529. };
  530. struct ggml_context * ctx0 = ggml_init(params);
  531. struct ggml_cgraph gf = {};
  532. struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  533. memcpy(embd->data, embd_inp.data(), N*ggml_element_size(embd));
  534. struct ggml_tensor * position = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
  535. for (int i = 0; i < N; ++i) {
  536. ((int32_t *) position->data)[i] = n_past + i;
  537. }
  538. // wte + wpe
  539. struct ggml_tensor * inpL =
  540. ggml_add(ctx0,
  541. ggml_get_rows(ctx0, model.wte, embd),
  542. ggml_get_rows(ctx0, model.wpe, position));
  543. for (int il = 0; il < n_layer; ++il) {
  544. struct ggml_tensor * cur;
  545. ggml_set_scratch(ctx0, { 0, scratch0_size, scratch0, });
  546. // norm
  547. {
  548. // [ 768, N]
  549. cur = ggml_norm(ctx0, inpL, hparams.eps);
  550. // cur = ln_1_g*cur + ln_1_b
  551. // [ 768, N]
  552. cur = ggml_add(ctx0,
  553. ggml_mul(ctx0,
  554. ggml_repeat(ctx0, model.layers[il].ln_1_g, cur),
  555. cur),
  556. ggml_repeat(ctx0, model.layers[il].ln_1_b, cur));
  557. }
  558. // attn
  559. // [2304, 768] - model.layers[il].c_attn_attn_w
  560. // [2304, 1] - model.layers[il].c_attn_attn_b
  561. // [ 768, N] - cur (in)
  562. // [2304, N] - cur (out)
  563. //
  564. // cur = attn_w*cur + attn_b
  565. // [2304, N]
  566. {
  567. cur = ggml_mul_mat(ctx0,
  568. model.layers[il].c_attn_attn_w,
  569. cur);
  570. cur = ggml_add(ctx0,
  571. ggml_repeat(ctx0, model.layers[il].c_attn_attn_b, cur),
  572. cur);
  573. }
  574. // self-attention
  575. {
  576. struct ggml_tensor * Qcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 0*sizeof(float)*n_embd);
  577. struct ggml_tensor * Kcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 1*sizeof(float)*n_embd);
  578. struct ggml_tensor * Vcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 2*sizeof(float)*n_embd);
  579. // store key and value to memory
  580. if (N >= 1) {
  581. struct ggml_tensor * k = ggml_view_1d(ctx0, cache.k, N*n_embd, (ggml_element_size(cache.k)*n_embd)*(il*n_ctx + n_past));
  582. struct ggml_tensor * v = ggml_view_1d(ctx0, cache.v, N*n_embd, (ggml_element_size(cache.v)*n_embd)*(il*n_ctx + n_past));
  583. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
  584. ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
  585. }
  586. // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
  587. // [64, N, 12]
  588. struct ggml_tensor * Q =
  589. ggml_permute(ctx0,
  590. ggml_cpy(ctx0,
  591. Qcur,
  592. ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd/n_head, n_head, N)),
  593. 0, 2, 1, 3);
  594. // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
  595. // [64, n_past + N, 12]
  596. struct ggml_tensor * K =
  597. ggml_permute(ctx0,
  598. ggml_reshape_3d(ctx0,
  599. ggml_view_1d(ctx0, cache.k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(cache.k)*n_embd),
  600. n_embd/n_head, n_head, n_past + N),
  601. 0, 2, 1, 3); //TODO: need to be tiled
  602. // GG: flash attention
  603. //struct ggml_tensor * V =
  604. // ggml_cpy(ctx0,
  605. // ggml_permute(ctx0,
  606. // ggml_reshape_3d(ctx0,
  607. // ggml_view_1d(ctx0, model.memory_v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_v)*n_embd),
  608. // n_embd/n_head, n_head, n_past + N),
  609. // 1, 2, 0, 3),
  610. // ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_past + N, n_embd/n_head, n_head));
  611. //struct ggml_tensor * KQV = ggml_flash_attn(ctx0, Q, K, V, true);
  612. // K * Q
  613. // [n_past + N, N, 12]
  614. struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q); //TODO: check if it broadcasts
  615. // KQ_scaled = KQ / sqrt(n_embd/n_head)
  616. // [n_past + N, N, 12]
  617. struct ggml_tensor * KQ_scaled =
  618. ggml_scale_inplace(ctx0,
  619. KQ,
  620. ggml_new_f32(ctx0, 1.0f/sqrt(float(n_embd)/n_head))
  621. );
  622. // KQ_masked = mask_past(KQ_scaled)
  623. // [n_past + N, N, 12]
  624. struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past);
  625. // KQ = soft_max(KQ_masked)
  626. // [n_past + N, N, 12]
  627. struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked);
  628. // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
  629. // [n_past + N, 64, 12]
  630. struct ggml_tensor * V_trans =
  631. ggml_cpy(ctx0,
  632. ggml_permute(ctx0,
  633. ggml_reshape_3d(ctx0,
  634. ggml_view_1d(ctx0, cache.v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(cache.v)*n_embd),
  635. n_embd/n_head, n_head, n_past + N),
  636. 1, 2, 0, 3),
  637. ggml_new_tensor_3d(ctx0, cache.v->type, n_past + N, n_embd/n_head, n_head));
  638. // KQV = transpose(V) * KQ_soft_max
  639. // [64, N, 12]
  640. struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_trans, KQ_soft_max);
  641. // KQV_merged = KQV.permute(0, 2, 1, 3)
  642. // [64, 12, N]
  643. struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
  644. // cur = KQV_merged.contiguous().view(n_embd, N)
  645. // [768, N]
  646. cur = ggml_cpy(ctx0,
  647. KQV_merged,
  648. ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
  649. }
  650. // projection
  651. // [ 768, 768] - model.layers[il].c_attn_proj_w
  652. // [ 768, 1] - model.layers[il].c_attn_proj_b
  653. // [ 768, N] - cur (in)
  654. // [ 768, N] - cur (out)
  655. //
  656. // cur = proj_w*cur + proj_b
  657. // [768, N]
  658. {
  659. cur = ggml_mul_mat(ctx0,
  660. model.layers[il].c_attn_proj_w,
  661. cur);
  662. cur = ggml_add(ctx0,
  663. ggml_repeat(ctx0, model.layers[il].c_attn_proj_b, cur),
  664. cur);
  665. }
  666. // add the input
  667. cur = ggml_add(ctx0, cur, inpL);
  668. struct ggml_tensor * inpFF = cur;
  669. ggml_set_scratch(ctx0, { 0, scratch1_size, scratch1, });
  670. // feed-forward network
  671. {
  672. // norm
  673. {
  674. cur = ggml_norm(ctx0, inpFF, hparams.eps);
  675. // cur = ln_2_g*cur + ln_2_b
  676. // [ 768, N]
  677. cur = ggml_add(ctx0,
  678. ggml_mul(ctx0,
  679. ggml_repeat(ctx0, model.layers[il].ln_2_g, cur),
  680. cur),
  681. ggml_repeat(ctx0, model.layers[il].ln_2_b, cur));
  682. }
  683. // fully connected
  684. // [3072, 768] - model.layers[il].c_mlp_fc_w
  685. // [3072, 1] - model.layers[il].c_mlp_fc_b
  686. // [ 768, N] - cur (in)
  687. // [3072, N] - cur (out)
  688. //
  689. // cur = fc_w*cur + fc_b
  690. // [3072, N]
  691. cur = ggml_mul_mat(ctx0,
  692. model.layers[il].c_mlp_fc_w,
  693. cur);
  694. cur = ggml_add(ctx0,
  695. ggml_repeat(ctx0, model.layers[il].c_mlp_fc_b, cur),
  696. cur);
  697. // GELU activation
  698. // [3072, N]
  699. cur = ggml_gelu(ctx0, cur);
  700. // projection
  701. // [ 768, 3072] - model.layers[il].c_mlp_proj_w
  702. // [ 768, 1] - model.layers[il].c_mlp_proj_b
  703. // [3072, N] - cur (in)
  704. // [ 768, N] - cur (out)
  705. //
  706. // cur = proj_w*cur + proj_b
  707. // [768, N]
  708. cur = ggml_mul_mat(ctx0,
  709. model.layers[il].c_mlp_proj_w,
  710. cur);
  711. cur = ggml_add(ctx0,
  712. ggml_repeat(ctx0, model.layers[il].c_mlp_proj_b, cur),
  713. cur);
  714. }
  715. // input for next layer
  716. inpL = ggml_add(ctx0, cur, inpFF);
  717. }
  718. ggml_set_scratch(ctx0, { 0, scratch0_size, scratch0, });
  719. // norm
  720. {
  721. // [ 768, N]
  722. inpL = ggml_norm(ctx0, inpL, hparams.eps);
  723. // inpL = ln_f_g*inpL + ln_f_b
  724. // [ 768, N]
  725. inpL = ggml_add(ctx0,
  726. ggml_mul(ctx0,
  727. ggml_repeat(ctx0, model.ln_f_g, inpL),
  728. inpL),
  729. ggml_repeat(ctx0, model.ln_f_b, inpL));
  730. }
  731. ggml_set_scratch(ctx0, { 0, 0, nullptr, });
  732. // inpL = WTE * inpL
  733. // [ 768, 50257] - model.lm_head
  734. // [ 768, N] - inpL
  735. inpL = ggml_mul_mat(ctx0, model.lm_head, inpL);
  736. // logits -> probs
  737. //inpL = ggml_soft_max_inplace(ctx0, inpL);
  738. // run the computation
  739. ggml_build_forward_expand(&gf, inpL);
  740. ggml_graph_compute_with_ctx(ctx0, &gf, n_threads);
  741. //if (n_past%100 == 0) {
  742. // ggml_graph_print (&gf);
  743. // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
  744. //}
  745. //embd_w.resize(n_vocab*N);
  746. //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
  747. // return result just for the last token
  748. embd_w.resize(n_vocab);
  749. memcpy(embd_w.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
  750. if (mem_per_token == 0) {
  751. mem_per_token = ggml_used_mem(ctx0)/N;
  752. }
  753. //printf("used_mem = %zu MB\n", ggml_used_mem(ctx0)/(1024*1024));
  754. ggml_free(ctx0);
  755. return true;
  756. }
  757. int main(int argc, char ** argv) {
  758. ggml_time_init();
  759. const int64_t t_main_start_us = ggml_time_us();
  760. gpt_params params;
  761. params.model = "models/gpt-2-117M/ggml-model.bin";
  762. if (gpt_params_parse(argc, argv, params) == false) {
  763. return 1;
  764. }
  765. if (params.seed < 0) {
  766. params.seed = int(time(NULL));
  767. }
  768. printf("%s: seed = %d\n", __func__, params.seed);
  769. std::mt19937 rng(params.seed);
  770. if (params.prompt.empty()) {
  771. params.prompt = gpt_random_prompt(rng);
  772. }
  773. int64_t t_load_us = 0;
  774. gpt_vocab vocab;
  775. starcoder_model model;
  776. // load the model
  777. {
  778. const int64_t t_start_us = ggml_time_us();
  779. if (!starcoder_model_load(params.model, model, vocab, params.n_gpu_layers)) {
  780. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  781. return 1;
  782. }
  783. t_load_us = ggml_time_us() - t_start_us;
  784. test_gpt_tokenizer(vocab, params.token_test);
  785. }
  786. int n_past = 0;
  787. int64_t t_sample_us = 0;
  788. int64_t t_predict_us = 0;
  789. std::vector<float> logits;
  790. // tokenize the prompt
  791. std::vector<gpt_vocab::id> embd_inp = ::gpt_tokenize(vocab, params.prompt);
  792. params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size());
  793. printf("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  794. printf("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  795. for (size_t i = 0; i < embd_inp.size(); i++) {
  796. printf("%s: token[%zu] = %6d, %s\n", __func__, i, embd_inp[i], vocab.id_to_token.at(embd_inp[i]).c_str());
  797. }
  798. printf("\n\n");
  799. // Handle StarChat "<|end|>" token.
  800. gpt_vocab::id starchat_end_token = -1;
  801. {
  802. const auto it = vocab.token_to_id.find("<|end|>");
  803. if (it != vocab.token_to_id.end()) {
  804. starchat_end_token = it->second;
  805. }
  806. }
  807. // submit the input prompt token-by-token
  808. // this reduces the memory usage during inference, at the cost of a bit of speed at the beginning
  809. std::vector<gpt_vocab::id> embd;
  810. // determine the required inference memory per token:
  811. size_t mem_per_token = 0;
  812. printf("Calling starcoder_eval\n");
  813. starcoder_eval(model, params.n_threads, 0, { 0, 1, 2, 3 }, logits, mem_per_token);
  814. for (size_t i = embd.size(); i < embd_inp.size() + params.n_predict; i++) {
  815. // predict
  816. if (embd.size() > 0) {
  817. const int64_t t_start_us = ggml_time_us();
  818. if (!starcoder_eval(model, params.n_threads, n_past, embd, logits, mem_per_token)) {
  819. printf("Failed to predict\n");
  820. return 1;
  821. }
  822. // Should input processing count towards t_predict?
  823. if (i > embd_inp.size()) {
  824. t_predict_us += ggml_time_us() - t_start_us;
  825. }
  826. }
  827. n_past += int(embd.size());
  828. embd.clear();
  829. if (i >= embd_inp.size()) {
  830. // sample next token
  831. const int top_k = params.top_k;
  832. const float top_p = params.top_p;
  833. const float temp = params.temp;
  834. const int n_vocab = model.hparams.n_vocab;
  835. gpt_vocab::id id = 0;
  836. {
  837. const int64_t t_start_sample_us = ggml_time_us();
  838. id = gpt_sample_top_k_top_p(vocab, logits.data() + (logits.size() - n_vocab), top_k, top_p, temp, rng);
  839. t_sample_us += ggml_time_us() - t_start_sample_us;
  840. }
  841. // add it to the context
  842. embd.push_back(id);
  843. } else {
  844. // if here, it means we are still processing the input prompt
  845. for (size_t k = i; k < embd_inp.size(); k++) {
  846. embd.push_back(embd_inp[k]);
  847. if (int32_t(embd.size()) >= params.n_batch) {
  848. break;
  849. }
  850. }
  851. i += int(embd.size()) - 1;
  852. }
  853. // display text
  854. for (auto id : embd) {
  855. printf("%s", vocab.id_to_token[id].c_str());
  856. }
  857. fflush(stdout);
  858. // check if model is santacoder
  859. if (model.hparams.n_layer <= 30 && embd.back() == 49152) {
  860. break;
  861. }
  862. // check if model is starcoder
  863. else if (embd.back() == 0) { //TODO: this is only for starcoder
  864. break;
  865. }
  866. // Handle StarChat "<|end|>" token.
  867. else if (embd.back() == starchat_end_token) {
  868. //break;
  869. }
  870. }
  871. // report timing
  872. {
  873. const int64_t t_main_end_us = ggml_time_us();
  874. printf("\n\n");
  875. printf("%s: mem per token = %8zu bytes\n", __func__, mem_per_token);
  876. printf("%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f);
  877. printf("%s: sample time = %8.2f ms\n", __func__, t_sample_us/1000.0f);
  878. //Shouldnt the input prompt be subracted?
  879. printf("%s: predict time = %8.2f ms / %.2f ms per token\n", __func__, t_predict_us/1000.0f, t_predict_us/1000.0f/(n_past - embd_inp.size()));
  880. //printf("%s: predict time = %8.2f ms / %.2f ms per token\n", __func__, t_predict_us/1000.0f, t_predict_us/1000.0f/n_past);
  881. printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
  882. }
  883. ggml_free(model.ctx);
  884. if (model.mm_addr) {
  885. munmap_file(model.mm_addr, model.mm_length);
  886. }
  887. return 0;
  888. }